repo_name
stringlengths 9
109
| hexsha
stringlengths 40
40
| code
stringlengths 547
141k
| apis
sequence | file_path
stringlengths 6
143
| api_extract
stringlengths 142
58.4k
|
---|---|---|---|---|---|
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 tensorflow as tf
def make_parallel(model, gpu_count):
def get_slice(data, idx, parts):
shape = tf.shape(data)
size = tf.concat(0, [shape[:1] // parts, shape[1:]])
stride = tf.concat(0, [shape[:1] // parts, shape[1:] * 0])
start = stride * idx
return tf.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 tf.device('/gpu:%d' % i):
with tf.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 tf.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()
| [
"tensorflow.device",
"tensorflow.concat",
"tensorflow.shape",
"tensorflow.slice",
"sklearn.model_selection.train_test_split",
"numpy.concatenate",
"tensorflow.name_scope",
"numpy.zeros"
] | sdc/detection/cnn_classifier.py | [(22, 'tensorflow.shape', 'tf.shape', (['data'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.concat', 'tf.concat', (['(0)', '[shape[:1] // parts, shape[1:]]'], {}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.concat', 'tf.concat', (['(0)', '[shape[:1] // parts, shape[1:] * 0]'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.slice', 'tf.slice', (['data', 'start', 'size'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (59, 'keras.models.Model', 'Model', ([], {'input': 'model.inputs', 'output': 'merged'}), False, 'from keras.models import Model\n'), (67, 'keras.models.Sequential', 'Sequential', ([], {}), False, 'from keras.models import Sequential\n'), (89, 'keras.models.Sequential', 'Sequential', ([], {}), False, 'from keras.models import Sequential\n'), (132, 'numpy.zeros', 'np.zeros', (['non_vehicles.shape'], {}), True, 'import numpy as np\n'), (133, 'numpy.concatenate', 'np.concatenate', (['(vehicles, non_vehicles)'], {}), True, 'import numpy as np\n'), (134, 'numpy.concatenate', 'np.concatenate', (['(y_vehicles, y_non_vehicles)'], {}), True, 'import numpy as np\n'), (145, 'sklearn.model_selection.train_test_split', 'train_test_split', (['file_list', 'labels'], {'test_size': 'test_size', 'random_state': '(100)'}), False, 'from sklearn.model_selection import train_test_split\n'), (150, 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 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)'}), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), (158, 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), (179, 'cv2.imread', 'cv2.imread', (['img_fname'], {}), False, 'import cv2\n'), (180, 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), False, 'import cv2\n'), (181, 'cv2.resize', 'cv2.resize', (['im', '(64, 64)'], {'interpolation': 'cv2.INTER_AREA'}), False, 'import cv2\n'), (34, 'tensorflow.device', 'tf.device', (["('/gpu:%d' % i)"], {}), True, 'import tensorflow as tf\n'), (69, 'keras.layers.Convolution2D', 'Convolution2D', (['(8)', '(8)', '(8)'], {'subsample': '(4, 4)', 'border_mode': '"""same"""', 'activation': '"""elu"""', 'name': '"""Conv1"""'}), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), (70, 'keras.layers.Convolution2D', 'Convolution2D', (['(16)', '(5)', '(5)'], {'subsample': '(2, 2)', 'border_mode': '"""same"""', 'activation': '"""elu"""', 'name': '"""Conv2"""'}), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), (71, 'keras.layers.Convolution2D', 'Convolution2D', (['(32)', '(5)', '(5)'], {'subsample': '(2, 2)', 'border_mode': '"""same"""', 'activation': '"""elu"""', 'name': '"""Conv3"""'}), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), (72, 'keras.layers.Flatten', 'Flatten', ([], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (73, 'keras.layers.ELU', 'ELU', ([], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (74, 'keras.layers.Dense', 'Dense', (['(1024)'], {'activation': '"""elu"""'}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (75, 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (76, 'keras.layers.ELU', 'ELU', ([], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (77, 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""elu"""'}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (78, 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (79, 'keras.layers.Dense', 'Dense', (['(1)'], {'name': '"""output"""'}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (80, 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (90, 'keras.layers.Convolution2D', 'Convolution2D', (['(8)', '(3)', '(3)'], {'input_shape': '(img_width, img_height, 3)'}), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), (91, 'keras.layers.Activation', 'Activation', (['"""elu"""'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (92, 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), False, 'from keras.layers import Convolution2D, MaxPooling2D\n'), (102, 'keras.layers.Flatten', 'Flatten', ([], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (103, 'keras.layers.Dense', 'Dense', (['(512)'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (104, 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (105, 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""sigmoid"""'}), False, 'from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU\n'), (117, 'json.dump', 'json.dump', (['model_json', 'json_file'], {}), False, 'import json\n'), (129, 'glob.glob', 'glob.glob', (['"""training_data/vehicles/*/*"""'], {}), False, 'import glob\n'), (130, 'numpy.zeros', 'np.zeros', (['vehicles.shape'], {}), True, 'import numpy as np\n'), (131, 'glob.glob', 'glob.glob', (['"""training_data/non-vehicles/*/*"""'], {}), False, 'import glob\n'), (35, 'tensorflow.name_scope', 'tf.name_scope', (["('tower_%d' % i)"], {}), True, 'import tensorflow as tf\n'), (57, 'keras.layers.merge', 'merge', (['outputs'], {'mode': '"""concat"""', 'concat_axis': '(0)'}), False, 'from keras.layers import merge\n'), (123, 'json.load', 'json.load', (['jfile'], {}), False, 'import json\n'), (41, 'keras.layers.core.Lambda', 'Lambda', (['get_slice'], {'output_shape': 'input_shape', 'arguments': "{'idx': i, 'parts': gpu_count}"}), False, 'from keras.layers.core import Lambda\n')] |
LSanselme/kerod | cb52775ed501cbe4bd5fc0f22ec0359ca1d5f902 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
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 = tf.where(indicator)
indices = tf.random.shuffle(indices)
indices = tf.reshape(indices, [-1])
num_samples = tf.minimum(tf.size(indices), num_samples)
selected_indices = tf.slice(indices, [0], tf.reshape(num_samples, [1]))
selected_indicator = ops.indices_to_dense_vector(selected_indices, tf.shape(indicator)[0])
return tf.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 = tf.logical_not(labels)
positive_idx = tf.logical_and(labels, indicator)
negative_idx = tf.logical_and(negative_idx, indicator)
# Sample positive and negative samples separately
if sample_size is None:
max_num_pos = tf.reduce_sum(tf.cast(positive_idx, dtype=tf.int32))
else:
max_num_pos = int(positive_fraction * sample_size)
sampled_pos_idx = subsample_indicator(positive_idx, max_num_pos)
num_sampled_pos = tf.reduce_sum(tf.cast(sampled_pos_idx, tf.int32))
if sample_size is None:
negative_positive_ratio = (1 - positive_fraction) / positive_fraction
max_num_neg = tf.cast(negative_positive_ratio * tf.cast(num_sampled_pos, dtype=tf.float32),
dtype=tf.int32)
else:
max_num_neg = sample_size - num_sampled_pos
sampled_neg_idx = subsample_indicator(negative_idx, max_num_neg)
return tf.logical_or(sampled_pos_idx, sampled_neg_idx)
def batch_sample_balanced_positive_negative(indicators,
sample_size,
labels,
positive_fraction=0.5,
dtype=tf.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(tf.cast(indicators, tf.bool),
sample_size,
tf.cast(targets, tf.bool),
positive_fraction=positive_fraction)
return tf.cast(tf.map_fn(_minibatch_subsample_fn, [indicators, labels],
dtype=tf.bool,
parallel_iterations=16,
back_prop=True),
dtype=dtype)
| [
"tensorflow.shape",
"tensorflow.logical_or",
"tensorflow.reshape",
"tensorflow.equal",
"tensorflow.cast",
"tensorflow.random.shuffle",
"tensorflow.map_fn",
"tensorflow.where",
"tensorflow.logical_not",
"tensorflow.size",
"tensorflow.logical_and"
] | src/kerod/core/sampling_ops.py | [(55, 'tensorflow.where', 'tf.where', (['indicator'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.random.shuffle', 'tf.random.shuffle', (['indices'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.reshape', 'tf.reshape', (['indices', '[-1]'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.equal', 'tf.equal', (['selected_indicator', '(1)'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.logical_not', 'tf.logical_not', (['labels'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.logical_and', 'tf.logical_and', (['labels', 'indicator'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.logical_and', 'tf.logical_and', (['negative_idx', 'indicator'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.logical_or', 'tf.logical_or', (['sampled_pos_idx', 'sampled_neg_idx'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.size', 'tf.size', (['indices'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.reshape', 'tf.reshape', (['num_samples', '[1]'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.cast', 'tf.cast', (['sampled_pos_idx', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.map_fn', 'tf.map_fn', (['_minibatch_subsample_fn', '[indicators, labels]'], {'dtype': 'tf.bool', 'parallel_iterations': '(16)', 'back_prop': '(True)'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.shape', 'tf.shape', (['indicator'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.cast', 'tf.cast', (['positive_idx'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.cast', 'tf.cast', (['indicators', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.cast', 'tf.cast', (['targets', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.cast', 'tf.cast', (['num_sampled_pos'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n')] |
luoyi1hao/ACRN_Chest_X-ray_IA | b2ecaf88e6b1bb59101fd2d611bf9d1e6716367a | from data import DataHandler
from models import ACRegNet
import tensorflow as tf
from utils import get_random_batch, read_config_file, create_dir
RUN_IN_GPU = False
def train_acregnet_model(config):
tf.reset_default_graph()
tf_config = tf.ConfigProto()
if RUN_IN_GPU:
tf_config.gpu_options.allow_growth = True
sess = tf.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')
tf.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)
| [
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"tensorflow.Session"
] | acregnet/train_acregnet.py | [(11, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (12, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.Session', 'tf.Session', ([], {'config': 'tf_config'}), True, 'import tensorflow as tf\n'), (19, 'data.DataHandler.load_images', 'DataHandler.load_images', (["config['train_ims_file']"], {}), False, 'from data import DataHandler\n'), (20, 'data.DataHandler.load_labels', 'DataHandler.load_labels', (["config['train_lbs_file']"], {}), False, 'from data import DataHandler\n'), (23, 'models.ACRegNet', 'ACRegNet', (['sess', 'config', '"""ACRegNet"""'], {'is_train': '(True)'}), False, 'from models import ACRegNet\n'), (40, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (45, 'utils.read_config_file', 'read_config_file', (['"""./config/JSRT/ACRegNet.cfg"""'], {}), False, 'from utils import get_random_batch, read_config_file, create_dir\n'), (46, 'utils.create_dir', 'create_dir', (["config['ckpt_dir']"], {}), False, 'from utils import get_random_batch, read_config_file, create_dir\n'), (28, 'utils.get_random_batch', 'get_random_batch', (['train_ims', "config['batch_size']", 'train_lbs'], {}), False, 'from utils import get_random_batch, read_config_file, create_dir\n')] |
AlexChrisF/udacity | b7f85a74058fc63ccb7601c418450ab934ef5953 | # Copyright 2016 The TensorFlow 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 tf.contrib.layers.sparse_feature_cross."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy
from tensorflow.contrib import layers
from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import sparse_ops
from tensorflow.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.ops.sparse_feature_cross_op.sparse_feature_cross",
"tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense",
"tensorflow.python.platform.test.main",
"tensorflow.python.client.session.Session",
"numpy.equal",
"numpy.not_equal",
"tensorflow.python.framework.constant_op.constant"
] | tensorflow/contrib/layers/python/kernel_tests/sparse_feature_cross_op_test.py | [(437, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (349, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[359], [359 + 1024]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (351, 'tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross', 'sparse_feature_cross_op.sparse_feature_cross', (['[t2, t1]'], {'hashed_output': '(True)', 'num_buckets': '(1024)'}), False, 'from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op\n'), (353, 'tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense', 'sparse_ops.sparse_tensor_to_dense', (['cross'], {}), False, 'from tensorflow.python.ops import sparse_ops\n'), (363, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[359], [359 + 1024]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (365, 'tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_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'}), False, 'from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op\n'), (370, 'tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense', 'sparse_ops.sparse_tensor_to_dense', (['cross'], {}), False, 'from tensorflow.python.ops import sparse_ops\n'), (354, 'tensorflow.python.client.session.Session', 'session.Session', ([], {}), False, 'from tensorflow.python.client import session\n'), (371, 'tensorflow.python.client.session.Session', 'session.Session', ([], {}), False, 'from tensorflow.python.client import session\n'), (433, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['shape', 'dtypes.int64'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (55, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (["[['batch1-FC1-F1', 'batch1-FC1-F2'], ['batch2-FC1-F1', 'batch2-FC1-F2']]", 'dtypes.string'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (58, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (["[['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']]", 'dtypes.string'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (90, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[11, 333], [55555, 999999]]', 'dtypes.int64'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (91, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (["[['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']]", 'dtypes.string'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (111, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (["[['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']]", 'dtypes.string'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (127, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (["[['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']]", 'dtypes.string'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (356, 'numpy.equal', 'numpy.equal', (['values[0]', 'values[1]'], {}), False, 'import numpy\n'), (373, 'numpy.not_equal', 'numpy.not_equal', (['values[0]', 'values[1]'], {}), False, 'import numpy\n')] |
AlexChrisF/udacity | b7f85a74058fc63ccb7601c418450ab934ef5953 | # Copyright 2016 The TensorFlow 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 tensorflow.contrib import layers
from tensorflow.contrib.tensor_forest.hybrid.python import hybrid_layer
from tensorflow.python.framework import ops
from tensorflow.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.python.ops.array_ops.concat",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.python.framework.ops.device"
] | tensorflow/contrib/tensor_forest/hybrid/python/layers/fully_connected.py | [(35, 'tensorflow.python.framework.ops.device', 'ops.device', (['self.device_assigner'], {}), False, 'from tensorflow.python.framework import ops\n'), (37, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['data', 'self.params.layer_size'], {}), False, 'from tensorflow.contrib import layers\n'), (52, 'tensorflow.python.framework.ops.device', 'ops.device', (['self.device_assigner'], {}), False, 'from tensorflow.python.framework import ops\n'), (54, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['data', '(1)'], {}), False, 'from tensorflow.contrib import layers\n'), (58, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['nn_activations'], {'squeeze_dims': '[1]'}), False, 'from tensorflow.python.ops import array_ops\n'), (68, 'tensorflow.python.framework.ops.device', 'ops.device', (['self.device_assigner'], {}), False, 'from tensorflow.python.framework import ops\n'), (79, 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['nn_activations', '(1)'], {'name': '"""flattened_nn_activations"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (41, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['nn_activations', 'self.params.layer_size'], {}), False, 'from tensorflow.contrib import layers\n'), (70, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['data', 'self.params.layer_size'], {}), False, 'from tensorflow.contrib import layers\n'), (75, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['nn_activations[-1]', 'self.params.layer_size'], {}), False, 'from tensorflow.contrib import layers\n')] |
calebchoo/modulabs | 314d9cd9b607460f8bfea80fc828b1521ca18443 | # Copyright 2016 The TensorFlow 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 tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
from tensorflow.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')
| [
"numpy.multiply",
"numpy.arange",
"tensorflow.contrib.learn.python.learn.datasets.base.Datasets",
"numpy.dtype",
"numpy.random.shuffle",
"numpy.frombuffer",
"tensorflow.python.framework.dtypes.as_dtype",
"numpy.zeros",
"tensorflow.python.platform.gfile.Open",
"tensorflow.contrib.learn.python.learn.datasets.base.maybe_download"
] | tensorflow/contrib/learn/python/learn/datasets/mnist.py | [(60, 'numpy.zeros', 'numpy.zeros', (['(num_labels, num_classes)'], {}), False, 'import numpy\n'), (188, 'tensorflow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', (['TRAIN_IMAGES', 'train_dir', '(SOURCE_URL + TRAIN_IMAGES)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (192, 'tensorflow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', (['TRAIN_LABELS', 'train_dir', '(SOURCE_URL + TRAIN_LABELS)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (196, 'tensorflow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', (['TEST_IMAGES', 'train_dir', '(SOURCE_URL + TEST_IMAGES)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (200, 'tensorflow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', (['TEST_LABELS', 'train_dir', '(SOURCE_URL + TEST_LABELS)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (216, 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets', 'base.Datasets', ([], {'train': 'train', 'validation': 'validation', 'test': 'test'}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (42, 'tensorflow.python.platform.gfile.Open', 'gfile.Open', (['filename', '"""rb"""'], {}), False, 'from tensorflow.python.platform import gfile\n'), (42, 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), False, 'import gzip\n'), (51, 'numpy.frombuffer', 'numpy.frombuffer', (['buf'], {'dtype': 'numpy.uint8'}), False, 'import numpy\n'), (59, 'numpy.arange', 'numpy.arange', (['num_labels'], {}), False, 'import numpy\n'), (68, 'tensorflow.python.platform.gfile.Open', 'gfile.Open', (['filename', '"""rb"""'], {}), False, 'from tensorflow.python.platform import gfile\n'), (68, 'gzip.GzipFile', 'gzip.GzipFile', ([], {'fileobj': 'f'}), False, 'import gzip\n'), (75, 'numpy.frombuffer', 'numpy.frombuffer', (['buf'], {'dtype': 'numpy.uint8'}), False, 'import numpy\n'), (180, 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets', 'base.Datasets', ([], {'train': 'train', 'validation': 'validation', 'test': 'test'}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (35, 'numpy.dtype', 'numpy.dtype', (['numpy.uint32'], {}), False, 'import numpy\n'), (95, 'tensorflow.python.framework.dtypes.as_dtype', 'dtypes.as_dtype', (['dtype'], {}), False, 'from tensorflow.python.framework import dtypes\n'), (155, 'numpy.arange', 'numpy.arange', (['self._num_examples'], {}), False, 'import numpy\n'), (156, 'numpy.random.shuffle', 'numpy.random.shuffle', (['perm'], {}), False, 'import numpy\n'), (116, 'numpy.multiply', 'numpy.multiply', (['images', '(1.0 / 255.0)'], {}), False, 'import numpy\n'), (146, 'six.moves.xrange', 'xrange', (['batch_size'], {}), False, 'from six.moves import xrange\n'), (147, 'six.moves.xrange', 'xrange', (['batch_size'], {}), False, 'from six.moves import xrange\n')] |
darkxaze/PINNs | f344a907cf8b585e5f667465178c4442b907024d | """
@author: Maziar Raissi
"""
import sys
#sys.path.insert(0, '../../Utilities/')
sys.path.append('F:/PINNs-master/PINN/src')
import tensorflow as tf
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)
tf.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')
| [
"numpy.asscalar",
"numpy.abs",
"numpy.random.seed",
"numpy.random.choice",
"numpy.linspace",
"numpy.meshgrid",
"numpy.reshape",
"numpy.tile",
"numpy.linalg.norm",
"numpy.std",
"matplotlib.pyplot.subplot",
"numpy.random.randn",
"matplotlib.gridspec.GridSpec",
"tensorflow.set_random_seed",
"numpy.array"
] | mycode/run_NavierStokes.py | [(7, 'sys.path.append', 'sys.path.append', (['"""F:/PINNs-master/PINN/src"""'], {}), False, 'import sys\n'), (21, 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), True, 'import numpy as np\n'), (22, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), True, 'import tensorflow as tf\n'), (54, 'numpy.tile', 'np.tile', (['X_star[:, 0:1]', '(1, T)'], {}), True, 'import numpy as np\n'), (55, 'numpy.tile', 'np.tile', (['X_star[:, 1:2]', '(1, T)'], {}), True, 'import numpy as np\n'), (74, 'numpy.random.choice', 'np.random.choice', (['(N * T)', 'N_train'], {'replace': '(False)'}), True, 'import numpy as np\n'), (86, 'numpy.array', 'np.array', (['[100]'], {}), True, 'import numpy as np\n'), (115, 'plot_sol.plot_solution', 'plot_solution', (['X_star', 'u_pred', '(1)'], {}), False, 'from plot_sol import plot_solution\n'), (116, 'plot_sol.plot_solution', 'plot_solution', (['X_star', 'v_pred', '(2)'], {}), False, 'from plot_sol import plot_solution\n'), (117, 'plot_sol.plot_solution', 'plot_solution', (['X_star', 'p_pred', '(3)'], {}), False, 'from plot_sol import plot_solution\n'), (118, 'plot_sol.plot_solution', 'plot_solution', (['X_star', 'p_star', '(4)'], {}), False, 'from plot_sol import plot_solution\n'), (119, 'plot_sol.plot_solution', 'plot_solution', (['X_star', '(p_star - p_pred)', '(5)'], {}), False, 'from plot_sol import plot_solution\n'), (125, 'numpy.linspace', 'np.linspace', (['lb[0]', 'ub[0]', 'nn'], {}), True, 'import numpy as np\n'), (126, 'numpy.linspace', 'np.linspace', (['lb[1]', 'ub[1]', 'nn'], {}), True, 'import numpy as np\n'), (127, 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), True, 'import numpy as np\n'), (166, 'numpy.asscalar', 'np.asscalar', (["data_vort['modes']"], {}), True, 'import numpy as np\n'), (167, 'numpy.asscalar', 'np.asscalar', (["data_vort['nel']"], {}), True, 'import numpy as np\n'), (169, 'numpy.reshape', 'np.reshape', (['x_vort', '(modes + 1, modes + 1, nel)'], {'order': '"""F"""'}), True, 'import numpy as np\n'), (170, 'numpy.reshape', 'np.reshape', (['y_vort', '(modes + 1, modes + 1, nel)'], {'order': '"""F"""'}), True, 'import numpy as np\n'), (171, 'numpy.reshape', 'np.reshape', (['w_vort', '(modes + 1, modes + 1, nel)'], {'order': '"""F"""'}), True, 'import numpy as np\n'), (173, 'numpy.array', 'np.array', (['[1.0, -2.0]'], {}), True, 'import numpy as np\n'), (174, 'numpy.array', 'np.array', (['[8.0, 2.0]'], {}), True, 'import numpy as np\n'), (176, 'plotting.newfig', 'newfig', (['(1.0)', '(1.2)'], {}), False, 'from plotting import newfig, savefig\n'), (180, 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), True, 'import matplotlib.gridspec as gridspec\n'), (182, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs0[:, :]'], {}), True, 'import matplotlib.pyplot as plt\n'), (186, 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), (203, 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), True, 'import matplotlib.gridspec as gridspec\n'), (205, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[:, (0)]'], {'projection': '"""3d"""'}), True, 'import matplotlib.pyplot as plt\n'), (226, 'axeq3d.axisEqual3D', 'axisEqual3D', (['ax'], {}), False, 'from axeq3d import axisEqual3D\n'), (229, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[:, (1)]'], {'projection': '"""3d"""'}), True, 'import matplotlib.pyplot as plt\n'), (250, 'axeq3d.axisEqual3D', 'axisEqual3D', (['ax'], {}), False, 'from axeq3d import axisEqual3D\n'), (255, 'plotting.newfig', 'newfig', (['(1.015)', '(0.8)'], {}), False, 'from plotting import newfig, savefig\n'), (260, 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), True, 'import matplotlib.gridspec as gridspec\n'), (262, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs2[:, (0)]'], {}), True, 'import matplotlib.pyplot as plt\n'), (266, 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), (276, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs2[:, (1)]'], {}), True, 'import matplotlib.pyplot as plt\n'), (280, 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), (291, 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(2)'], {}), True, 'import matplotlib.gridspec as gridspec\n'), (293, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs3[:, :]'], {}), True, 'import matplotlib.pyplot as plt\n'), (319, 'plotting.savefig', 'savefig', (['"""./figures/NavierStokes_prediction"""'], {}), False, 'from plotting import newfig, savefig\n'), (56, 'numpy.tile', 'np.tile', (['t_star', '(1, N)'], {}), True, 'import numpy as np\n'), (101, 'numpy.linalg.norm', 'np.linalg.norm', (['(u_star - u_pred)', '(2)'], {}), True, 'import numpy as np\n'), (101, 'numpy.linalg.norm', 'np.linalg.norm', (['u_star', '(2)'], {}), True, 'import numpy as np\n'), (102, 'numpy.linalg.norm', 'np.linalg.norm', (['(v_star - v_pred)', '(2)'], {}), True, 'import numpy as np\n'), (102, 'numpy.linalg.norm', 'np.linalg.norm', (['v_star', '(2)'], {}), True, 'import numpy as np\n'), (103, 'numpy.linalg.norm', 'np.linalg.norm', (['(p_star - p_pred)', '(2)'], {}), True, 'import numpy as np\n'), (103, 'numpy.linalg.norm', 'np.linalg.norm', (['p_star', '(2)'], {}), True, 'import numpy as np\n'), (105, 'numpy.abs', 'np.abs', (['(lambda_1_value - 1.0)'], {}), True, 'import numpy as np\n'), (149, 'numpy.abs', 'np.abs', (['(lambda_1_value_noisy - 1.0)'], {}), True, 'import numpy as np\n'), (106, 'numpy.abs', 'np.abs', (['(lambda_2_value - 0.01)'], {}), True, 'import numpy as np\n'), (139, 'numpy.random.randn', 'np.random.randn', (['u_train.shape[0]', 'u_train.shape[1]'], {}), True, 'import numpy as np\n'), (140, 'numpy.random.randn', 'np.random.randn', (['v_train.shape[0]', 'v_train.shape[1]'], {}), True, 'import numpy as np\n'), (150, 'numpy.abs', 'np.abs', (['(lambda_2_value_noisy - 0.01)'], {}), True, 'import numpy as np\n'), (139, 'numpy.std', 'np.std', (['u_train'], {}), True, 'import numpy as np\n'), (140, 'numpy.std', 'np.std', (['v_train'], {}), True, 'import numpy as np\n'), (212, 'itertools.product', 'product', (['r1', 'r2', 'r3'], {}), False, 'from itertools import product, combinations\n'), (236, 'itertools.product', 'product', (['r1', 'r2', 'r3'], {}), False, 'from itertools import product, combinations\n'), (213, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\n'), (213, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\n'), (213, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\n'), (237, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\n'), (237, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\n'), (237, 'numpy.abs', 'np.abs', (['(s - e)'], {}), True, 'import numpy as np\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 tensorflow as tf
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 = tf.image.random_flip_left_right(image)
image_shape = tf.shape(image)
image = tf.pad(
image, [[random_crop_pad, random_crop_pad],
[random_crop_pad, random_crop_pad], [0, 0]],
mode='REFLECT')
image = tf.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 = tf.shape(images)[3]
image_height, image_width = tf.shape(images)[1], tf.shape(images)[2]
cutout_center_height = tf.random.uniform(
shape=[], minval=0, maxval=image_height,
dtype=tf.int32)
cutout_center_width = tf.random.uniform(
shape=[], minval=0, maxval=image_width,
dtype=tf.int32)
lower_pad = tf.maximum(0, cutout_center_height - length // 2)
upper_pad = tf.maximum(0, image_height - cutout_center_height - length // 2)
left_pad = tf.maximum(0, cutout_center_width - length // 2)
right_pad = tf.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 = tf.pad(
tf.zeros(cutout_shape, dtype=images.dtype),
padding_dims, constant_values=1)
patch = tf.ones_like(images, dtype=images.dtype) * replace,
mask = tf.expand_dims(mask, -1)
mask = tf.tile(mask, [1, 1, num_channels])
images = tf.where(
tf.equal(mask, 0),
patch,
images)
images = tf.squeeze(images, axis=0)
return {'image': images, 'label': labels}
| [
"tensorflow.image.random_flip_left_right",
"tensorflow.shape",
"tensorflow.zeros",
"tensorflow.maximum",
"tensorflow.random.uniform",
"tensorflow.equal",
"tensorflow.expand_dims",
"tensorflow.squeeze",
"tensorflow.ones_like",
"tensorflow.image.random_crop",
"tensorflow.pad",
"tensorflow.tile"
] | flax_models/cifar/datasets/augmentation.py | [(28, 'absl.flags.DEFINE_integer', '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"""'], {}), False, 'from absl import flags\n'), (50, 'tensorflow.image.random_flip_left_right', 'tf.image.random_flip_left_right', (['image'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.pad', 'tf.pad', (['image', '[[random_crop_pad, random_crop_pad], [random_crop_pad, random_crop_pad], [0, 0]\n ]'], {'mode': '"""REFLECT"""'}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.image.random_crop', 'tf.image.random_crop', (['image', 'image_shape'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[]', 'minval': '(0)', 'maxval': 'image_height', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[]', 'minval': '(0)', 'maxval': 'image_width', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.maximum', 'tf.maximum', (['(0)', '(cutout_center_height - length // 2)'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.maximum', 'tf.maximum', (['(0)', '(image_height - cutout_center_height - length // 2)'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.maximum', 'tf.maximum', (['(0)', '(cutout_center_width - length // 2)'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.maximum', 'tf.maximum', (['(0)', '(image_width - cutout_center_width - length // 2)'], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask', '(-1)'], {}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.tile', 'tf.tile', (['mask', '[1, 1, num_channels]'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.squeeze', 'tf.squeeze', (['images'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (76, 'flax_models.cifar.datasets.auto_augment.get_autoaugment_fn', 'auto_augment.get_autoaugment_fn', (['dataset_name'], {}), False, 'from flax_models.cifar.datasets import auto_augment\n'), (101, 'tensorflow.shape', 'tf.shape', (['images'], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.zeros', 'tf.zeros', (['cutout_shape'], {'dtype': 'images.dtype'}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.equal', 'tf.equal', (['mask', '(0)'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.shape', 'tf.shape', (['images'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.shape', 'tf.shape', (['images'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.ones_like', 'tf.ones_like', (['images'], {'dtype': 'images.dtype'}), True, 'import tensorflow as tf\n')] |
muchemwal/models | 49fd0a8a61b0e5dab196014bf47de7f62d97c884 | import os
import io
import time
import base64
import functools
from PIL import Image
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from helpers import *
os.environ["TFHUB_DOWNLOAD_PROGRESS"] = "True"
class PythonPredictor:
def __init__(self, config):
# Import TF-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(tf.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.squeeze"
] | tensorflow/super_resolution/syndicai.py | [(20, 'tensorflow_hub.load', 'hub.load', (['"""https://tfhub.dev/captain-pool/esrgan-tf2/1"""'], {}), True, 'import tensorflow_hub as hub\n'), (31, 'io.BytesIO', 'io.BytesIO', ([], {}), False, 'import io\n'), (30, 'tensorflow.squeeze', 'tf.squeeze', (['fake_image'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
flags = tf.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 TF 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.")
tf.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.")
tf.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.")
tf.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.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow 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."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.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 == tf.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 = tf.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():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.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 = tf.reshape(masked_lm_log_probs,
[-1, masked_lm_log_probs.shape[-1]])
masked_lm_predictions = tf.argmax(
masked_lm_log_probs, axis=-1, output_type=tf.int32)
masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1])
masked_lm_ids = tf.reshape(masked_lm_ids, [-1])
masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
masked_lm_accuracy = tf.metrics.accuracy(
labels=masked_lm_ids,
predictions=masked_lm_predictions,
weights=masked_lm_weights)
masked_lm_mean_loss = tf.metrics.mean(
values=masked_lm_example_loss, weights=masked_lm_weights)
next_sentence_log_probs = tf.reshape(
next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]])
next_sentence_predictions = tf.argmax(
next_sentence_log_probs, axis=-1, output_type=tf.int32)
next_sentence_labels = tf.reshape(next_sentence_labels, [-1])
next_sentence_accuracy = tf.metrics.accuracy(
labels=next_sentence_labels, predictions=next_sentence_predictions)
next_sentence_mean_loss = tf.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 = tf.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 tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation before the output layer.
# This matrix is not used after pre-training.
with tf.variable_scope("transform"):
input_tensor = tf.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 = tf.get_variable(
"output_bias",
shape=[bert_config.vocab_size],
initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
label_ids = tf.reshape(label_ids, [-1])
label_weights = tf.reshape(label_weights, [-1])
one_hot_labels = tf.one_hot(
label_ids, depth=bert_config.vocab_size, dtype=tf.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 = -tf.reduce_sum(log_probs * one_hot_labels, axis=[-1])
numerator = tf.reduce_sum(label_weights * per_example_loss)
denominator = tf.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 tf.variable_scope("cls/seq_relationship"):
output_weights = tf.get_variable(
"output_weights",
shape=[2, bert_config.hidden_size],
initializer=modeling.create_initializer(bert_config.initializer_range))
output_bias = tf.get_variable(
"output_bias", shape=[2], initializer=tf.zeros_initializer())
logits = tf.matmul(input_tensor, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
log_probs = tf.nn.log_softmax(logits, axis=-1)
labels = tf.reshape(labels, [-1])
one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.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 = tf.reshape(
tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1])
flat_positions = tf.reshape(positions + flat_offsets, [-1])
flat_sequence_tensor = tf.reshape(sequence_tensor,
[batch_size * seq_length, width])
output_tensor = tf.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":
tf.FixedLenFeature([max_seq_length], tf.int64),
"input_mask":
tf.FixedLenFeature([max_seq_length], tf.int64),
"segment_ids":
tf.FixedLenFeature([max_seq_length], tf.int64),
"masked_lm_positions":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_ids":
tf.FixedLenFeature([max_predictions_per_seq], tf.int64),
"masked_lm_weights":
tf.FixedLenFeature([max_predictions_per_seq], tf.float32),
"next_sentence_labels":
tf.FixedLenFeature([1], tf.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 = tf.data.Dataset.from_tensor_slices(tf.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(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
d = d.shuffle(buffer_size=100)
else:
d = tf.data.TFRecordDataset(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(
tf.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 TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def main(_):
tf.logging.set_verbosity(tf.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)
tf.gfile.MakeDirs(FLAGS.output_dir)
input_files = []
for input_pattern in FLAGS.input_file.split(","):
input_files.extend(tf.gfile.Glob(input_pattern))
tf.logging.info("*** Input Files ***")
for input_file in input_files:
tf.logging.info(" %s" % input_file)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.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=tf.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 = tf.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:
tf.logging.info("***** Running training *****")
tf.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:
tf.logging.info("***** Running evaluation *****")
tf.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 tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.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")
tf.app.run()
| [
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.metrics.accuracy",
"tensorflow.nn.log_softmax",
"tensorflow.FixedLenFeature",
"tensorflow.reduce_sum",
"tensorflow.gfile.GFile",
"tensorflow.train.init_from_checkpoint",
"tensorflow.contrib.data.parallel_interleave",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.gather",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.argmax",
"tensorflow.app.run",
"tensorflow.metrics.mean",
"tensorflow.matmul",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.gfile.Glob",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.nn.bias_add",
"tensorflow.train.Scaffold",
"tensorflow.constant",
"tensorflow.range",
"tensorflow.reduce_mean",
"tensorflow.flags.DEFINE_string",
"tensorflow.reshape",
"tensorflow.variable_scope"
] | training_utility/run_pretraining_adapter.py | [(84, 'tensorflow.flags.DEFINE_string', 'tf.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."""'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.flags.DEFINE_string', 'tf.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."""'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.flags.DEFINE_string', 'tf.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."""'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""master"""', 'None', '"""[Optional] TensorFlow master URL."""'], {}), True, 'import tensorflow as tf\n'), (310, 'retrograph.modeling.modeling_adapter.get_shape_list', 'modeling.get_shape_list', (['sequence_tensor'], {'expected_rank': '(3)'}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (317, 'tensorflow.reshape', 'tf.reshape', (['(positions + flat_offsets)', '[-1]'], {}), True, 'import tensorflow as tf\n'), (318, 'tensorflow.reshape', 'tf.reshape', (['sequence_tensor', '[batch_size * seq_length, width]'], {}), True, 'import tensorflow as tf\n'), (320, 'tensorflow.gather', 'tf.gather', (['flat_sequence_tensor', 'flat_positions'], {}), True, 'import tensorflow as tf\n'), (393, 'tensorflow.parse_single_example', 'tf.parse_single_example', (['record', 'name_to_features'], {}), True, 'import tensorflow as tf\n'), (407, 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), True, 'import tensorflow as tf\n'), (412, 'retrograph.modeling.modeling_adapter.BertConfig.from_json_file', 'modeling.BertConfig.from_json_file', (['FLAGS.bert_config_file'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (414, 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['FLAGS.output_dir'], {}), True, 'import tensorflow as tf\n'), (420, 'tensorflow.logging.info', 'tf.logging.info', (['"""*** Input Files ***"""'], {}), True, 'import tensorflow as tf\n'), (452, 'tensorflow.contrib.tpu.TPUEstimator', 'tf.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'}), True, 'import tensorflow as tf\n'), (494, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.logging.info', 'tf.logging.info', (['"""*** Features ***"""'], {}), True, 'import tensorflow as tf\n'), (131, 'retrograph.modeling.modeling_adapter.BertModel', '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'}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (150, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.logging.info', 'tf.logging.info', (['"""**** Trainable Variables ****"""'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""cls/predictions"""'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.matmul', 'tf.matmul', (['input_tensor', 'output_weights'], {'transpose_b': '(True)'}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['logits', 'output_bias'], {}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.nn.log_softmax', 'tf.nn.log_softmax', (['logits'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['label_ids', '[-1]'], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.reshape', 'tf.reshape', (['label_weights', '[-1]'], {}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.one_hot', 'tf.one_hot', (['label_ids'], {'depth': 'bert_config.vocab_size', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (278, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(label_weights * per_example_loss)'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""cls/seq_relationship"""'], {}), True, 'import tensorflow as tf\n'), (298, 'tensorflow.matmul', 'tf.matmul', (['input_tensor', 'output_weights'], {'transpose_b': '(True)'}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['logits', 'output_bias'], {}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.nn.log_softmax', 'tf.nn.log_softmax', (['logits'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.reshape', 'tf.reshape', (['labels', '[-1]'], {}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.one_hot', 'tf.one_hot', (['labels'], {'depth': '(2)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (304, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['per_example_loss'], {}), True, 'import tensorflow as tf\n'), (422, 'tensorflow.logging.info', 'tf.logging.info', (["(' %s' % input_file)"], {}), True, 'import tensorflow as tf\n'), (426, 'tensorflow.contrib.cluster_resolver.TPUClusterResolver', 'tf.contrib.cluster_resolver.TPUClusterResolver', (['FLAGS.tpu_name'], {'zone': 'FLAGS.tpu_zone', 'project': 'FLAGS.gcp_project'}), True, 'import tensorflow as tf\n'), (460, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Running training *****"""'], {}), True, 'import tensorflow as tf\n'), (461, 'tensorflow.logging.info', 'tf.logging.info', (['""" Batch size = %d"""', 'FLAGS.train_batch_size'], {}), True, 'import tensorflow as tf\n'), (470, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Running evaluation *****"""'], {}), True, 'import tensorflow as tf\n'), (471, 'tensorflow.logging.info', 'tf.logging.info', (['""" Batch size = %d"""', 'FLAGS.eval_batch_size'], {}), True, 'import tensorflow as tf\n'), (482, 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""eval_results.txt"""'], {}), False, 'import os\n'), (119, 'tensorflow.logging.info', 'tf.logging.info', (["(' name = %s, shape = %s' % (name, features[name].shape))"], {}), True, 'import tensorflow as tf\n'), (156, 'retrograph.modeling.modeling_adapter.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['tvars', 'init_checkpoint'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (172, 'tensorflow.logging.info', 'tf.logging.info', (['""" name = %s, shape = %s%s"""', 'var.name', 'var.shape', 'init_string'], {}), True, 'import tensorflow as tf\n'), (177, 'retrograph.modeling.optimization_adapter.create_optimizer', 'optimization.create_optimizer', (['total_loss', 'learning_rate', 'num_train_steps', 'num_warmup_steps', 'use_tpu'], {}), True, 'from retrograph.modeling import optimization_adapter as optimization\n'), (180, 'tensorflow.contrib.tpu.TPUEstimatorSpec', 'tf.contrib.tpu.TPUEstimatorSpec', ([], {'mode': 'mode', 'loss': 'total_loss', 'train_op': 'train_op', 'scaffold_fn': 'scaffold_fn'}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""transform"""'], {}), True, 'import tensorflow as tf\n'), (255, 'retrograph.modeling.modeling_adapter.layer_norm', 'modeling.layer_norm', (['input_tensor'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (277, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(log_probs * one_hot_labels)'], {'axis': '[-1]'}), True, 'import tensorflow as tf\n'), (279, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['label_weights'], {}), True, 'import tensorflow as tf\n'), (303, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(one_hot_labels * log_probs)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (316, 'tensorflow.range', 'tf.range', (['(0)', 'batch_size'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (341, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_predictions_per_seq]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (345, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_predictions_per_seq]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[max_predictions_per_seq]', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[1]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['input_files'], {}), True, 'import tensorflow as tf\n'), (400, 'tensorflow.to_int32', 'tf.to_int32', (['t'], {}), True, 'import tensorflow as tf\n'), (418, 'tensorflow.gfile.Glob', 'tf.gfile.Glob', (['input_pattern'], {}), True, 'import tensorflow as tf\n'), (436, 'tensorflow.contrib.tpu.TPUConfig', 'tf.contrib.tpu.TPUConfig', ([], {'iterations_per_loop': 'FLAGS.iterations_per_loop', 'num_shards': 'FLAGS.num_tpu_cores', 'per_host_input_for_training': 'is_per_host'}), True, 'import tensorflow as tf\n'), (483, 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['output_eval_file', '"""w"""'], {}), True, 'import tensorflow as tf\n'), (484, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Eval results *****"""'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.contrib.tpu.TPUEstimatorSpec', 'tf.contrib.tpu.TPUEstimatorSpec', ([], {'mode': 'mode', 'loss': 'total_loss', 'eval_metrics': 'eval_metrics', 'scaffold_fn': 'scaffold_fn'}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (294, 'retrograph.modeling.modeling_adapter.create_initializer', 'modeling.create_initializer', (['bert_config.initializer_range'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (296, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (355, 'tensorflow.constant', 'tf.constant', (['input_files'], {}), True, 'import tensorflow as tf\n'), (365, 'tensorflow.contrib.data.parallel_interleave', 'tf.contrib.data.parallel_interleave', (['tf.data.TFRecordDataset'], {'sloppy': 'is_training', 'cycle_length': 'cycle_length'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.train.Scaffold', 'tf.train.Scaffold', ([], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.reshape', 'tf.reshape', (['masked_lm_log_probs', '[-1, masked_lm_log_probs.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.argmax', 'tf.argmax', (['masked_lm_log_probs'], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.reshape', 'tf.reshape', (['masked_lm_example_loss', '[-1]'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.reshape', 'tf.reshape', (['masked_lm_ids', '[-1]'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.reshape', 'tf.reshape', (['masked_lm_weights', '[-1]'], {}), True, 'import tensorflow as tf\n'), (198, 'tensorflow.metrics.accuracy', 'tf.metrics.accuracy', ([], {'labels': 'masked_lm_ids', 'predictions': 'masked_lm_predictions', 'weights': 'masked_lm_weights'}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.metrics.mean', 'tf.metrics.mean', ([], {'values': 'masked_lm_example_loss', 'weights': 'masked_lm_weights'}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.reshape', 'tf.reshape', (['next_sentence_log_probs', '[-1, next_sentence_log_probs.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.argmax', 'tf.argmax', (['next_sentence_log_probs'], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.reshape', 'tf.reshape', (['next_sentence_labels', '[-1]'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.metrics.accuracy', 'tf.metrics.accuracy', ([], {'labels': 'next_sentence_labels', 'predictions': 'next_sentence_predictions'}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.metrics.mean', 'tf.metrics.mean', ([], {'values': 'next_sentence_example_loss'}), True, 'import tensorflow as tf\n'), (252, 'retrograph.modeling.modeling_adapter.get_activation', 'modeling.get_activation', (['bert_config.hidden_act'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n'), (253, 'retrograph.modeling.modeling_adapter.create_initializer', 'modeling.create_initializer', (['bert_config.initializer_range'], {}), True, 'from retrograph.modeling import modeling_adapter as modeling\n')] |
pizzahan/lingvo | 9b85b7ba5d037701302efa807841c05223bc7d1d | # -*- coding: utf-8 -*-
# Copyright 2018 The TensorFlow 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 tensorflow as tf
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 tf.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 tf.where(
py_x_ops.token_in_vocab(tokstr, vocab=self._pieces),
py_x_ops.vocab_token_to_id(tokstr, vocab=self._pieces),
tf.broadcast_to(NO_TOKEN, tf.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 UTF-8 characters (letters).
chars = tf.strings.unicode_split(word, 'UTF-8')
tokens = self._StringToToken(chars)
tokens = tf.where(
tf.equal(tokens, NO_TOKEN),
# Unseen character.
tf.broadcast_to(self.unk_id, tf.shape(tokens)),
tokens)
# Create initial candidate list.
candidates = tf.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 tf.logical_and(
tf.reduce_any(tf.not_equal(candidates, NO_TOKEN)),
tf.random.uniform([]) < self._merge_prob)
def _MergeOneToken(tokens, i):
return tf.expand_dims(
self._MergeTokens((tokens[i], tokens[i + 1])), axis=-1)
def _MergeCandidates(tokens, candidates):
"""Merge in the reverse binary tree."""
best_id = tf.argmin(candidates, output_type=tf.int32)
# Perform the merge at position best_id.
tokens = tf.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 = tf.zeros([0], dtype=candidates.dtype)
def _MergeLeft():
return tf.concat(
[candidates[:best_id - 1],
_MergeOneToken(tokens, best_id - 1)],
axis=0)
left_candidates = tf.cond(tf.equal(best_id, 0), lambda: empty, _MergeLeft)
def _MergeRight():
return tf.concat(
[_MergeOneToken(tokens, best_id), candidates[best_id + 2:]], axis=0)
right_candidates = tf.cond(
tf.greater_equal(best_id,
tf.size(tokens) - 1), lambda: empty, _MergeRight)
candidates = tf.concat([left_candidates, right_candidates], axis=0)
return tokens, candidates
return tf.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 = tf.sparse.to_dense(tf.strings.split([text]), default_value='')[0]
num_words = tf.size(words)
ids_ta = tf.TensorArray(tf.int32, 0, dynamic_size=True)
def _WordsToIds(i, words, ids_ta):
encoded_ids = self._EncodeToIds(BOW_STR + words[i])
ids_ta = ids_ta.scatter(
tf.range(ids_ta.size(),
ids_ta.size() + tf.size(encoded_ids)), encoded_ids)
return i + 1, words, ids_ta
_, _, ids_ta = tf.while_loop(
lambda i, *_: i < num_words,
_WordsToIds,
loop_vars=(tf.constant(0, tf.int32), words, ids_ta),
parallel_iterations=30,
back_prop=False)
ids = ids_ta.stack()
return ids, self._TokenToString(ids)
def Decode(self, ids):
txt = tf.strings.reduce_join(self._TokenToString(ids))
txt = tf.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 = tf.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)
| [
"tensorflow.strings.regex_replace",
"tensorflow.not_equal",
"tensorflow.strings.unicode_split",
"tensorflow.concat",
"tensorflow.while_loop",
"tensorflow.gfile.Open",
"tensorflow.TensorArray",
"tensorflow.zeros",
"tensorflow.shape",
"tensorflow.equal",
"tensorflow.strings.split",
"tensorflow.random.uniform",
"tensorflow.constant",
"tensorflow.map_fn",
"tensorflow.strings.strip",
"tensorflow.size",
"tensorflow.argmin"
] | lingvo/core/wpm_encoder.py | [(67, 'lingvo.core.ops.py_x_ops.vocab_id_to_token', 'py_x_ops.vocab_id_to_token', (['token'], {'vocab': 'self._pieces'}), False, 'from lingvo.core.ops import py_x_ops\n'), (87, 'tensorflow.strings.unicode_split', 'tf.strings.unicode_split', (['word', '"""UTF-8"""'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.map_fn', 'tf.map_fn', (['self._MergeTokens', '(tokens[:-1], tokens[1:])'], {'dtype': 'tokens.dtype'}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.size', 'tf.size', (['words'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.TensorArray', 'tf.TensorArray', (['tf.int32', '(0)'], {'dynamic_size': '(True)'}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.strings.regex_replace', 'tf.strings.regex_replace', (['txt', 'BOW_STR', '""" """'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.strings.strip', 'tf.strings.strip', (['txt'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['wpm_filepath', '"""r"""'], {}), True, 'import tensorflow as tf\n'), (71, 'lingvo.core.ops.py_x_ops.token_in_vocab', 'py_x_ops.token_in_vocab', (['tokstr'], {'vocab': 'self._pieces'}), False, 'from lingvo.core.ops import py_x_ops\n'), (72, 'lingvo.core.ops.py_x_ops.vocab_token_to_id', 'py_x_ops.vocab_token_to_id', (['tokstr'], {'vocab': 'self._pieces'}), False, 'from lingvo.core.ops import py_x_ops\n'), (90, 'tensorflow.equal', 'tf.equal', (['tokens', 'NO_TOKEN'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.argmin', 'tf.argmin', (['candidates'], {'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.concat', 'tf.concat', (['[tokens[:best_id], [candidates[best_id]], tokens[best_id + 2:]]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.zeros', 'tf.zeros', (['[0]'], {'dtype': 'candidates.dtype'}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.concat', 'tf.concat', (['[left_candidates, right_candidates]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.while_loop', 'tf.while_loop', (['_ShouldMerge', '_MergeCandidates', '(tokens, candidates)'], {'parallel_iterations': '(1)', 'back_prop': '(False)'}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.shape', 'tf.shape', (['tokstr'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.shape', 'tf.shape', (['tokens'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.equal', 'tf.equal', (['best_id', '(0)'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.strings.split', 'tf.strings.split', (['[text]'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.not_equal', 'tf.not_equal', (['candidates', 'NO_TOKEN'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.random.uniform', 'tf.random.uniform', (['[]'], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.size', 'tf.size', (['tokens'], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.size', 'tf.size', (['encoded_ids'], {}), True, 'import tensorflow as tf\n')] |
pizzahan/lingvo | 9b85b7ba5d037701302efa807841c05223bc7d1d | # Copyright 2018 The TensorFlow 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 tensorflow as tf
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 tf.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 tf.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 = tf.stack(transformer_output, 3)
return transformer_output, paddings, src_segment_id
| [
"tensorflow.variable_scope",
"tensorflow.stack",
"tensorflow.name_scope"
] | lingvo/tasks/mt/layers.py | [(45, 'lingvo.core.layers_with_attention.TransformerLayer.Params', 'layers_with_attention.TransformerLayer.Params', ([], {}), False, 'from lingvo.core import layers_with_attention\n'), (48, 'lingvo.core.layers.LayerNorm.Params', 'layers.LayerNorm.Params', ([], {}), False, 'from lingvo.core import layers\n'), (73, 'tensorflow.variable_scope', 'tf.variable_scope', (['p.name'], {}), True, 'import tensorflow as tf\n'), (76, 'six.moves.range', 'range', (['p.num_transformer_layers'], {}), False, 'from six.moves import range\n'), (145, 'tensorflow.name_scope', 'tf.name_scope', (['p.name'], {}), True, 'import tensorflow as tf\n'), (98, 'six.moves.range', 'range', (['p.num_transparent_outputs'], {}), False, 'from six.moves import range\n'), (58, 'lingvo.core.layers.WeightedSumLayer.Params', 'layers.WeightedSumLayer.Params', ([], {}), False, 'from lingvo.core import layers\n'), (174, 'six.moves.range', 'range', (['p.num_transparent_outputs'], {}), False, 'from six.moves import range\n'), (179, 'tensorflow.stack', 'tf.stack', (['transformer_output', '(3)'], {}), True, 'import tensorflow as tf\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 tensorflow.python.framework import ops
import keras.backend as K
import tensorflow as tf
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 tf.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 * tf.cast(grad > 0., dtype) * \
tf.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 = tf.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 = tf.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 = tf.gradients(tensor, var_list)
return [grad if grad is not None else tf.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))
| [
"numpy.expand_dims",
"numpy.maximum",
"numpy.minimum",
"tensorflow.python.framework.ops.RegisterGradient",
"numpy.clip",
"numpy.min",
"numpy.uint8",
"numpy.squeeze",
"tensorflow.cast",
"tensorflow.gradients",
"numpy.ones",
"numpy.ndim",
"numpy.max",
"tensorflow.zeros_like",
"numpy.mean",
"numpy.float32",
"tensorflow.get_default_graph"
] | grad-cam_5category.py | [(136, 'keras.applications.vgg16.VGG16', 'VGG16', ([], {'weights': '"""imagenet"""'}), False, 'from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\n'), (34, 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), True, 'import numpy as np\n'), (35, 'keras.applications.vgg16.preprocess_input', 'preprocess_input', (['x'], {}), False, 'from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\n'), (51, 'keras.backend.max', 'K.max', (['layer_output'], {'axis': '(3)'}), True, 'import keras.backend as K\n'), (56, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (88, 'numpy.clip', 'np.clip', (['x', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (98, 'tensorflow.gradients', 'tf.gradients', (['tensor', 'var_list'], {}), True, 'import tensorflow as tf\n'), (105, 'keras.models.Model', 'Model', ([], {'inputs': 'input_model.input', 'outputs': 'x'}), False, 'from keras.models import Model\n'), (107, 'keras.backend.sum', 'K.sum', (['model.output'], {}), True, 'import keras.backend as K\n'), (110, 'keras.backend.function', 'K.function', (['[model.input]', '[conv_output, grads]'], {}), True, 'import keras.backend as K\n'), (115, 'numpy.mean', 'np.mean', (['grads_val'], {'axis': '(0, 1)'}), True, 'import numpy as np\n'), (116, 'numpy.ones', 'np.ones', (['output.shape[0:2]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (121, 'cv2.resize', 'cv2.resize', (['cam', '(224, 224)'], {}), False, 'import cv2\n'), (122, 'numpy.maximum', 'np.maximum', (['cam', '(0)'], {}), True, 'import numpy as np\n'), (127, 'numpy.min', 'np.min', (['image'], {}), True, 'import numpy as np\n'), (128, 'numpy.minimum', 'np.minimum', (['image', '(255)'], {}), True, 'import numpy as np\n'), (21, 'keras.backend.one_hot', 'K.one_hot', (['[category_index]', 'nb_classes'], {}), True, 'import keras.backend as K\n'), (40, 'tensorflow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', (['"""GuidedBackProp"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (69, 'keras.applications.vgg16.VGG16', 'VGG16', ([], {'weights': '"""imagenet"""'}), False, 'from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\n'), (79, 'numpy.ndim', 'np.ndim', (['x'], {}), True, 'import numpy as np\n'), (80, 'numpy.squeeze', 'np.squeeze', (['x'], {}), True, 'import numpy as np\n'), (92, 'keras.backend.image_dim_ordering', 'K.image_dim_ordering', ([], {}), True, 'import keras.backend as K\n'), (104, 'keras.layers.core.Lambda', 'Lambda', (['target_layer'], {'output_shape': 'target_category_loss_output_shape'}), False, 'from keras.layers.core import Lambda\n'), (123, 'numpy.max', 'np.max', (['cam'], {}), True, 'import numpy as np\n'), (130, 'numpy.uint8', 'np.uint8', (['(255 * heatmap)'], {}), True, 'import numpy as np\n'), (131, 'numpy.float32', 'np.float32', (['cam'], {}), True, 'import numpy as np\n'), (131, 'numpy.float32', 'np.float32', (['image'], {}), True, 'import numpy as np\n'), (132, 'numpy.max', 'np.max', (['cam'], {}), True, 'import numpy as np\n'), (133, 'numpy.uint8', 'np.uint8', (['cam'], {}), True, 'import numpy as np\n'), (52, 'keras.backend.sum', 'K.sum', (['max_output'], {}), True, 'import keras.backend as K\n'), (53, 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), True, 'import keras.backend as K\n'), (94, 'numpy.clip', 'np.clip', (['x', '(0)', '(255)'], {}), True, 'import numpy as np\n'), (99, 'tensorflow.zeros_like', 'tf.zeros_like', (['var'], {}), True, 'import tensorflow as tf\n'), (148, 'keras.applications.vgg16.decode_predictions', 'decode_predictions', (['predictions'], {}), False, 'from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\n'), (44, 'tensorflow.cast', 'tf.cast', (['(op.inputs[0] > 0.0)', 'dtype'], {}), True, 'import tensorflow as tf\n'), (28, 'keras.backend.square', 'K.square', (['x'], {}), True, 'import keras.backend as K\n'), (43, 'tensorflow.cast', 'tf.cast', (['(grad > 0.0)', 'dtype'], {}), True, 'import tensorflow as tf\n')] |
xuyuandong/sequence_behavior_ctr_model | e1bb71b4579456b1c6fbf3b432a84a3cb52611b7 | import tensorflow as tf
#from tensorflow.python.ops.rnn_cell import *
#from tensorflow.python.ops.rnn_cell_impl import _Linear
from tensorflow.contrib.rnn.python.ops.core_rnn_cell import *
#from tensorflow import keras
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import array_ops
from tensorflow.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 = tf.concat(facts, 2)
print ("query_size mismatch")
query = tf.concat(values = [
query,
query,
], axis=1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.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 = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
if mask is not None:
mask = tf.equal(mask, tf.ones_like(mask))
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.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 tf.variable_scope(name_or_scope=scope, default_name="prelu"):
_alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1],
dtype=_x.dtype, initializer=tf.constant_initializer(0.1))
return tf.maximum(0.0, _x) + _alpha * tf.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 = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.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 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
b = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
with tf.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 = tf.tensordot(facts, w1, axes=1)
tmp2 = tf.tensordot(query, w2, axes=1)
tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]])
tmp = tf.tanh((tmp1 + tmp2) + b)
# For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector
v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.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 = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.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 = tf.concat(facts, 2)
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.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 = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
if mask is not None:
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.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 = tf.expand_dims(facts, 1)
def cond(batch, output, i):
return tf.less(i, tf.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 = tf.reduce_sum(self_attention_tmp, 1)
output = output.write(i, self_attention_tmp)
return batch, output, i + 1
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.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 = tf.expand_dims(facts, 1)
def cond(batch, output, i):
return tf.less(i, tf.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 = tf.reduce_sum(self_attention_tmp, 1)
output = output.write(i, self_attention_tmp)
return batch, output, i + 1
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.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 = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.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 = tf.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, facts_size, activation=tf.nn.sigmoid, name='f1_shine_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, facts_size, activation=tf.nn.sigmoid, name='f2_shine_att' + stag)
d_layer_2_all = tf.reshape(d_layer_2_all, tf.shape(facts))
output = d_layer_2_all
return output
| [
"tensorflow.concat",
"tensorflow.python.ops.array_ops.split",
"tensorflow.reduce_sum",
"tensorflow.minimum",
"tensorflow.tanh",
"tensorflow.where",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.while_loop",
"tensorflow.layers.dense",
"tensorflow.name_scope",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.tensordot",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.maximum",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.array_ops.transpose",
"tensorflow.random_normal"
] | script/utils.py | [(29, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', '(80)'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_att' + stag)"}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', '(40)'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_att' + stag)"}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_2_all', '(1)'], {'activation': 'None', 'name': "('f3_att' + stag)"}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.tensordot', 'tf.tensordot', (['tmp', 'v'], {'axes': '(1)', 'name': '"""v_dot_tmp"""'}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.where', 'tf.where', (['key_masks', 'v_dot_tmp', 'paddings'], {}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['v_dot_tmp'], {'name': '"""alphas"""'}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.layers.dense', 'tf.layers.dense', (['query', 'facts_size'], {'activation': 'None', 'name': "('f1' + stag)"}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', '(80)'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_att' + stag)"}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', '(40)'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_att' + stag)"}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_2_all', '(1)'], {'activation': 'None', 'name': "('f3_att' + stag)"}), True, 'import tensorflow as tf\n'), (315, 'tensorflow.while_loop', 'tf.while_loop', (['cond', 'body', '[facts, output_ta, 0]'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.transpose', 'tf.transpose', (['self_attention'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.while_loop', 'tf.while_loop', (['cond', 'body', '[facts, output_ta, 0]'], {}), True, 'import tensorflow as tf\n'), (341, 'tensorflow.transpose', 'tf.transpose', (['self_attention'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.layers.dense', 'tf.layers.dense', (['query', 'facts_size'], {'activation': 'None', 'name': "('f1_trans_shine' + stag)"}), True, 'import tensorflow as tf\n'), (360, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (361, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', 'facts_size'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_shine_att' + stag)"}), True, 'import tensorflow as tf\n'), (362, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', 'facts_size'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_shine_att' + stag)"}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.concat', 'tf.concat', ([], {'values': '[query, query]', 'axis': '(1)'}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask', '(1)'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.where', 'tf.where', (['key_masks', 'scores', 'paddings'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scores'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.matmul', 'tf.matmul', (['scores', 'facts'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.python.ops.array_ops.split', 'array_ops.split', ([], {'value': 'value', 'num_or_size_splits': '(2)', 'axis': '(1)'}), False, 'from tensorflow.python.ops import array_ops\n'), (130, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'scope', 'default_name': '"""prelu"""'}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.random_normal', 'tf.random_normal', (['[hidden_size, attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.random_normal', 'tf.random_normal', (['[input_size, attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.random_normal', 'tf.random_normal', (['[attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.random_normal', 'tf.random_normal', (['[attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.name_scope', 'tf.name_scope', (['"""v"""'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.tensordot', 'tf.tensordot', (['facts', 'w1'], {'axes': '(1)'}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.tensordot', 'tf.tensordot', (['query', 'w2'], {'axes': '(1)'}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.tanh', 'tf.tanh', (['(tmp1 + tmp2 + b)'], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.ones_like', 'tf.ones_like', (['v_dot_tmp'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.expand_dims', 'tf.expand_dims', (['alphas', '(-1)'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (249, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (272, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask', '(1)'], {}), True, 'import tensorflow as tf\n'), (282, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scores'], {}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.matmul', 'tf.matmul', (['scores', 'facts'], {}), True, 'import tensorflow as tf\n'), (298, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (307, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self_attention_tmp', '(1)'], {}), True, 'import tensorflow as tf\n'), (322, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (331, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self_attention_tmp', '(1)'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (351, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (353, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (359, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.ones_like', 'tf.ones_like', (['scores'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.expand_dims', 'tf.expand_dims', (['scores', '(-1)'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.maximum', 'tf.maximum', (['(0.0)', '_x'], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.ones_like', 'tf.ones_like', (['scores'], {}), True, 'import tensorflow as tf\n'), (275, 'tensorflow.where', 'tf.where', (['key_masks', 'scores', 'paddings'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.expand_dims', 'tf.expand_dims', (['scores', '(-1)'], {}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', (['(1.0)'], {'dtype': 'inputs.dtype'}), False, 'from tensorflow.python.ops import init_ops\n'), (103, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""gates"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (116, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""candidate"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (132, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.minimum', 'tf.minimum', (['(0.0)', '_x'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.shape', 'tf.shape', (['batch'], {}), True, 'import tensorflow as tf\n'), (325, 'tensorflow.shape', 'tf.shape', (['batch'], {}), True, 'import tensorflow as tf\n'), (358, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.shape', 'tf.shape', (['tmp2'], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n')] |
omshinde/dfc2019 | 2e48cc8442c2c33aef7e1a0de27041709ef160e8 | from toposort import toposort
import contextlib
import numpy as np
import tensorflow as tf
import tensorflow.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:tensorflow:VARIABLES collection name is deprecated"
setattr(tf.GraphKeys, "VARIABLES", "variables")
# save original gradients since tf.gradient could be monkey-patched to point
# to our version
from tensorflow.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 tf.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 tensorflow tf.gradients
(https://www.tensorflow.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 tensorflow 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 = tf.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): # tf.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 = tf.stop_gradient(x, name=x.op.name+"_sg")
else:
grad_node = tf.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, tf.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 = tf.expand_dims(indices, -1)
return tf.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 tf.name_scope(scope_name):
yield op_list
g = tf.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 TensorFlow 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)
| [
"tensorflow.get_default_graph",
"tensorflow.contrib.graph_editor.filter_ts",
"numpy.sqrt",
"tensorflow.get_collection",
"tensorflow.contrib.graph_editor.get_backward_walk_ops",
"tensorflow.contrib.graph_editor.get_forward_walk_ops",
"tensorflow.contrib.graph_editor.reroute_ts",
"tensorflow.scatter_nd",
"tensorflow.expand_dims",
"tensorflow.stop_gradient",
"tensorflow.contrib.graph_editor.select_ops",
"tensorflow.name_scope",
"tensorflow.contrib.graph_editor.sgv",
"tensorflow.contrib.graph_editor.filter_ts_from_regex",
"tensorflow.contrib.graph_editor.add_control_inputs"
] | track2/icnet/memory_saving_gradients.py | [(8, 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10000)'], {}), False, 'import sys\n'), (61, 'tensorflow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', (['[y.op for y in ys]'], {'inclusive': '(True)'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (67, 'tensorflow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', (['[x.op for x in xs]'], {'inclusive': '(True)', 'within_ops': 'bwd_ops'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (81, 'tensorflow.contrib.graph_editor.filter_ts', 'ge.filter_ts', (['fwd_ops', '(True)'], {}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (303, 'tensorflow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', (['[x.op for x in ts]'], {'within_ops': 'within_ops'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (309, 'toposort.toposort', 'toposort', (['deps'], {}), False, 'from toposort import toposort\n'), (339, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.contrib.graph_editor.sgv', 'ge.sgv', (['ops_to_copy'], {}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (255, 'tensorflow.contrib.graph_editor.reroute_ts', 'ge.reroute_ts', (['checkpoints_disconnected_other', 'checkpoints_other'], {'can_modify': 'copied_ops'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (321, 'tensorflow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', (['seed_ops'], {'stop_at_ts': 'stop_at_ts'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (336, 'tensorflow.name_scope', 'tf.name_scope', (['scope_name'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.contrib.graph_editor.select_ops', 'ge.select_ops', (["(scope_name + '/.*')"], {'graph': 'g'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (387, 'tensorflow.contrib.graph_editor.add_control_inputs', 'ge.add_control_inputs', (['op', 'ci'], {}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (89, 'tensorflow.get_collection', 'tf.get_collection', (['"""checkpoints"""'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['x'], {'name': "(x.op.name + '_sg')"}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['x'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.contrib.graph_editor.sgv', 'ge.sgv', (['ops_to_copy'], {}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (288, 'tensorflow.scatter_nd', 'tf.scatter_nd', (['indices', 'x.values', 'x.dense_shape'], {}), True, 'import tensorflow as tf\n'), (333, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (93, 'tensorflow.contrib.graph_editor.filter_ts_from_regex', 'ge.filter_ts_from_regex', (['fwd_ops', '"""conv2d|Conv|MatMul"""'], {}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (287, 'tensorflow.expand_dims', 'tf.expand_dims', (['indices', '(-1)'], {}), True, 'import tensorflow as tf\n'), (151, 'numpy.sqrt', 'np.sqrt', (['N'], {}), True, 'import numpy as np\n'), (128, 'tensorflow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', (['t.op'], {'inclusive': '(True)', 'within_ops': 'fwd_ops'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (129, 'tensorflow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', (['t.op'], {'inclusive': '(False)', 'within_ops': 'fwd_ops'}), True, 'import tensorflow.contrib.graph_editor as ge\n'), (154, 'numpy.sqrt', 'np.sqrt', (['N'], {}), True, 'import numpy as np\n')] |
changwoolee/gradient-rescaling-attention-model | 2f1d819e8cee03a9d06312e700a5c474bed48c70 | import tensorflow as tf
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 = tf.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.tensorflow_backend.set_session(tensorflow_session(gpu_memory_fraction=gpu_memory_fraction))
def reset_session(gpu_memory_fraction):
K.clear_session()
init_session(gpu_memory_fraction)
def tensorflow_session(gpu_memory_fraction):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = gpu_memory_fraction
return tf.Session(config=config)
def load_image(path):
img = Image.open(path)
if img.mode != 'RGB':
img = img.convert('RGB')
return img
| [
"tensorflow.ConfigProto",
"tensorflow.exp",
"tensorflow.Session"
] | util.py | [(49, 'keras.utils.data_utils.OrderedEnqueuer', 'OrderedEnqueuer', (['sequence'], {'use_multiprocessing': 'use_multiprocessing'}), False, 'from keras.utils.data_utils import OrderedEnqueuer\n'), (62, 'keras.backend.clear_session', 'K.clear_session', ([], {}), True, 'from keras import backend as K\n'), (67, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (74, 'PIL.Image.open', 'Image.open', (['path'], {}), False, 'from PIL import Image\n'), (17, 'keras.backend.clip', 'K.clip', (['y_logvar', '(-10)', '(10)'], {}), True, 'from keras import backend as K\n'), (36, 'keras.backend.mean', 'K.mean', (['loss'], {'axis': '(-1)'}), True, 'from keras import backend as K\n'), (19, 'keras.backend.square', 'K.square', (['(y_true / 127.5 - y_mean / 127.5)'], {}), True, 'from keras import backend as K\n'), (30, 'keras.backend.sigmoid', 'K.sigmoid', (['y_logvar'], {}), True, 'from keras import backend as K\n'), (21, 'keras.backend.abs', 'K.abs', (['(y_true / 127.5 - y_mean / 127.5)'], {}), True, 'from keras import backend as K\n'), (23, 'tensorflow.exp', 'tf.exp', (['(-y_logvar)'], {}), True, 'import tensorflow as tf\n'), (33, 'keras.backend.stop_gradient', 'K.stop_gradient', (['attention_mask'], {}), True, 'from keras import backend as K\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 tensorflow as tf
from texar.tf.utils.exceptions import TexarError
from texar.tf.modules.classifiers.classifier_base import ClassifierBase
from texar.tf.modules.encoders.conv_encoders import Conv1DEncoder
from texar.tf.utils import utils
from texar.tf.hyperparams import HParams
__all__ = [
"Conv1DClassifier"
]
class Conv1DClassifier(ClassifierBase):
"""Simple Conv-1D classifier.
This is a combination of the
:class:`~texar.tf.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 = tf.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 tf.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.tf.modules.Conv1DEncoder`.
See the :meth:`~texar.tf.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.tf.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.tf.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:`tf.estimator.ModeKeys <estimator/ModeKeys>`, including
`TRAIN`, `EVAL`, and `PREDICT`. If `None`,
:func:`texar.tf.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 `tf.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 = tf.greater(logits, 0)
logits = tf.reshape(logits, [-1])
else:
pred = tf.argmax(logits, 1)
pred = tf.cast(tf.reshape(pred, [-1]), tf.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
| [
"tensorflow.variable_scope",
"tensorflow.argmax",
"tensorflow.reshape",
"tensorflow.greater"
] | texar/tf/modules/classifiers/conv_classifiers.py | [(63, 'texar.tf.modules.classifiers.classifier_base.ClassifierBase.__init__', 'ClassifierBase.__init__', (['self', 'hparams'], {}), False, 'from texar.tf.modules.classifiers.classifier_base import ClassifierBase\n'), (135, 'texar.tf.modules.encoders.conv_encoders.Conv1DEncoder.default_hparams', 'Conv1DEncoder.default_hparams', ([], {}), False, 'from texar.tf.modules.encoders.conv_encoders import Conv1DEncoder\n'), (65, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.variable_scope'], {}), True, 'import tensorflow as tf\n'), (68, 'texar.tf.modules.encoders.conv_encoders.Conv1DEncoder', 'Conv1DEncoder', ([], {'hparams': 'encoder_hparams'}), False, 'from texar.tf.modules.encoders.conv_encoders import Conv1DEncoder\n'), (188, 'tensorflow.greater', 'tf.greater', (['logits', '(0)'], {}), True, 'import tensorflow as tf\n'), (189, 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1]'], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.argmax', 'tf.argmax', (['logits', '(1)'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.reshape', 'tf.reshape', (['pred', '[-1]'], {}), True, 'import tensorflow as tf\n'), (203, 'texar.tf.utils.exceptions.TexarError', 'TexarError', (["('Attempting to access trainable_variables before module %s was fully built. The module is built once it is called, e.g., with `%s(...)`'\n % (self.name, self.name))"], {}), False, 'from texar.tf.utils.exceptions import TexarError\n'), (67, 'texar.tf.modules.encoders.conv_encoders.Conv1DEncoder.default_hparams', 'Conv1DEncoder.default_hparams', ([], {}), False, 'from texar.tf.modules.encoders.conv_encoders import Conv1DEncoder\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 tensorflow as tf
from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor
from texar.tf.utils.test import pretrained_test
# pylint: disable=too-many-locals, no-member
class XLNetRegressorTest(tf.test.TestCase):
"""Tests :class:`~texar.tf.modules.XLNetRegressor` class.
"""
@pretrained_test
def test_model_loading(self):
r"""Tests model loading functionality."""
inputs = tf.placeholder(dtype=tf.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 = tf.placeholder(dtype=tf.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 = tf.random_uniform([batch_size, max_time],
maxval=30521, dtype=tf.int32)
# case 1
hparams = {
"pretrained_model_name": None,
}
regressor = XLNetRegressor(hparams=hparams)
logits = regressor(inputs)
with self.test_session() as sess:
sess.run(tf.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(tf.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(tf.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 = tf.placeholder(tf.int32, shape=[batch_size, 6])
regressor = XLNetRegressor(hparams=hparams)
logits = regressor(inputs)
with self.test_session() as sess:
sess.run(tf.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 = tf.placeholder(tf.int32, shape=[batch_size, 6])
regressor = XLNetRegressor(hparams=hparams)
logits = regressor(inputs)
with self.test_session() as sess:
sess.run(tf.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__":
tf.test.main()
| [
"tensorflow.placeholder",
"tensorflow.test.main",
"tensorflow.global_variables_initializer",
"tensorflow.random_uniform",
"numpy.random.randint"
] | texar/tf/modules/regressors/xlnet_regressor_test.py | [(160, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None, None]'}), True, 'import tensorflow as tf\n'), (30, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor.available_checkpoints', 'XLNetRegressor.available_checkpoints', ([], {}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (39, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[None, None]'}), True, 'import tensorflow as tf\n'), (45, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (58, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (68, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (78, 'tensorflow.random_uniform', 'tf.random_uniform', (['[batch_size, max_time]'], {'maxval': '(30521)', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (85, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (98, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (111, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (126, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[batch_size, 6]'}), True, 'import tensorflow as tf\n'), (127, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (146, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[batch_size, 6]'}), True, 'import tensorflow as tf\n'), (147, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'hparams': 'hparams'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (31, 'texar.tf.modules.regressors.xlnet_regressor.XLNetRegressor', 'XLNetRegressor', ([], {'pretrained_model_name': 'pretrained_model_name'}), False, 'from texar.tf.modules.regressors.xlnet_regressor import XLNetRegressor\n'), (89, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (134, 'numpy.random.randint', 'np.random.randint', (['(30521)'], {'size': '(batch_size, 6)'}), True, 'import numpy as np\n'), (154, 'numpy.random.randint', 'np.random.randint', (['(30521)'], {'size': '(batch_size, 6)'}), True, 'import numpy as np\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 tensorflow as tf
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, tf.test.TestCase):
@classmethod
def setUpClass(cls):
algorithmic.TinyAlgo.setup_for_test()
def testNoShuffleDeterministic(self):
problem = algorithmic.TinyAlgo()
dataset = problem.dataset(mode=tf.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 tf.Session() as sess:
self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20))
def testNoShufflePreprocess(self):
problem = algorithmic.TinyAlgo()
dataset1 = problem.dataset(mode=tf.estimator.ModeKeys.TRAIN,
data_dir=algorithmic.TinyAlgo.data_dir,
shuffle_files=False, preprocess=False)
dataset2 = problem.dataset(mode=tf.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 tf.Session() as sess:
self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20))
@tf.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)
@tf.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)
@tf.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)
@tf.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__":
tf.test.main()
| [
"numpy.all",
"tensorflow.contrib.eager.run_test_in_graph_and_eager_modes",
"tensorflow.test.main",
"tensorflow.Session"
] | v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/data_generators/problem_test.py | [(83, 'tensorflow.contrib.eager.run_test_in_graph_and_eager_modes', 'tf.contrib.eager.run_test_in_graph_and_eager_modes', ([], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.eager.run_test_in_graph_and_eager_modes', 'tf.contrib.eager.run_test_in_graph_and_eager_modes', ([], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.contrib.eager.run_test_in_graph_and_eager_modes', 'tf.contrib.eager.run_test_in_graph_and_eager_modes', ([], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.contrib.eager.run_test_in_graph_and_eager_modes', 'tf.contrib.eager.run_test_in_graph_and_eager_modes', ([], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (53, 'tensor2tensor.data_generators.algorithmic.TinyAlgo.setup_for_test', 'algorithmic.TinyAlgo.setup_for_test', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (56, 'tensor2tensor.data_generators.algorithmic.TinyAlgo', 'algorithmic.TinyAlgo', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (69, 'tensor2tensor.data_generators.algorithmic.TinyAlgo', 'algorithmic.TinyAlgo', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (85, 'tensor2tensor.data_generators.problem_hparams.TestProblem', 'problem_hparams.TestProblem', ([], {'input_vocab_size': '(2)', 'target_vocab_size': '(3)'}), False, 'from tensor2tensor.data_generators import problem_hparams\n'), (43, 'numpy.all', 'np.all', (['(v1 == v2)'], {}), True, 'import numpy as np\n'), (64, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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):
tf.reset_default_graph()
sess = tf.Session()
dataset = dataset_mnist.DatasetMnist(
constants.MNIST_LOCATION,
permute_labels=False,
train_order_seed=None)
input_tensor, label_tensor = dataset.placeholders
hyperparameters = {'layers': [(1000, tf.nn.relu), (500, tf.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(tf.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)
| [
"tensorflow.reset_default_graph",
"tensorflow.Session"
] | lottery_ticket/mnist_fc/big_two_layer_exp.py | [(103, 'fire.Fire', 'fire.Fire', (['main'], {}), False, 'import fire\n'), (65, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (67, 'lottery_ticket.datasets.dataset_mnist.DatasetMnist', 'dataset_mnist.DatasetMnist', (['constants.MNIST_LOCATION'], {'permute_labels': '(False)', 'train_order_seed': 'None'}), False, 'from lottery_ticket.datasets import dataset_mnist\n'), (73, 'lottery_ticket.foundations.model_fc.ModelFc', 'model_fc.ModelFc', (['hyperparameters', 'input_tensor', 'label_tensor'], {'presets': 'presets', 'masks': 'masks'}), False, 'from lottery_ticket.foundations import model_fc\n'), (89, 'lottery_ticket.foundations.pruning.prune_holistically', 'pruning.prune_holistically', (['(0.5)', 'masks', 'final_weights'], {}), False, 'from lottery_ticket.foundations import pruning\n'), (62, 'lottery_ticket.foundations.paths.experiment', 'paths.experiment', (['constants.EXPERIMENT_PATH', '"""big_two_layer"""'], {}), False, 'from lottery_ticket.foundations import paths\n'), (83, 'functools.partial', 'functools.partial', (['tf.train.GradientDescentOptimizer', '(0.1)'], {}), False, 'import functools\n'), (85, 'lottery_ticket.foundations.paths.run', 'paths.run', (['self.output_dir', 'iteration'], {}), False, 'from lottery_ticket.foundations import paths\n'), (100, 'lottery_ticket.foundations.save_restore.standardize', 'save_restore.standardize', (['None'], {}), False, 'from lottery_ticket.foundations import save_restore\n')] |
RandolphVI/Question-Difficulty-Prediction | 77b4b83b5bc747c5074926d7a37545a5d46ed343 | # -*- coding:utf-8 -*-
__author__ = 'Randolph'
import os
import sys
import time
import logging
sys.path.append('../')
logging.getLogger('tensorflow').disabled = True
import tensorflow as tf
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 = tf.train.latest_checkpoint(CPT_DIR)
logger.info(checkpoint_file)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.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 = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.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 = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def,
output_node_names.split("|"))
tf.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()
| [
"tensorflow.Graph",
"tensorflow.train.latest_checkpoint",
"sklearn.metrics.r2_score",
"sklearn.metrics.mean_squared_error",
"tensorflow.ConfigProto",
"tensorflow.Session"
] | TF/TARNN/test_tarnn.py | [(9, 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), False, 'import sys\n'), (18, 'utils.param_parser.parameter_parser', 'parser.parameter_parser', ([], {}), True, 'from utils import param_parser as parser\n'), (19, 'utils.data_helpers.get_model_name', 'dh.get_model_name', ([], {}), True, 'from utils import data_helpers as dh\n'), (10, 'logging.getLogger', 'logging.getLogger', (['"""tensorflow"""'], {}), False, 'import logging\n'), (30, 'utils.data_helpers.tab_printer', 'dh.tab_printer', (['args', 'logger'], {}), True, 'from utils import data_helpers as dh\n'), (35, 'utils.data_helpers.load_data_and_labels', 'dh.load_data_and_labels', (['args.test_file', 'args.word2vec_file'], {'data_aug_flag': '(False)'}), True, 'from utils import data_helpers as dh\n'), (38, 'utils.data_helpers.pad_data', 'dh.pad_data', (['test_data', 'args.pad_seq_len'], {}), True, 'from utils import data_helpers as dh\n'), (41, 'utils.data_helpers.option', 'dh.option', ([], {'pattern': '(1)'}), True, 'from utils import data_helpers as dh\n'), (50, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (20, 'time.asctime', 'time.asctime', ([], {}), False, 'import time\n'), (44, 'utils.checkmate.get_best_checkpoint', 'cm.get_best_checkpoint', (['BEST_CPT_DIR'], {'select_maximum_value': '(True)'}), True, 'from utils import checkmate as cm\n'), (47, 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['CPT_DIR'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': 'args.allow_soft_placement', 'log_device_placement': 'args.log_device_placement'}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), True, 'import tensorflow as tf\n'), (114, 'utils.data_helpers.evaluation', 'dh.evaluation', (['true_labels', 'predicted_scores'], {}), True, 'from utils import data_helpers as dh\n'), (117, 'sklearn.metrics.r2_score', 'r2_score', (['true_labels', 'predicted_scores'], {}), False, 'from sklearn.metrics import mean_squared_error, r2_score\n'), (127, 'utils.data_helpers.create_prediction_file', 'dh.create_prediction_file', ([], {'output_file': "(SAVE_DIR + '/predictions.json')", 'all_id': 'test_data.id', 'all_labels': 'true_labels', 'all_predict_scores': 'predicted_scores'}), True, 'from utils import data_helpers as dh\n'), (116, 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['true_labels', 'predicted_scores'], {}), False, 'from sklearn.metrics import mean_squared_error, r2_score\n'), (125, 'os.path.exists', 'os.path.exists', (['SAVE_DIR'], {}), False, 'import os\n'), (126, 'os.makedirs', 'os.makedirs', (['SAVE_DIR'], {}), False, 'import os\n')] |
alishameli/CS231n-Sample-Code-1 | e47e593026c80530f7c387c4feca24f88c1618a2 | import argparse
import os
import numpy as np
import tensorflow as tf
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 = tf.placeholder(tf.float32, shape=(None, height, width, channels))
# Construct the network
net = models.ResNet50UpProj({'data': input_node}, batch_size)
with tf.Session() as sess:
# Load the converted parameters
print('Loading the model')
net.load(model_data_path, sess)
uninitialized_vars = []
for var in tf.global_variables():
try:
sess.run(var)
except tf.errors.FailedPreconditionError:
uninitialized_vars.append(var)
init_new_vars_op = tf.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()
| [
"matplotlib.pyplot.imshow",
"numpy.asarray",
"tensorflow.global_variables",
"tensorflow.variables_initializer",
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
] | tensorflow/predict.py | [(19, 'PIL.Image.open', 'Image.open', (['image_path'], {}), False, 'from PIL import Image\n'), (25, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, height, width, channels)'}), True, 'import tensorflow as tf\n'), (28, 'models.ResNet50UpProj', 'models.ResNet50UpProj', (["{'data': input_node}", 'batch_size'], {}), False, 'import models\n'), (60, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (68, 'os._exit', 'os._exit', (['(0)'], {}), False, 'import os\n'), (22, 'numpy.asarray', 'np.asarray', (['img'], {}), True, 'import numpy as np\n'), (30, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.variables_initializer', 'tf.variables_initializer', (['uninitialized_vars'], {}), True, 'import tensorflow as tf\n'), (50, 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), True, 'from matplotlib import pyplot as plt\n'), (51, 'matplotlib.pyplot.imshow', 'plt.imshow', (['pred[(0), :, :, (0)]'], {'interpolation': '"""nearest"""'}), True, 'from matplotlib import pyplot as plt\n'), (53, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'from matplotlib import pyplot as plt\n'), (21, 'numpy.array', 'np.array', (['img'], {}), True, 'import numpy as np\n')] |
My-Technical-Architect/tensorflow | 35cf4653e6fe15953e2e565afc5a0fd2ab4d5290 | # Copyright 2016 The TensorFlow 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 tensorflow as tf
from tensorflow.python.framework import tensor_util
dists = tf.contrib.distributions
class DistributionTest(tf.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, tf.random_normal(shape))
for name, shape in param_shapes.items()])
dist = cls(**params)
self.assertAllEqual(sample_shape, tf.shape(dist.sample()).eval())
dist_copy = dist.copy()
self.assertAllEqual(sample_shape,
tf.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 = tf.placeholder(dtype=tf.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: tf.TensorShape(None),
lambda: tf.shape(x)))
x = tf.placeholder(dtype=tf.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: tf.TensorShape(None),
lambda: tf.shape(x)))
# Test case 3.
x = tf.placeholder(dtype=tf.int32)
is_scalar = normal._is_scalar_helper(x.get_shape, lambda: tf.shape(x))
self.assertTrue(is_scalar.eval(feed_dict={x: 1}))
self.assertFalse(is_scalar.eval(feed_dict={x: [1]}))
if __name__ == '__main__':
tf.test.main()
| [
"tensorflow.TensorShape",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.test.main",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.random_normal"
] | tensorflow/contrib/distributions/python/kernel_tests/distribution_test.py | [(123, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[]'}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32', 'shape': '[1]'}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (81, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['normal.is_scalar_event'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (82, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['normal.is_scalar_batch'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (86, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['normal.is_scalar_event'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (87, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['normal.is_scalar_batch'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (91, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['mvn.is_scalar_event'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (92, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['mvn.is_scalar_batch'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (96, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['mvn.is_scalar_event'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (97, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['mvn.is_scalar_batch'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (117, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.random_normal', 'tf.random_normal', (['shape'], {}), True, 'import tensorflow as tf\n')] |
gujralsanyam22/models | 11ea5237818e791a5717716d5413977f4c4db1e3 | # Copyright 2019 The TensorFlow 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.
# ==============================================================================
"""Tensorflow Example proto decoder for object detection.
A decoder to decode string tensors containing serialized tensorflow.Example
protos for object detection.
"""
import tensorflow as tf
class TfExampleDecoder(object):
"""Tensorflow Example proto decoder."""
def __init__(self, include_mask=False):
self._include_mask = include_mask
self._keys_to_features = {
'image/encoded':
tf.io.FixedLenFeature((), tf.string),
'image/source_id':
tf.io.FixedLenFeature((), tf.string),
'image/height':
tf.io.FixedLenFeature((), tf.int64),
'image/width':
tf.io.FixedLenFeature((), tf.int64),
'image/object/bbox/xmin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/xmax':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymin':
tf.io.VarLenFeature(tf.float32),
'image/object/bbox/ymax':
tf.io.VarLenFeature(tf.float32),
'image/object/class/label':
tf.io.VarLenFeature(tf.int64),
'image/object/area':
tf.io.VarLenFeature(tf.float32),
'image/object/is_crowd':
tf.io.VarLenFeature(tf.int64),
}
if include_mask:
self._keys_to_features.update({
'image/object/mask':
tf.io.VarLenFeature(tf.string),
})
def _decode_image(self, parsed_tensors):
"""Decodes the image and set its static shape."""
image = tf.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 tf.stack([ymin, xmin, ymax, xmax], axis=-1)
def _decode_masks(self, parsed_tensors):
"""Decode a set of PNG masks to the tf.float32 tensors."""
def _decode_png_mask(png_bytes):
mask = tf.squeeze(
tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1)
mask = tf.cast(mask, dtype=tf.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 tf.cond(
pred=tf.greater(tf.size(input=masks), 0),
true_fn=lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32),
false_fn=lambda: tf.zeros([0, height, width], dtype=tf.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 tf.cond(
tf.greater(tf.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 tf.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 = tf.io.parse_single_example(
serialized=serialized_example, features=self._keys_to_features)
for k in parsed_tensors:
if isinstance(parsed_tensors[k], tf.SparseTensor):
if parsed_tensors[k].dtype == tf.string:
parsed_tensors[k] = tf.sparse.to_dense(
parsed_tensors[k], default_value='')
else:
parsed_tensors[k] = tf.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 = tf.cond(
tf.greater(tf.shape(parsed_tensors['image/object/is_crowd'])[0], 0),
lambda: tf.cast(parsed_tensors['image/object/is_crowd'], dtype=tf.bool),
lambda: tf.zeros_like(parsed_tensors['image/object/class/label'], dtype=tf.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
| [
"tensorflow.sparse.to_dense",
"tensorflow.zeros",
"tensorflow.io.decode_png",
"tensorflow.stack",
"tensorflow.shape",
"tensorflow.io.parse_single_example",
"tensorflow.cast",
"tensorflow.io.decode_image",
"tensorflow.io.VarLenFeature",
"tensorflow.io.FixedLenFeature",
"tensorflow.zeros_like",
"tensorflow.map_fn",
"tensorflow.size"
] | official/vision/detection/dataloader/tf_example_decoder.py | [(61, 'tensorflow.io.decode_image', 'tf.io.decode_image', (["parsed_tensors['image/encoded']"], {'channels': '(3)'}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.stack', 'tf.stack', (['[ymin, xmin, ymax, xmax]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.io.parse_single_example', 'tf.io.parse_single_example', ([], {'serialized': 'serialized_example', 'features': 'self._keys_to_features'}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['()', 'tf.string'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['()', 'tf.string'], {}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['()', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['()', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.cast', 'tf.cast', (['mask'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.io.decode_png', 'tf.io.decode_png', (['png_bytes'], {'channels': '(1)', 'dtype': 'tf.uint8'}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.cast', 'tf.cast', (["parsed_tensors['image/object/is_crowd']"], {'dtype': 'tf.bool'}), True, 'import tensorflow as tf\n'), (137, 'tensorflow.zeros_like', 'tf.zeros_like', (["parsed_tensors['image/object/class/label']"], {'dtype': 'tf.bool'}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.io.VarLenFeature', 'tf.io.VarLenFeature', (['tf.string'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.size', 'tf.size', ([], {'input': 'masks'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.map_fn', 'tf.map_fn', (['_decode_png_mask', 'masks'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.zeros', 'tf.zeros', (['[0, height, width]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.shape', 'tf.shape', (["parsed_tensors['image/object/area']"], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.sparse.to_dense', 'tf.sparse.to_dense', (['parsed_tensors[k]'], {'default_value': '""""""'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.sparse.to_dense', 'tf.sparse.to_dense', (['parsed_tensors[k]'], {'default_value': '(0)'}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.shape', 'tf.shape', (["parsed_tensors['image/object/is_crowd']"], {}), True, 'import tensorflow as tf\n')] |
gujralsanyam22/models | d96f8f043dbe2b5ca8ea1785f57df8faf68d8875 | # Copyright 2020 The TensorFlow 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 tensorflow as tf
from official.vision.beta.ops import box_ops
@tf.keras.utils.register_keras_serializable(package='Vision')
class BoxMatcher(tf.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 = tf.greater(
matched_iou, self._config_dict['foreground_iou_threshold'])
negative_matches = tf.logical_and(
tf.greater_equal(
matched_iou, self._config_dict['background_iou_low_threshold']),
tf.less(
matched_iou, self._config_dict['background_iou_high_threshold']))
ignored_matches = tf.logical_and(
tf.less(matched_iou, 0.0),
tf.greater_equal(
matched_iou, self._config_dict['background_iou_high_threshold']))
ignored_matches = tf.logical_and(
ignored_matches,
tf.less(
matched_iou, self._config_dict['foreground_iou_threshold']))
background_indicator = tf.logical_or(negative_matches, ignored_matches)
# re-assign negatively matched boxes to the background class.
matched_gt_boxes = tf.where(
tf.tile(tf.expand_dims(background_indicator, -1), [1, 1, 4]),
tf.zeros_like(matched_gt_boxes),
matched_gt_boxes)
matched_gt_classes = tf.where(
background_indicator,
tf.zeros_like(matched_gt_classes),
matched_gt_classes)
matched_gt_indices = tf.where(
background_indicator,
-tf.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)
| [
"tensorflow.less",
"tensorflow.logical_or",
"tensorflow.greater",
"tensorflow.ones_like",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.expand_dims",
"tensorflow.zeros_like",
"tensorflow.greater_equal"
] | official/vision/beta/modeling/layers/box_matcher.py | [(23, 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""Vision"""'}), True, 'import tensorflow as tf\n'), (99, 'official.vision.beta.ops.box_ops.box_matching', 'box_ops.box_matching', (['boxes', 'gt_boxes', 'gt_classes'], {}), False, 'from official.vision.beta.ops import box_ops\n'), (101, 'tensorflow.greater', 'tf.greater', (['matched_iou', "self._config_dict['foreground_iou_threshold']"], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.logical_or', 'tf.logical_or', (['negative_matches', 'ignored_matches'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.greater_equal', 'tf.greater_equal', (['matched_iou', "self._config_dict['background_iou_low_threshold']"], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.less', 'tf.less', (['matched_iou', "self._config_dict['background_iou_high_threshold']"], {}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.less', 'tf.less', (['matched_iou', '(0.0)'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.greater_equal', 'tf.greater_equal', (['matched_iou', "self._config_dict['background_iou_high_threshold']"], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.less', 'tf.less', (['matched_iou', "self._config_dict['foreground_iou_threshold']"], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.zeros_like', 'tf.zeros_like', (['matched_gt_boxes'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.zeros_like', 'tf.zeros_like', (['matched_gt_classes'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.expand_dims', 'tf.expand_dims', (['background_indicator', '(-1)'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.ones_like', 'tf.ones_like', (['matched_gt_indices'], {}), True, 'import tensorflow as tf\n')] |
gujralsanyam22/models | 11ea5237818e791a5717716d5413977f4c4db1e3 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
# 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 tf.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 tf.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 = tf.stack([
box_coder.decode(boxes, anchors).get()
for boxes in tf.unstack(encoded_boxes)
])
return decoded_boxes
| [
"tensorflow.name_scope",
"tensorflow.unstack"
] | official/vision/detection/utils/object_detection/box_coder.py | [(69, 'tensorflow.name_scope', 'tf.name_scope', (['"""Encode"""'], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.name_scope', 'tf.name_scope', (['"""Decode"""'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.unstack', 'tf.unstack', (['encoded_boxes'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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 = tf.clip_by_value(K.exp(self.theta), 1e-3, 1e4)
super().build(input_shape)
def call(self, x):
return tf.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 tf.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: tf.where(tf.is_nan(x), tf.zeros_like(x), x))
ColWiseMultLayer = lambda name: Lambda(lambda l: l[0]*(tf.matmul(tf.reshape(l[1], (-1,1)),
tf.ones((1, l[0].get_shape()[1]),
dtype=l[1].dtype))),
name=name)
| [
"tensorflow.is_nan",
"tensorflow.zeros_like",
"tensorflow.reshape",
"tensorflow.identity"
] | build/lib/sctransfer/layers.py | [(25, 'tensorflow.identity', 'tf.identity', (['x'], {}), True, 'import tensorflow as tf\n'), (72, 'keras.engine.base_layer.InputSpec', 'InputSpec', ([], {'min_ndim': '(2)', 'axes': '{(-1): input_dim}'}), False, 'from keras.engine.base_layer import InputSpec\n'), (21, 'keras.backend.exp', 'K.exp', (['self.theta'], {}), True, 'from keras import backend as K\n'), (86, 'tensorflow.is_nan', 'tf.is_nan', (['x'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.zeros_like', 'tf.zeros_like', (['x'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.reshape', 'tf.reshape', (['l[1]', '(-1, 1)'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
tf.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, tf.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=tf.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 tf.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=tf.estimator.ModeKeys.TRAIN,
data_dir=algorithmic.TinyAlgo.data_dir,
shuffle_files=False, preprocess=False)
dataset2 = problem.dataset(mode=tf.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 tf.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__":
tf.test.main()
| [
"numpy.all",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.test.main",
"tensorflow.Session"
] | tensor2tensor/data_generators/problem_test.py | [(32, 'tensorflow.compat.v1.enable_eager_execution', 'tf.compat.v1.enable_eager_execution', ([], {}), True, 'import tensorflow as tf\n'), (57, 'tensor2tensor.utils.test_utils.run_in_graph_mode_only', 'test_utils.run_in_graph_mode_only', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (70, 'tensor2tensor.utils.test_utils.run_in_graph_mode_only', 'test_utils.run_in_graph_mode_only', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (87, 'tensor2tensor.utils.test_utils.run_in_graph_and_eager_modes', 'test_utils.run_in_graph_and_eager_modes', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (97, 'tensor2tensor.utils.test_utils.run_in_graph_and_eager_modes', 'test_utils.run_in_graph_and_eager_modes', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (112, 'tensor2tensor.utils.test_utils.run_in_graph_and_eager_modes', 'test_utils.run_in_graph_and_eager_modes', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (127, 'tensor2tensor.utils.test_utils.run_in_graph_and_eager_modes', 'test_utils.run_in_graph_and_eager_modes', ([], {}), False, 'from tensor2tensor.utils import test_utils\n'), (154, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (55, 'tensor2tensor.data_generators.algorithmic.TinyAlgo.setup_for_test', 'algorithmic.TinyAlgo.setup_for_test', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (59, 'tensor2tensor.data_generators.algorithmic.TinyAlgo', 'algorithmic.TinyAlgo', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (73, 'tensor2tensor.data_generators.algorithmic.TinyAlgo', 'algorithmic.TinyAlgo', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (89, 'tensor2tensor.data_generators.problem_hparams.TestProblem', 'problem_hparams.TestProblem', ([], {'input_vocab_size': '(2)', 'target_vocab_size': '(3)'}), False, 'from tensor2tensor.data_generators import problem_hparams\n'), (129, 'tensor2tensor.data_generators.algorithmic.TinyAlgo', 'algorithmic.TinyAlgo', ([], {}), False, 'from tensor2tensor.data_generators import algorithmic\n'), (45, 'numpy.all', 'np.all', (['(v1 == v2)'], {}), True, 'import numpy as np\n'), (67, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\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 tensorflow as tf
import tensorflow_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 = tf.split(
lhs, [1, 1, num_lhs_samples], axis=-2)
rhs_means, rhs_stddevs, rhs_samples = tf.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(tf.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: -tf.math.log(tf.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 -tf.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 - tf.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(tf.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 = tf.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 = tf.where(
tf.stop_gradient(indicator_matrix), distance_matrix,
tf.fill(tf.shape(distance_matrix), distance_matrix.dtype.max))
hard_distances = tf.math.reduce_min(distance_matrix, axis=-1)
return hard_distances
hard_negative_mining_distances = find_hard_distances(
anchor_match_mining_distance_matrix, indicators)
indicators &= tf.math.equal(
anchor_match_mining_distance_matrix,
tf.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 = tf.nn.relu(positive_distances + margin - negative_distances)
losses = tf.where(
tf.stop_gradient(losses < losses.dtype.max), losses,
tf.zeros_like(losses))
num_nonzero_losses = tf.math.count_nonzero(losses)
loss = tf.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 tensorflow_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 tf.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 = tf.shape(anchor_keypoints)[0]
anchor_match_negative_indicator_matrix = tf.math.logical_not(
tf.eye(num_anchors, dtype=tf.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 = tf.cast(tf.shape(anchor_embeddings)[0], dtype=tf.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 = tf.boolean_mask(
negative_distances,
mask=negative_distances < negative_distances.dtype.max)
negative_mining_distances = tf.boolean_mask(
negative_mining_distances,
mask=negative_distances < negative_distances.dtype.max)
active_triplet_ratio = (
tf.cast(num_active_triplets, dtype=tf.float32) / num_total_triplets)
active_mining_triplet_ratio = (
tf.cast(num_active_mining_triplets, dtype=tf.float32) /
num_total_triplets)
active_loss = (
loss / tf.math.maximum(1e-12, tf.stop_gradient(active_triplet_ratio)))
active_mining_loss = (
mining_loss /
tf.math.maximum(1e-12, tf.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:
tf.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:
tf.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':
tf.constant(margin),
'triplet_loss/Anchor/Positive/Distance/Mean':
tf.math.reduce_mean(anchor_positive_distances),
'triplet_mining/Anchor/Positive/Distance/Mean':
tf.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 = tf.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':
tf.math.reduce_mean(tf.constant(prior_mean)),
'regularization_loss/KL/PriorVar/Mean':
tf.math.reduce_mean(tf.constant(prior_stddev)**2),
'regularization_loss/KL/Loss/Original':
loss,
'regularization_loss/KL/Loss/Weighted':
weighted_loss,
'regularization_loss/KL/Loss/Weight':
tf.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 = tf.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': tf.constant(loss_weight),
}
return weighted_loss, summaries
| [
"tensorflow.boolean_mask",
"tensorflow.nn.relu",
"tensorflow.math.reduce_min",
"tensorflow.constant",
"tensorflow.math.count_nonzero",
"tensorflow.shape",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.math.reduce_mean",
"tensorflow.stop_gradient",
"tensorflow.eye",
"tensorflow.zeros_like",
"tensorflow.split"
] | poem/core/loss_utils.py | [(185, 'poem.core.distance_utils.compute_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'}), False, 'from poem.core import distance_utils\n'), (446, 'poem.core.distance_utils.compute_distance_matrix', 'distance_utils.compute_distance_matrix', (['anchor_embeddings', 'match_embeddings'], {'distance_fn': 'embedding_sample_distance_fn'}), False, 'from poem.core import distance_utils\n'), (609, 'functools.partial', 'functools.partial', (['distance_utils.compute_l2_distances'], {'squared': '(True)'}), False, 'import functools\n'), (238, 'tensorflow.expand_dims', 'tf.expand_dims', (['anchor_positive_mining_distances'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (247, 'tensorflow.math.reduce_min', 'tf.math.reduce_min', (['distance_matrix'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.expand_dims', 'tf.expand_dims', (['hard_negative_mining_distances'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.nn.relu', 'tf.nn.relu', (['(positive_distances + margin - negative_distances)'], {}), True, 'import tensorflow as tf\n'), (325, 'tensorflow.math.count_nonzero', 'tf.math.count_nonzero', (['losses'], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['losses'], {}), True, 'import tensorflow as tf\n'), (476, 'tensorflow.boolean_mask', 'tf.boolean_mask', (['negative_distances'], {'mask': '(negative_distances < negative_distances.dtype.max)'}), True, 'import tensorflow as tf\n'), (479, 'tensorflow.boolean_mask', 'tf.boolean_mask', (['negative_mining_distances'], {'mask': '(negative_distances < negative_distances.dtype.max)'}), True, 'import tensorflow as tf\n'), (539, 'tensorflow.constant', 'tf.constant', (['margin'], {}), True, 'import tensorflow as tf\n'), (541, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['anchor_positive_distances'], {}), True, 'import tensorflow as tf\n'), (543, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['anchor_positive_mining_distances'], {}), True, 'import tensorflow as tf\n'), (588, 'poem.core.distance_utils.compute_gaussian_kl_divergence', 'distance_utils.compute_gaussian_kl_divergence', (['means', 'stddevs'], {'rhs_means': 'prior_mean', 'rhs_stddevs': 'prior_stddev'}), False, 'from poem.core import distance_utils\n'), (601, 'tensorflow.constant', 'tf.constant', (['loss_weight'], {}), True, 'import tensorflow as tf\n'), (634, 'tensorflow.constant', 'tf.constant', (['loss_weight'], {}), True, 'import tensorflow as tf\n'), (65, 'functools.partial', 'functools.partial', (['l2_distance_computer'], {'squared': '(True)'}), False, 'import functools\n'), (124, 'functools.partial', 'functools.partial', (['tf.math.reduce_mean'], {'axis': '[-2, -1]'}), False, 'import functools\n'), (126, 'functools.partial', 'functools.partial', (['data_utils.compute_lower_percentile_means'], {'axis': '[-2, -1]', 'q': '(50)'}), False, 'import functools\n'), (147, 'functools.partial', 'functools.partial', (['tf.math.reduce_mean'], {'axis': '[-1]'}), False, 'import functools\n'), (245, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['indicator_matrix'], {}), True, 'import tensorflow as tf\n'), (323, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['(losses < losses.dtype.max)'], {}), True, 'import tensorflow as tf\n'), (324, 'tensorflow.zeros_like', 'tf.zeros_like', (['losses'], {}), True, 'import tensorflow as tf\n'), (413, 'tensorflow.expand_dims', 'tf.expand_dims', (['embeddings'], {'axis': '(-2)'}), True, 'import tensorflow as tf\n'), (430, 'tensorflow.shape', 'tf.shape', (['anchor_keypoints'], {}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.eye', 'tf.eye', (['num_anchors'], {'dtype': 'tf.bool'}), True, 'import tensorflow as tf\n'), (461, 'tensorflow.shape', 'tf.shape', (['anchor_embeddings'], {}), True, 'import tensorflow as tf\n'), (484, 'tensorflow.cast', 'tf.cast', (['num_active_triplets'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (486, 'tensorflow.cast', 'tf.cast', (['num_active_mining_triplets'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (499, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['negative_distances'], {}), True, 'import tensorflow as tf\n'), (511, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['negative_mining_distances'], {}), True, 'import tensorflow as tf\n'), (593, 'tensorflow.constant', 'tf.constant', (['prior_mean'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.split', 'tf.split', (['lhs', '[1, 1, num_lhs_samples]'], {'axis': '(-2)'}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.split', 'tf.split', (['rhs', '[1, 1, num_rhs_samples]'], {'axis': '(-2)'}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.shape', 'tf.shape', (['distance_matrix'], {}), True, 'import tensorflow as tf\n'), (490, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['active_triplet_ratio'], {}), True, 'import tensorflow as tf\n'), (493, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['active_mining_triplet_ratio'], {}), True, 'import tensorflow as tf\n'), (548, 'tensorflow_probability.stats.percentile', 'tfp.stats.percentile', (['anchor_positive_distances'], {'q': '(50)'}), True, 'import tensorflow_probability as tfp\n'), (550, 'tensorflow_probability.stats.percentile', 'tfp.stats.percentile', (['anchor_positive_mining_distances'], {'q': '(50)'}), True, 'import tensorflow_probability as tfp\n'), (595, 'tensorflow.constant', 'tf.constant', (['prior_stddev'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['x'], {'axis': '[-2, -1]'}), True, 'import tensorflow as tf\n'), (524, 'tensorflow_probability.stats.percentile', 'tfp.stats.percentile', (['negative_distances'], {'q': '(50)'}), True, 'import tensorflow_probability as tfp\n'), (526, 'tensorflow_probability.stats.percentile', 'tfp.stats.percentile', (['negative_mining_distances'], {'q': '(50)'}), True, 'import tensorflow_probability as tfp\n'), (129, 'tensorflow.math.reduce_mean', 'tf.math.reduce_mean', (['x'], {'axis': '[-2, -1]'}), True, 'import tensorflow as tf\n'), (135, 'poem.core.data_utils.compute_lower_percentile_means', 'data_utils.compute_lower_percentile_means', (['x'], {'axis': '[-2, -1]', 'q': '(50)'}), False, 'from poem.core import data_utils\n')] |
TangZhenchaoTZC/Keras-mask-detection | 325679d06a12a90b2552ed7d447298a23e3b9d57 | """fasterRCNN训练的损失函数与数据生成器"""
from keras.applications.imagenet_utils import preprocess_input
from keras import backend as K
import keras
import tensorflow as tf
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 = tf.where(keras.backend.equal(anchor_state, 1))
labels_for_object = tf.gather_nd(labels, indices_for_object)
classification_for_object = tf.gather_nd(classification, indices_for_object)
cls_loss_for_object = keras.backend.binary_crossentropy(labels_for_object, classification_for_object)
# 找出实际上为背景的先验框
indices_for_back = tf.where(keras.backend.equal(anchor_state, 0))
labels_for_back = tf.gather_nd(labels, indices_for_back)
classification_for_back = tf.gather_nd(classification, indices_for_back)
# 计算每一个先验框应该有的权重
cls_loss_for_back = keras.backend.binary_crossentropy(labels_for_back, classification_for_back)
# 标准化,实际上是正样本的数量
normalizer_pos = tf.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 = tf.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 = tf.where(keras.backend.equal(anchor_state, 1))
regression = tf.gather_nd(regression, indices)
regression_target = tf.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 = tf.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) | [
"numpy.expand_dims",
"tensorflow.gather_nd",
"numpy.logical_and",
"matplotlib.colors.hsv_to_rgb",
"numpy.reshape",
"numpy.random.shuffle",
"numpy.shape",
"numpy.random.rand",
"numpy.array"
] | fasterRCNNtrain/loss_and_gen.py | [(14, 'sys.path.append', 'sys.path.append', (['""".."""'], {}), False, 'import sys\n'), (32, 'tensorflow.gather_nd', 'tf.gather_nd', (['labels', 'indices_for_object'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.gather_nd', 'tf.gather_nd', (['classification', 'indices_for_object'], {}), True, 'import tensorflow as tf\n'), (35, 'keras.backend.binary_crossentropy', 'keras.backend.binary_crossentropy', (['labels_for_object', 'classification_for_object'], {}), False, 'import keras\n'), (39, 'tensorflow.gather_nd', 'tf.gather_nd', (['labels', 'indices_for_back'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.gather_nd', 'tf.gather_nd', (['classification', 'indices_for_back'], {}), True, 'import tensorflow as tf\n'), (43, 'keras.backend.binary_crossentropy', 'keras.backend.binary_crossentropy', (['labels_for_back', 'classification_for_back'], {}), False, 'import keras\n'), (78, 'tensorflow.gather_nd', 'tf.gather_nd', (['regression', 'indices'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.gather_nd', 'tf.gather_nd', (['regression_target', 'indices'], {}), True, 'import tensorflow as tf\n'), (85, 'keras.backend.abs', 'keras.backend.abs', (['regression_diff'], {}), False, 'import keras\n'), (106, 'keras.backend.abs', 'K.abs', (['x'], {}), True, 'from keras import backend as K\n'), (117, 'keras.objectives.categorical_crossentropy', 'categorical_crossentropy', (['y_true[(0), :, :]', 'y_pred[(0), :, :]'], {}), False, 'from keras.objectives import categorical_crossentropy\n'), (160, 'PIL.Image.open', 'Image.open', (['line[0]'], {}), False, 'from PIL import Image\n'), (184, 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(w, h)', '(128, 128, 128)'], {}), False, 'from PIL import Image\n'), (19, 'numpy.random.rand', 'np.random.rand', ([], {}), True, 'import numpy as np\n'), (31, 'keras.backend.equal', 'keras.backend.equal', (['anchor_state', '(1)'], {}), False, 'import keras\n'), (38, 'keras.backend.equal', 'keras.backend.equal', (['anchor_state', '(0)'], {}), False, 'import keras\n'), (46, 'keras.backend.equal', 'keras.backend.equal', (['anchor_state', '(1)'], {}), False, 'import keras\n'), (47, 'keras.backend.floatx', 'keras.backend.floatx', ([], {}), False, 'import keras\n'), (48, 'keras.backend.cast_to_floatx', 'keras.backend.cast_to_floatx', (['(1.0)'], {}), False, 'import keras\n'), (50, 'keras.backend.equal', 'keras.backend.equal', (['anchor_state', '(0)'], {}), False, 'import keras\n'), (51, 'keras.backend.floatx', 'keras.backend.floatx', ([], {}), False, 'import keras\n'), (52, 'keras.backend.cast_to_floatx', 'keras.backend.cast_to_floatx', (['(1.0)'], {}), False, 'import keras\n'), (55, 'keras.backend.sum', 'keras.backend.sum', (['cls_loss_for_object'], {}), False, 'import keras\n'), (77, 'keras.backend.equal', 'keras.backend.equal', (['anchor_state', '(1)'], {}), False, 'import keras\n'), (87, 'keras.backend.less', 'keras.backend.less', (['regression_diff', '(1.0 / sigma_squared)'], {}), False, 'import keras\n'), (94, 'keras.backend.sum', 'keras.backend.sum', (['regression_loss'], {}), False, 'import keras\n'), (107, 'keras.backend.less_equal', 'K.less_equal', (['x_abs', '(1.0)'], {}), True, 'from keras import backend as K\n'), (109, 'keras.backend.sum', 'K.sum', (['(epsilon + y_true[:, :, :4 * num_classes])'], {}), True, 'from keras import backend as K\n'), (204, 'matplotlib.colors.hsv_to_rgb', 'hsv_to_rgb', (['x'], {}), False, 'from matplotlib.colors import rgb_to_hsv, hsv_to_rgb\n'), (209, 'numpy.random.shuffle', 'np.random.shuffle', (['box'], {}), True, 'import numpy as np\n'), (233, 'random.shuffle', 'shuffle', (['self.train_lines'], {}), False, 'from random import shuffle\n'), (47, 'keras.backend.shape', 'keras.backend.shape', (['normalizer_pos'], {}), False, 'import keras\n'), (51, 'keras.backend.shape', 'keras.backend.shape', (['normalizer_neg'], {}), False, 'import keras\n'), (56, 'keras.backend.sum', 'keras.backend.sum', (['cls_loss_for_back'], {}), False, 'import keras\n'), (88, 'keras.backend.pow', 'keras.backend.pow', (['regression_diff', '(2)'], {}), False, 'import keras\n'), (92, 'keras.backend.shape', 'keras.backend.shape', (['indices'], {}), False, 'import keras\n'), (93, 'keras.backend.floatx', 'keras.backend.floatx', ([], {}), False, 'import keras\n'), (108, 'keras.backend.sum', 'K.sum', (['(y_true[:, :, :4 * num_classes] * (x_bool * (0.5 * x * x) + (1 - x_bool) *\n (x_abs - 0.5)))'], {}), True, 'from keras import backend as K\n'), (196, 'numpy.array', 'np.array', (['image'], {}), True, 'import numpy as np\n'), (239, 'numpy.shape', 'np.shape', (['img'], {}), True, 'import numpy as np\n'), (245, 'numpy.array', 'np.array', (['y[:, :4]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (286, 'numpy.reshape', 'np.reshape', (['classification', '[-1, 1]'], {}), True, 'import numpy as np\n'), (287, 'numpy.reshape', 'np.reshape', (['regression', '[-1, 5]'], {}), True, 'import numpy as np\n'), (289, 'numpy.array', 'np.array', (['img'], {}), True, 'import numpy as np\n'), (218, 'numpy.logical_and', 'np.logical_and', (['(box_w > 1)', '(box_h > 1)'], {}), True, 'import numpy as np\n'), (290, 'numpy.array', 'np.array', (['classification'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (291, 'numpy.array', 'np.array', (['regression'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (294, 'numpy.expand_dims', 'np.expand_dims', (['y', '(0)'], {}), True, 'import numpy as np\n'), (294, 'numpy.expand_dims', 'np.expand_dims', (['tmp_inp', '(0)'], {}), True, 'import numpy as np\n')] |
sorhus/tensorflow | acb1ef68f5aea3b6f7f1e14db588b74134719b5e | # Copyright 2017 The TensorFlow 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 tensorflow as tf
# pylint: disable=g-bad-import-order
import tensorflow.contrib.eager as tfe
from tensorflow.contrib.eager.python.examples.spinn import data
from third_party.examples.eager.spinn import spinn
from tensorflow.contrib.summary import summary_test_util
from tensorflow.python.eager import test
from tensorflow.python.framework import test_util
from tensorflow.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 tf.device("cpu:0"):
labels = tf.random_uniform([batch_size], minval=1, maxval=4, dtype=tf.int64)
prem = tf.random_uniform(
(sequence_length, batch_size), maxval=vocab_size, dtype=tf.int64)
prem_trans = tf.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 = tf.random_uniform(
(sequence_length, batch_size), maxval=vocab_size, dtype=tf.int64)
hypo_trans = tf.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.TensorFlowTestCase):
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 tf.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(tf.float32, out[0].dtype)
self.assertEqual(tf.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 tf.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(tf.float32, out[0].dtype)
self.assertEqual(tf.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 tf.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(tf.random_normal((1, size * 2)))
right_in.append(tf.random_normal((1, size * 2)))
tracking.append(tf.random_normal((1, tracker_size * 2)))
out = reducer(left_in, right_in, tracking=tracking)
self.assertEqual(batch_size, len(out))
self.assertEqual(tf.float32, out[0].dtype)
self.assertEqual((1, size * 2), out[0].shape)
def testReduceTreeLSTM(self):
with tf.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(tf.float32, h.dtype)
self.assertEqual(tf.float32, c.dtype)
self.assertEqual((2, 2), h.shape)
self.assertEqual((2, 2), c.shape)
def testTracker(self):
with tf.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(tf.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(tf.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(tf.float32, out1[0].dtype)
self.assertEqual((1, tracker_size * 2), out1[0].shape)
self.assertEqual(tf.float32, tracker.state.c.dtype)
self.assertEqual((batch_size, tracker_size), tracker.state.c.shape)
self.assertEqual(tf.float32, tracker.state.h.dtype)
self.assertEqual((batch_size, tracker_size), tracker.state.h.shape)
def testSPINN(self):
with tf.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 = tf.random_normal((sequence_length, 1, config.d_proj))
transitions = tf.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=tf.int64)
self.assertEqual(tf.int64, transitions.dtype)
self.assertEqual((num_transitions, 1), transitions.shape)
out = s(buffers, transitions, training=True)
self.assertEqual(tf.float32, out.dtype)
self.assertEqual((1, embedding_dims), out.shape)
def testSNLIClassifierAndTrainer(self):
with tf.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 = tf.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(tf.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(tf.float32, logits.dtype)
self.assertEqual((batch_size, d_out), logits.shape)
# Calculate loss.
loss1 = trainer.loss(labels, logits)
self.assertEqual(tf.float32, loss1.dtype)
self.assertEqual((), loss1.shape)
loss2, logits = trainer.train_batch(
labels, prem, prem_trans, hypo, hypo_trans)
self.assertEqual(tf.float32, loss2.dtype)
self.assertEqual((), loss2.shape)
self.assertEqual(tf.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(tf.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 tf.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 = tf.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.device",
"tensorflow.constant",
"tensorflow.python.eager.test.main",
"tensorflow.contrib.summary.summary_test_util.events_from_file",
"tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary",
"tensorflow.contrib.eager.python.examples.spinn.data.SnliData",
"tensorflow.python.training.checkpoint_utils.list_variables",
"tensorflow.contrib.eager.python.examples.spinn.data.load_word_vectors",
"tensorflow.contrib.eager.num_gpus",
"numpy.array",
"tensorflow.random_uniform",
"tensorflow.random_normal"
] | tensorflow/contrib/eager/python/examples/spinn/spinn_test.py | [(61, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (84, 'collections.namedtuple', 'collections.namedtuple', (['"""Config"""', "['d_hidden', 'd_proj', 'd_tracker', 'predict', 'embed_dropout',\n 'mlp_dropout', 'n_mlp_layers', 'd_mlp', 'd_out', 'projection', 'lr',\n 'batch_size', 'epochs', 'force_cpu', 'logdir', 'log_every', 'dev_every',\n 'save_every', 'lr_decay_every', 'lr_decay_by', 'inference_premise',\n 'inference_hypothesis']"], {}), False, 'import collections\n'), (475, 'tensorflow.python.eager.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.eager import test\n'), (47, 'tensorflow.device', 'tf.device', (['"""cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.random_uniform', 'tf.random_uniform', (['[batch_size]'], {'minval': '(1)', 'maxval': '(4)', 'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.random_uniform', 'tf.random_uniform', (['(sequence_length, batch_size)'], {'maxval': 'vocab_size', 'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.random_uniform', 'tf.random_uniform', (['(sequence_length, batch_size)'], {'maxval': 'vocab_size', 'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (124, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (127, 'shutil.rmtree', 'shutil.rmtree', (['self._temp_data_dir'], {}), False, 'import shutil\n'), (312, 'os.path.join', 'os.path.join', (['snli_1_0_dir', '"""snli_1.0_train.txt"""'], {}), False, 'import os\n'), (313, 'os.makedirs', 'os.makedirs', (['snli_1_0_dir'], {}), False, 'import os\n'), (341, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""glove"""'], {}), False, 'import os\n'), (342, 'os.makedirs', 'os.makedirs', (['glove_dir'], {}), False, 'import os\n'), (343, 'os.path.join', 'os.path.join', (['glove_dir', '"""glove.42B.300d.txt"""'], {}), False, 'import os\n'), (360, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""snli/snli_1.0"""'], {}), False, 'import os\n'), (363, 'tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary', 'data.load_vocabulary', (['self._temp_data_dir'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (364, 'tensorflow.contrib.eager.python.examples.spinn.data.load_word_vectors', 'data.load_word_vectors', (['self._temp_data_dir', 'vocab'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (370, 'third_party.examples.eager.spinn.spinn.train_or_infer_spinn', 'spinn.train_or_infer_spinn', (['embed', 'word2index', 'None', 'None', 'None', 'config'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (376, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""snli/snli_1.0"""'], {}), False, 'import os\n'), (379, 'tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary', 'data.load_vocabulary', (['self._temp_data_dir'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (380, 'tensorflow.contrib.eager.python.examples.spinn.data.load_word_vectors', 'data.load_word_vectors', (['self._temp_data_dir', 'vocab'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (393, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""snli/snli_1.0"""'], {}), False, 'import os\n'), (396, 'tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary', 'data.load_vocabulary', (['self._temp_data_dir'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (397, 'tensorflow.contrib.eager.python.examples.spinn.data.load_word_vectors', 'data.load_word_vectors', (['self._temp_data_dir', 'vocab'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (399, 'tensorflow.contrib.eager.python.examples.spinn.data.SnliData', 'data.SnliData', (['fake_train_file', 'word2index'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (400, 'tensorflow.contrib.eager.python.examples.spinn.data.SnliData', 'data.SnliData', (['fake_train_file', 'word2index'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (401, 'tensorflow.contrib.eager.python.examples.spinn.data.SnliData', 'data.SnliData', (['fake_train_file', 'word2index'], {}), False, 'from tensorflow.contrib.eager.python.examples.spinn import data\n'), (409, 'third_party.examples.eager.spinn.spinn.train_or_infer_spinn', 'spinn.train_or_infer_spinn', (['embed', 'word2index', 'train_data', 'dev_data', 'test_data', 'config'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (415, 'tensorflow.contrib.summary.summary_test_util.events_from_file', 'summary_test_util.events_from_file', (['summary_file'], {}), False, 'from tensorflow.contrib.summary import summary_test_util\n'), (123, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (131, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (136, 'third_party.examples.eager.spinn.spinn._bundle', 'spinn._bundle', (['lstm_iter'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (147, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (150, 'third_party.examples.eager.spinn.spinn._unbundle', 'spinn._unbundle', (['state'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (161, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (165, 'third_party.examples.eager.spinn.spinn.Reducer', 'spinn.Reducer', (['size'], {'tracker_size': 'tracker_size'}), False, 'from third_party.examples.eager.spinn import spinn\n'), (181, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (184, 'third_party.examples.eager.spinn.spinn.Reducer', 'spinn.Reducer', (['size'], {'tracker_size': 'tracker_size'}), False, 'from third_party.examples.eager.spinn import spinn\n'), (186, 'numpy.array', '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'}), True, 'import numpy as np\n'), (189, 'numpy.array', 'np.array', (['[[0, 1], [2, 3]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (190, 'numpy.array', 'np.array', (['[[0, -1], [-2, -3]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (199, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (206, 'third_party.examples.eager.spinn.spinn.Tracker', 'spinn.Tracker', (['tracker_size', '(False)'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (241, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (247, 'collections.namedtuple', 'collections.namedtuple', (['"""Config"""', "['d_hidden', 'd_proj', 'd_tracker', 'predict']"], {}), False, 'import collections\n'), (251, 'third_party.examples.eager.spinn.spinn.SPINN', 'spinn.SPINN', (['config'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (254, 'tensorflow.random_normal', 'tf.random_normal', (['(sequence_length, 1, config.d_proj)'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.constant', 'tf.constant', (['[[3], [3], [2], [3], [3], [3], [2], [2], [2], [3], [3], [3], [2], [3], [3],\n [2], [2], [3], [3], [3], [2], [2], [2], [2], [3], [2], [2]]'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.device', 'tf.device', (['self._test_device'], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.random_normal', 'tf.random_normal', (['(vocab_size, d_embed)'], {}), True, 'import tensorflow as tf\n'), (279, 'third_party.examples.eager.spinn.spinn.SNLIClassifier', 'spinn.SNLIClassifier', (['config', 'embed'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (280, 'third_party.examples.eager.spinn.spinn.SNLIClassifierTrainer', 'spinn.SNLIClassifierTrainer', (['model', 'config.lr'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (387, 'third_party.examples.eager.spinn.spinn.train_or_infer_spinn', 'spinn.train_or_infer_spinn', (['embed', 'word2index', 'None', 'None', 'None', 'config'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (435, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (436, 'tensorflow.device', 'tf.device', (['test_device'], {}), True, 'import tensorflow as tf\n'), (446, 'tensorflow.random_normal', 'tf.random_normal', (['(vocab_size, d_embed)'], {}), True, 'import tensorflow as tf\n'), (449, 'third_party.examples.eager.spinn.spinn.SNLIClassifier', 'spinn.SNLIClassifier', (['config', 'embed'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (450, 'third_party.examples.eager.spinn.spinn.SNLIClassifierTrainer', 'spinn.SNLIClassifierTrainer', (['model', 'config.lr'], {}), False, 'from third_party.examples.eager.spinn import spinn\n'), (460, 'gc.collect', 'gc.collect', ([], {}), False, 'import gc\n'), (461, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (462, 'six.moves.xrange', 'xrange', (['benchmark_iterations'], {}), False, 'from six.moves import xrange\n'), (51, 'numpy.array', '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, \n 3, 2, 2]] * batch_size)'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (57, 'numpy.array', '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, \n 3, 2, 2]] * batch_size)'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (132, 'numpy.array', 'np.array', (['[[0, 1], [2, 3]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (133, 'numpy.array', 'np.array', (['[[0, -1], [-2, -3]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (134, 'numpy.array', 'np.array', (['[[0, 2], [4, 6]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (135, 'numpy.array', 'np.array', (['[[0, -2], [-4, -6]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (148, 'numpy.array', 'np.array', (['[[0, 1, 2], [3, 4, 5]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (149, 'numpy.array', 'np.array', (['[[0, -1, -2], [-3, -4, -5]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (155, 'numpy.array', 'np.array', (['[[0, 1, 2, 0, -1, -2]]'], {}), True, 'import numpy as np\n'), (157, 'numpy.array', 'np.array', (['[[3, 4, 5, -3, -4, -5]]'], {}), True, 'import numpy as np\n'), (368, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""logdir"""'], {}), False, 'import os\n'), (384, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""logdir"""'], {}), False, 'import os\n'), (406, 'os.path.join', 'os.path.join', (['self._temp_data_dir', '"""logdir"""'], {}), False, 'import os\n'), (414, 'os.path.join', 'os.path.join', (['config.logdir', '"""events.out.*"""'], {}), False, 'import os\n'), (423, 'os.path.join', 'os.path.join', (['config.logdir', '"""ckpt*"""'], {}), False, 'import os\n'), (425, 'tensorflow.python.training.checkpoint_utils.list_variables', 'checkpoint_utils.list_variables', (['config.logdir'], {}), False, 'from tensorflow.python.training import checkpoint_utils\n'), (464, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (141, 'numpy.array', 'np.array', (['[[0, 2, 0, -2, 0, 4, 0, -4]]'], {}), True, 'import numpy as np\n'), (143, 'numpy.array', 'np.array', (['[[1, 3, -1, -3, 2, 6, -2, -6]]'], {}), True, 'import numpy as np\n'), (171, 'tensorflow.random_normal', 'tf.random_normal', (['(1, size * 2)'], {}), True, 'import tensorflow as tf\n'), (172, 'tensorflow.random_normal', 'tf.random_normal', (['(1, size * 2)'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.random_normal', 'tf.random_normal', (['(1, tracker_size * 2)'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.random_normal', 'tf.random_normal', (['(batch_size, size * 2)'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.random_normal', 'tf.random_normal', (['(batch_size, size * 2)'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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 TensorFlow 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 tf.group of tf.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(tf.assign_add(ref=variable, value=delta))
with tf.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 tf.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
)
| [
"tensorflow.assign_add",
"tensorflow.control_dependencies"
] | src/tensorforce/tensorforce/core/optimizers/optimizer.py | [(59, 'tensorforce.TensorforceError', 'TensorforceError', (['"""Invalid variables and deltas lists."""'], {}), False, 'from tensorforce import TensorforceError, util\n'), (65, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'assignments'}), True, 'import tensorflow as tf\n'), (66, 'tensorforce.util.no_operation', 'util.no_operation', ([], {}), False, 'from tensorforce import TensorforceError, util\n'), (107, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'deltas'}), True, 'import tensorflow as tf\n'), (108, 'tensorforce.util.no_operation', 'util.no_operation', ([], {}), False, 'from tensorforce import TensorforceError, util\n'), (112, 'tensorforce.TensorforceError', 'TensorforceError', (['"""Invalid trainable variable."""'], {}), False, 'from tensorforce import TensorforceError, util\n'), (63, 'tensorflow.assign_add', 'tf.assign_add', ([], {'ref': 'variable', 'value': 'delta'}), True, 'import tensorflow as tf\n'), (98, 'tensorforce.TensorforceError.unexpected', 'TensorforceError.unexpected', ([], {}), False, 'from tensorforce import TensorforceError, util\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 tensorflow as tf
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 TensorFlow 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 = [tf.zeros_like(tensor=variable) for variable in variables]
previous_perturbations = [tf.zeros_like(tensor=variable) for variable in variables]
if self.unroll_loop:
# Unrolled for loop
for sample in range(self.num_samples):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
tf.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 tf.control_dependencies(control_inputs=(applied,)):
perturbed_loss = fn_loss(**arguments)
direction = tf.sign(x=(unperturbed_loss - perturbed_loss))
deltas = [
delta + direction * perturbation
for delta, perturbation in zip(deltas, perturbations)
]
else:
# TensorFlow while loop
def body(deltas, previous_perturbations):
with tf.control_dependencies(control_inputs=deltas):
perturbations = [
tf.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 tf.control_dependencies(control_inputs=(applied,)):
perturbed_loss = fn_loss(**arguments)
direction = tf.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 tf.control_dependencies(control_inputs=deltas):
num_samples = tf.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 tf.control_dependencies(control_inputs=(applied,)):
# Trivial operation to enforce control dependency
return [util.identity_operation(x=delta) for delta in deltas]
| [
"tensorflow.zeros_like",
"tensorflow.sign",
"tensorflow.control_dependencies"
] | src/tensorforce/tensorforce/core/optimizers/evolutionary.py | [(69, 'tensorflow.zeros_like', 'tf.zeros_like', ([], {'tensor': 'variable'}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.zeros_like', 'tf.zeros_like', ([], {'tensor': 'variable'}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'deltas'}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(applied,)'}), True, 'import tensorflow as tf\n'), (133, 'tensorforce.util.identity_operation', 'util.identity_operation', ([], {'x': 'delta'}), False, 'from tensorforce import util\n'), (75, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'deltas'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(applied,)'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.sign', 'tf.sign', ([], {'x': '(unperturbed_loss - perturbed_loss)'}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'deltas'}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(applied,)'}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.sign', 'tf.sign', ([], {'x': '(unperturbed_loss - perturbed_loss)'}), True, 'import tensorflow as tf\n'), (126, 'tensorforce.util.tf_dtype', 'util.tf_dtype', ([], {'dtype': '"""float"""'}), False, 'from tensorforce import util\n'), (77, 'tensorforce.util.shape', 'util.shape', (['variable'], {}), False, 'from tensorforce import util\n'), (100, 'tensorforce.util.shape', 'util.shape', (['variable'], {}), False, 'from tensorforce import util\n')] |
abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | # Lint as: python2, python3
# Copyright 2018 The TensorFlow 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 tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework import test_util
from tensorflow.python.platform import test
# Number of steps to train model.
TRAIN_STEPS = 1
CONFIG = tf.ConfigProto(device_count={"GPU": 0})
class UnidirectionalSequenceLstmTest(test_util.TensorFlowTestCase):
def setUp(self):
tf.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 tf.keras.layers.StackedRNNCells([
tf.lite.experimental.nn.TFLiteLSTMCell(
self.num_units, use_peepholes=True, forget_bias=1.0, name="rnn1"),
tf.lite.experimental.nn.TFLiteLSTMCell(
self.num_units, num_proj=8, forget_bias=1.0, name="rnn2"),
tf.lite.experimental.nn.TFLiteLSTMCell(
self.num_units // 2,
use_peepholes=True,
num_proj=8,
forget_bias=0,
name="rnn3"),
tf.lite.experimental.nn.TFLiteLSTMCell(
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 = tf.Variable(
tf.random_normal([self.num_units, self.n_classes]))
out_bias = tf.Variable(tf.random_normal([self.n_classes]))
# input image placeholder
x = tf.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 = tf.transpose(x, perm=[1, 0, 2])
outputs, _ = tf.lite.experimental.nn.dynamic_rnn(
lstm_layer, lstm_input, dtype="float32")
outputs = tf.unstack(outputs, axis=0)
else:
lstm_input = tf.unstack(x, self.time_steps, 1)
outputs, _ = tf.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 = tf.matmul(outputs[-1], out_weights) + out_bias
output_class = tf.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 = tf.placeholder("float", [None, self.n_classes])
# Loss function
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
# Optimization
opt = tf.train.AdamOptimizer(
learning_rate=self.learning_rate).minimize(loss)
# Initialize variables
init = tf.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 tf.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.
tf.reset_default_graph()
x, prediction, output_class = self.buildModel(lstm_layer, is_dynamic_rnn)
new_sess = tf.compat.v1.Session(config=CONFIG)
saver = tf.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 tensorflow from session to tflite model then based
on the inputs, run tflite inference and return the results.
Args:
sess: Current tensorflow session.
test_inputs: The test inputs for tflite.
input_tensor: The input tensor of tensorflow graph.
output_tensor: The output tensor of tensorflow graph.
use_mlir_converter: Whether or not to use MLIRConverter to convert the
model.
Returns:
The tflite inference result.
"""
converter = tf.lite.TFLiteConverter.from_session(sess, [input_tensor],
[output_tensor])
tflite = converter.convert()
converter.experimental_enable_mlir_converter = use_mlir_converter
interpreter = tf.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 = tf.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 = tf.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 = tf.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 = tf.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.nn.TFLiteLSTMCell",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.nn.static_rnn",
"tensorflow.lite.TFLiteConverter.from_session",
"tensorflow.lite.experimental.nn.dynamic_rnn",
"tensorflow.train.AdamOptimizer",
"numpy.allclose",
"numpy.reshape",
"tensorflow.lite.Interpreter",
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"tensorflow.python.platform.test.main",
"tensorflow.train.Saver",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.matmul",
"tensorflow.unstack",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.compat.v1.Session",
"tensorflow.random_normal"
] | tensorflow/lite/experimental/examples/lstm/unidirectional_sequence_lstm_test.py | [(32, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'GPU': 0}"}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (38, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""/tmp/data/"""'], {'one_hot': '(True)'}), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), (92, 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, self.time_steps, self.n_input]'], {'name': '"""INPUT_IMAGE"""'}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['prediction'], {'name': '"""OUTPUT_CLASS"""'}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, self.n_classes]'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (134, 'six.moves.range', 'range', (['TRAIN_STEPS'], {}), False, 'from six.moves import range\n'), (160, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (164, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'CONFIG'}), True, 'import tensorflow as tf\n'), (168, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (188, 'numpy.reshape', 'np.reshape', (['b1', '(1, self.time_steps, self.n_input)'], {}), True, 'import numpy as np\n'), (215, 'tensorflow.lite.TFLiteConverter.from_session', 'tf.lite.TFLiteConverter.from_session', (['sess', '[input_tensor]', '[output_tensor]'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.lite.Interpreter', 'tf.lite.Interpreter', ([], {'model_content': 'tflite'}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'CONFIG'}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'CONFIG'}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.random_normal', 'tf.random_normal', (['[self.num_units, self.n_classes]'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.random_normal', 'tf.random_normal', (['[self.n_classes]'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.transpose', 'tf.transpose', (['x'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.lite.experimental.nn.dynamic_rnn', 'tf.lite.experimental.nn.dynamic_rnn', (['lstm_layer', 'lstm_input'], {'dtype': '"""float32"""'}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.unstack', 'tf.unstack', (['outputs'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.unstack', 'tf.unstack', (['x', 'self.time_steps', '(1)'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.nn.static_rnn', 'tf.nn.static_rnn', (['lstm_layer', 'lstm_input'], {'dtype': '"""float32"""'}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.matmul', 'tf.matmul', (['outputs[-1]', 'out_weights'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'prediction', 'labels': 'y'}), True, 'import tensorflow as tf\n'), (252, 'numpy.allclose', 'np.allclose', (['expected_output', 'result'], {'rtol': '(1e-06)', 'atol': '(0.01)'}), True, 'import numpy as np\n'), (272, 'numpy.allclose', 'np.allclose', (['expected_output', 'result'], {'rtol': '(1e-06)', 'atol': '(0.01)'}), True, 'import numpy as np\n'), (58, 'tensorflow.lite.experimental.nn.TFLiteLSTMCell', 'tf.lite.experimental.nn.TFLiteLSTMCell', (['self.num_units'], {'use_peepholes': '(True)', 'forget_bias': '(1.0)', 'name': '"""rnn1"""'}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.lite.experimental.nn.TFLiteLSTMCell', 'tf.lite.experimental.nn.TFLiteLSTMCell', (['self.num_units'], {'num_proj': '(8)', 'forget_bias': '(1.0)', 'name': '"""rnn2"""'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.lite.experimental.nn.TFLiteLSTMCell', 'tf.lite.experimental.nn.TFLiteLSTMCell', (['(self.num_units // 2)'], {'use_peepholes': '(True)', 'num_proj': '(8)', 'forget_bias': '(0)', 'name': '"""rnn3"""'}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.lite.experimental.nn.TFLiteLSTMCell', 'tf.lite.experimental.nn.TFLiteLSTMCell', (['self.num_units'], {'forget_bias': '(1.0)', 'name': '"""rnn4"""'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.learning_rate'}), True, 'import tensorflow as tf\n')] |
oahziur/probability | 8edc2892658b5fac7f2e162e1abdc37d1f9858da | # Copyright 2018 The TensorFlow 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 tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfe = tf.contrib.eager
@tfe.run_all_tests_in_graph_and_eager_modes
class DistributionTest(tf.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, tf.random_normal(shape))
for name, shape in param_shapes.items()])
dist = cls(**params)
self.assertAllEqual(sample_shape, self.evaluate(
tf.shape(dist.sample())))
dist_copy = dist.copy()
self.assertAllEqual(sample_shape,
self.evaluate(tf.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(tf.contrib.util.constant_value(normal.is_scalar_event()))
self.assertTrue(tf.contrib.util.constant_value(normal.is_scalar_batch()))
normal = tfd.Normal([mu], [sigma], validate_args=True)
self.assertTrue(tf.contrib.util.constant_value(normal.is_scalar_event()))
self.assertFalse(tf.contrib.util.constant_value(normal.is_scalar_batch()))
mvn = tfd.MultivariateNormalDiag([mu], [sigma], validate_args=True)
self.assertFalse(tf.contrib.util.constant_value(mvn.is_scalar_event()))
self.assertTrue(tf.contrib.util.constant_value(mvn.is_scalar_batch()))
mvn = tfd.MultivariateNormalDiag([[mu]], [[sigma]], validate_args=True)
self.assertFalse(tf.contrib.util.constant_value(mvn.is_scalar_event()))
self.assertFalse(tf.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 = tf.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(tf.TensorShape(None), lambda: tf.shape(x)))
x = tf.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(tf.TensorShape(None), lambda: tf.shape(x)))
# There's no notion of partially known shapes in eager mode, so exit
# early.
if tf.executing_eagerly():
return
# Test case 3.
x = tf.placeholder_with_default(input=1, shape=None)
is_scalar = normal._is_scalar_helper(x.shape, lambda: tf.shape(x))
self.assertTrue(self.evaluate(is_scalar))
x = tf.placeholder_with_default(input=[1], shape=None)
is_scalar = normal._is_scalar_helper(x.shape, lambda: tf.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 = tf.TensorShape(batch_shape)
self._static_event_shape = tf.TensorShape(event_shape)
super(FakeDistribution, self).__init__(
dtype=tf.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 tf.executing_eagerly():
return
fake_distribution = self._GetFakeDistribution()
# Make a new session since we're playing with static shapes. [And below.]
x = tf.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 = tf.convert_to_tensor([6, 7], dtype=tf.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 = tf.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 = tf.convert_to_tensor([6, 7], dtype=tf.int32)
y = dist._set_sample_static_shape(x, sample_shape)
self.assertAllEqual([6, 7, None, 3, 5], y.shape.as_list())
x = tf.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 = tf.convert_to_tensor([6, 7], dtype=tf.int32)
y = dist._set_sample_static_shape(x, sample_shape)
self.assertAllEqual([6, 7, None, 3, None], y.shape.as_list())
x = tf.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 = tf.convert_to_tensor([6, 7], dtype=tf.int32)
y = dist._set_sample_static_shape(x, sample_shape)
self.assertTrue(y.shape.ndims is None)
x = tf.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 = tf.convert_to_tensor([6, 7], dtype=tf.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 tf.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 tf.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 TensorFlow 1.12.
normal = tfd.Normal(loc=tf.constant(0, tf.float16),
scale=tf.constant(1, tf.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 tf.executing_eagerly():
return
exp = tfd.Exponential(rate=tf.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 tf.executing_eagerly():
return
mvn_dynamic = tfd.MultivariateNormalDiag(
loc=tf.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 TensorFlow 1.12.
normal = tfd.Normal(loc=tf.constant(0, tf.float16),
scale=tf.constant(1, tf.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 tf.executing_eagerly():
return
exp = tfd.Exponential(rate=tf.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 tf.executing_eagerly():
return
mvn_dynamic = tfd.MultivariateNormalDiag(
loc=tf.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=tf.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__":
tf.test.main()
| [
"tensorflow.convert_to_tensor",
"tensorflow.TensorShape",
"tensorflow.executing_eagerly",
"tensorflow.constant",
"tensorflow.shape",
"tensorflow.placeholder_with_default",
"tensorflow.test.main",
"numpy.ones",
"tensorflow.name_scope",
"numpy.float32",
"numpy.zeros",
"tensorflow.random_normal"
] | tensorflow_probability/python/distributions/distribution_test.py | [(378, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '(1)', 'shape': '[]'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '[1]', 'shape': '[1]'}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '(1)', 'shape': 'None'}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '[1]', 'shape': 'None'}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[6, 7]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[6, 7]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[6, 7]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (183, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[6, 7]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[6, 7]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (311, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.name_scope', 'tf.name_scope', (['"""y"""'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.TensorShape', 'tf.TensorShape', (['batch_shape'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.TensorShape', 'tf.TensorShape', (['event_shape'], {}), True, 'import tensorflow as tf\n'), (158, 'numpy.ones', 'np.ones', (['(6, 7, 2, 3, 5)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (167, 'numpy.ones', 'np.ones', (['(6, 7, 2, 3, 5)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (174, 'numpy.ones', 'np.ones', (['(6, 7, 2, 3, 5)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (181, 'numpy.ones', 'np.ones', (['(6, 7, 2, 3, 5)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (188, 'numpy.ones', 'np.ones', (['(6, 7, 2, 3, 5)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (225, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.float16'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.float16'], {}), True, 'import tensorflow as tf\n'), (235, 'numpy.float32', 'np.float32', (['[1.0, 2.0]'], {}), True, 'import numpy as np\n'), (249, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '(1.0)', 'shape': 'None'}), True, 'import tensorflow as tf\n'), (260, 'numpy.zeros', 'np.zeros', (['[2, 2]'], {}), True, 'import numpy as np\n'), (290, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.float16'], {}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.float16'], {}), True, 'import tensorflow as tf\n'), (300, 'numpy.float32', 'np.float32', (['[1.0, 2.0]'], {}), True, 'import numpy as np\n'), (314, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '(1.0)', 'shape': 'None'}), True, 'import tensorflow as tf\n'), (326, 'numpy.zeros', 'np.zeros', (['[2, 2]'], {}), True, 'import numpy as np\n'), (104, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (276, 'numpy.ones', 'np.ones', (['(3, 3)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (342, 'numpy.ones', 'np.ones', (['(3, 3)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (49, 'tensorflow.random_normal', 'tf.random_normal', (['shape'], {}), True, 'import tensorflow as tf\n')] |
oahziur/probability | ca14fa8924749593fd21e2b6389551f964527eec | # Copyright 2018 The TensorFlow 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 tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.internal import test_case
tfd = tfp.distributions
tfe = tf.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 = tf.constant([2.] * 5)
concentration = tf.constant([2.] * 5)
pareto = tfd.Pareto(concentration, scale)
self.assertEqual(self.evaluate(pareto.batch_shape_tensor()), (5,))
self.assertEqual(pareto.batch_shape, tf.TensorShape([5]))
self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), [])
self.assertEqual(pareto.event_shape, tf.TensorShape([]))
def testParetoShapeBroadcast(self):
scale = tf.constant([[3., 2.]])
concentration = tf.constant([[4.], [5.], [6.]])
pareto = tfd.Pareto(concentration, scale)
self.assertAllEqual(self.evaluate(pareto.batch_shape_tensor()), (3, 2))
self.assertAllEqual(pareto.batch_shape, tf.TensorShape([3, 2]))
self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), [])
self.assertEqual(pareto.event_shape, tf.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 = tf.constant([3.] * batch_size)
scale_v = 3.
concentration = tf.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 = tf.constant([2., 3., 4.])
concentration = tf.constant([2.] * batch_size)
pareto = tfd.Pareto(concentration, scale, validate_args=True)
with self.assertRaisesOpError("not in the support"):
x = tf.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 = tf.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 = tf.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 = tf.constant([[2., 4., 5.]] * batch_size)
scale_v = [2., 4., 5.]
concentration = tf.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 = tf.constant([3.] * batch_size)
scale_v = 3.
concentration = tf.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 = tf.constant([[2., 4., 5.]] * batch_size)
scale_v = [2., 4., 5.]
concentration = tf.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 = tf.constant(1.)
concentration = tf.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 = tf.constant(1.)
concentration = tf.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 = tf.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([tf.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__":
tf.test.main()
| [
"tensorflow.TensorShape",
"numpy.log",
"tensorflow.constant",
"numpy.arange",
"tensorflow.placeholder_with_default",
"tensorflow.test.main",
"tensorflow.zeros_like",
"numpy.array",
"scipy.stats.pareto"
] | tensorflow_probability/python/distributions/pareto_test.py | [(349, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (37, 'scipy.stats.pareto', 'stats.pareto', (['concentration'], {'scale': 'scale'}), False, 'from scipy import stats\n'), (40, 'tensorflow.constant', 'tf.constant', (['([2.0] * 5)'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.constant', 'tf.constant', (['([2.0] * 5)'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.constant', 'tf.constant', (['[[3.0, 2.0]]'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.constant', 'tf.constant', (['[[4.0], [5.0], [6.0]]'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.constant', 'tf.constant', (['([3.0] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.constant', 'tf.constant', (['[2.0]'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.constant', 'tf.constant', (['[2.0, 3.0, 4.0]'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.constant', 'tf.constant', (['([2.0] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.constant', 'tf.constant', (['([[2.0, 4.0, 5.0]] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.constant', 'tf.constant', (['([[1.0]] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.constant', 'tf.constant', (['([3.0] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.constant', 'tf.constant', (['[2.0]'], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.constant', 'tf.constant', (['([[2.0, 4.0, 5.0]] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.constant', 'tf.constant', (['([[1.0]] * batch_size)'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), True, 'import tensorflow as tf\n'), (316, 'numpy.arange', 'np.arange', (['(1.0)', '(5.0)'], {}), True, 'import numpy as np\n'), (319, 'numpy.arange', 'np.arange', (['(2.0)', '(10.0)', '(2)'], {}), True, 'import numpy as np\n'), (45, 'tensorflow.TensorShape', 'tf.TensorShape', (['[5]'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.TensorShape', 'tf.TensorShape', (['[]'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.TensorShape', 'tf.TensorShape', (['[3, 2]'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.TensorShape', 'tf.TensorShape', (['[]'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '[2.0, 3.0, 3.0]', 'shape': '[3]'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '[2.0, 2.0, 5.0]', 'shape': '[3]'}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', ([], {'input': '[1.0, 3.0, 5.0]', 'shape': '[3]'}), True, 'import tensorflow as tf\n'), (123, 'numpy.array', 'np.array', (['[[6.0, 7.0, 9.2, 5.0, 6.0, 7.0]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (165, 'numpy.array', 'np.array', (['[[6.0, 7.0, 9.2, 5.0, 6.0, 7.0]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (285, 'numpy.arange', 'np.arange', (['(1)', '(21)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (300, 'numpy.arange', 'np.arange', (['(1)', '(11)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (337, 'tensorflow.zeros_like', 'tf.zeros_like', (['true_kl'], {}), True, 'import tensorflow as tf\n'), (325, 'numpy.log', 'np.log', (['b_concentration'], {}), True, 'import numpy as np\n'), (325, 'numpy.log', 'np.log', (['a_concentration'], {}), True, 'import numpy as np\n'), (324, 'numpy.log', 'np.log', (['a_scale'], {}), True, 'import numpy as np\n'), (324, 'numpy.log', 'np.log', (['b_scale'], {}), True, 'import numpy as np\n')] |
connectthefuture/tensorflow | 93812423fcd5878aa2c1d0b68dc0496980c8519d | # Copyright 2015 The TensorFlow 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 tensorflow as tf
from tensorflow.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(tf.test.TestCase):
def _SparseTensorPlaceholder(self, dtype=None):
if dtype is None: dtype = tf.int32
return tf.SparseTensor(
tf.placeholder(tf.int64),
tf.placeholder(dtype),
tf.placeholder(tf.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 tf.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 tf.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 tf.SparseTensorValue(ind, val, shape)
def testAddTakeMany(self):
with self.test_session(graph=tf.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 = tf.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 = tf.convert_to_tensor(
[handle0_value, handle1_value], dtype=tf.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=tf.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 = tf.convert_to_tensor(
[handle0_value, handle1_value], dtype=tf.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(tf.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 tf.Session() as sess:
with tf.device("/cpu:0"):
indices = tf.Variable(indices)
values = tf.Variable(values)
shape = tf.Variable(shape)
st = tf.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 = tf.serialize_many_sparse(st)
st_deserialized = tf.deserialize_many_sparse(
st_serialized, dtype=values.dtype)
st_deserialized_op = st_deserialized.values.op
tf.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__":
tf.test.main()
| [
"tensorflow.convert_to_tensor",
"tensorflow.device",
"numpy.asarray",
"tensorflow.stack",
"tensorflow.SparseTensorValue",
"numpy.random.randint",
"numpy.testing.assert_equal",
"tensorflow.Graph",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.test.main",
"tensorflow.deserialize_many_sparse",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"numpy.array",
"numpy.random.seed",
"tensorflow.SparseTensor",
"tensorflow.serialize_many_sparse"
] | tensorflow/python/kernel_tests/sparse_tensors_map_ops_test.py | [(234, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.SparseTensorValue', 'tf.SparseTensorValue', (['ind', 'val', 'shape'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.SparseTensorValue', 'tf.SparseTensorValue', (['ind', 'val', 'shape'], {}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.SparseTensorValue', 'tf.SparseTensorValue', (['ind', 'val', 'shape'], {}), True, 'import tensorflow as tf\n'), (187, 'numpy.random.seed', 'np.random.seed', (['(127)'], {}), True, 'import numpy as np\n'), (190, 'numpy.random.randint', 'np.random.randint', (['batch_size'], {'size': 'num_elements', 'dtype': 'np.int64'}), True, 'import numpy as np\n'), (192, 'numpy.arange', 'np.arange', (['num_elements'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (196, 'numpy.asarray', 'np.asarray', (['[batch_size, num_elements]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (40, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.placeholder', 'tf.placeholder', (['dtype'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.stack', 'tf.stack', (['[handle0, handle1]'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[handle0_value, handle1_value]'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (130, 'numpy.array', 'np.array', (['[[0, 0], [0, 1], [2, 0]]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (131, 'numpy.array', 'np.array', (["[b'a', b'b', b'c']"], {}), True, 'import numpy as np\n'), (132, 'numpy.array', 'np.array', (['[4, 5]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (159, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['[handle0_value, handle1_value]'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (45, 'numpy.array', 'np.array', (['[[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]'], {}), True, 'import numpy as np\n'), (49, 'numpy.array', 'np.array', (['[0, 10, 13, 14, 32, 33]'], {}), True, 'import numpy as np\n'), (54, 'numpy.array', 'np.array', (['[5, 6]'], {}), True, 'import numpy as np\n'), (58, 'numpy.array', 'np.array', (['[[0, 0], [1, 0], [1, 2], [1, 3], [2, 2], [2, 3]]'], {}), True, 'import numpy as np\n'), (62, 'numpy.array', 'np.array', (['[0, 10, 13, 14, 32, 33]'], {}), True, 'import numpy as np\n'), (67, 'numpy.array', 'np.array', (['[3, 4]'], {}), True, 'import numpy as np\n'), (71, 'numpy.array', 'np.array', (['[[0, 0, 0]]'], {}), True, 'import numpy as np\n'), (72, 'numpy.array', 'np.array', (['[0]'], {}), True, 'import numpy as np\n'), (73, 'numpy.array', 'np.array', (['[3, 4, 5]'], {}), True, 'import numpy as np\n'), (78, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (79, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (101, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (102, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (150, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (172, 'numpy.arange', 'np.arange', (['(6)'], {}), True, 'import numpy as np\n'), (198, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.Variable', 'tf.Variable', (['indices'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.Variable', 'tf.Variable', (['values'], {}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.Variable', 'tf.Variable', (['shape'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.SparseTensor', 'tf.SparseTensor', (['indices', 'values', 'shape'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.serialize_many_sparse', 'tf.serialize_many_sparse', (['st'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.deserialize_many_sparse', 'tf.deserialize_many_sparse', (['st_serialized'], {'dtype': 'values.dtype'}), True, 'import tensorflow as tf\n'), (218, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['st_roundtrip_values.values', 'st_deserialized_values.values'], {}), True, 'import numpy as np\n'), (220, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['st_roundtrip_values.indices', 'st_deserialized_values.indices'], {}), True, 'import numpy as np\n'), (222, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['st_roundtrip_values.dense_shape', 'st_deserialized_values.dense_shape'], {}), True, 'import numpy as np\n'), (77, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n')] |
connectthefuture/tensorflow | 93812423fcd5878aa2c1d0b68dc0496980c8519d | # Copyright 2016 The TensorFlow 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 tensorflow as tf
from tensorflow.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(tf.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
tf.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:
tf.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
tf.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:
tf.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 = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)
config = tf.ConfigProto(
graph_options=tf.GraphOptions(optimizer_options=optimizer_options))
with tf.Session(config=config) as sess:
with tf.device("/cpu:0" if not use_gpu else None):
param_op = tf.group(random_ops.parameterized_truncated_normal(shape))
naive_op = tf.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(tf.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__":
tf.test.main()
| [
"tensorflow.device",
"tensorflow.python.ops.random_ops.truncated_normal",
"numpy.random.seed",
"numpy.power",
"numpy.isnan",
"tensorflow.OptimizerOptions",
"tensorflow.test.main",
"tensorflow.python.ops.random_ops.parameterized_truncated_normal",
"tensorflow.GraphOptions",
"tensorflow.Session",
"tensorflow.set_random_seed",
"numpy.double"
] | tensorflow/python/kernel_tests/parameterized_truncated_normal_op_test.py | [(186, 'numpy.random.seed', 'np.random.seed', (['(1618)'], {}), True, 'import numpy as np\n'), (189, 'tensorflow.OptimizerOptions', 'tf.OptimizerOptions', ([], {'opt_level': 'tf.OptimizerOptions.L0'}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (40, 'numpy.double', 'np.double', (['mean'], {}), True, 'import numpy as np\n'), (41, 'numpy.double', 'np.double', (['stddev'], {}), True, 'import numpy as np\n'), (193, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (96, 'math.sqrt', 'math.sqrt', (['total_variance'], {}), False, 'import math\n'), (111, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), True, 'import tensorflow as tf\n'), (119, 'functools.reduce', 'functools.reduce', (['(lambda x, y: x * y)', 'shape', '(1)'], {}), False, 'import functools\n'), (135, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.GraphOptions', 'tf.GraphOptions', ([], {'optimizer_options': 'optimizer_options'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.device', 'tf.device', (["('/cpu:0' if not use_gpu else None)"], {}), True, 'import tensorflow as tf\n'), (64, 'numpy.double', 'np.double', (['(0.0)'], {}), True, 'import numpy as np\n'), (195, 'tensorflow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', (['shape'], {}), False, 'from tensorflow.python.ops import random_ops\n'), (196, 'tensorflow.python.ops.random_ops.truncated_normal', 'random_ops.truncated_normal', (['shape'], {}), False, 'from tensorflow.python.ops import random_ops\n'), (66, 'numpy.power', 'np.power', (['self.maxval', '(k - 1)'], {}), True, 'import numpy as np\n'), (67, 'numpy.power', 'np.power', (['self.minval', '(k - 1)'], {}), True, 'import numpy as np\n'), (113, 'tensorflow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', (['shape', 'mean', 'stddev', 'minval', 'maxval'], {}), False, 'from tensorflow.python.ops import random_ops\n'), (137, 'tensorflow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', (['shape', 'mean', 'stddev', 'minval', 'maxval'], {}), False, 'from tensorflow.python.ops import random_ops\n'), (140, 'numpy.isnan', 'np.isnan', (['samples'], {}), True, 'import numpy as np\n'), (116, 'numpy.isnan', 'np.isnan', (['samples'], {}), True, 'import numpy as np\n')] |
Pandinosaurus/model-optimization | 12dc84dd34ee3c6eb08b381c0abcd65b31a42366 | # Copyright 2021 The TensorFlow 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 tensorflow as tf
from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry
from tensorflow_model_optimization.python.core.quantization.keras import quant_ops
from tensorflow_model_optimization.python.core.quantization.keras import quantizers
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_registry
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantizers
layers = tf.keras.layers
K = tf.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 = tf.reshape(t, shape=(-1,))
uniques, index = tf.unique(t_flatten)
return uniques, tf.reshape(index, shape=tf.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 tf.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 = tf.size(centroids)
if self.preserve_sparsity:
sparsity_mask = tf.math.divide_no_nan(weights, weights)
zero_idx = tf.argmin(tf.abs(centroids), axis=-1)
centroids_mask = 1.0 - tf.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=tf.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=tf.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 = tf.dtypes.cast(
clustering_impl.get_pulling_indices(ori_weights_tf),
lookup.dtype
)
pulling_indices_tf = layer.add_weight(
PULLING_INDICES,
shape=lookup.shape,
initializer=tf.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(
tf.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(tf.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 = tf.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.multiply",
"tensorflow.unique",
"tensorflow.shape",
"tensorflow.reduce_any",
"tensorflow.reshape",
"tensorflow.one_hot",
"tensorflow.math.divide_no_nan",
"tensorflow.size",
"tensorflow.abs"
] | tensorflow_model_optimization/python/core/quantization/keras/collaborative_optimizations/cluster_preserve/cluster_preserve_quantize_registry.py | [(61, 'tensorflow.reshape', 'tf.reshape', (['t'], {'shape': '(-1,)'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.unique', 'tf.unique', (['t_flatten'], {}), True, 'import tensorflow as tf\n'), (296, 'tensorflow.size', 'tf.size', (['centroids'], {}), True, 'import tensorflow as tf\n'), (422, 'tensorflow_model_optimization.python.core.quantization.keras.quant_ops.LastValueQuantize', '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'}), False, 'from tensorflow_model_optimization.python.core.quantization.keras import quant_ops\n'), (454, 'tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_quantizers.Default8BitConvWeightsQuantizer.__init__', 'default_8bit_quantizers.Default8BitConvWeightsQuantizer.__init__', (['self'], {}), False, 'from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantizers\n'), (292, 'logging.warning', 'logging.warning', (['"""Input layer does not contain zero weights, so apply CQAT instead."""'], {}), False, 'import logging\n'), (299, 'tensorflow.math.divide_no_nan', 'tf.math.divide_no_nan', (['weights', 'weights'], {}), True, 'import tensorflow as tf\n'), (461, 'tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_quantizers.Default8BitConvWeightsQuantizer.build', 'default_8bit_quantizers.Default8BitConvWeightsQuantizer.build', (['self', 'tensor_shape', 'name', 'layer'], {}), False, 'from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantizers\n'), (63, 'tensorflow.shape', 'tf.shape', (['t'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow_model_optimization.python.core.quantization.keras.default_8bit.default_8bit_quantize_registry.Default8BitQuantizeRegistry', 'default_8bit_quantize_registry.Default8BitQuantizeRegistry', ([], {}), False, 'from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_registry\n'), (290, 'tensorflow.reduce_any', 'tf.reduce_any', (['(weights == 0)'], {}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.abs', 'tf.abs', (['centroids'], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.one_hot', 'tf.one_hot', (['zero_idx', 'num_centroids'], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow_model_optimization.python.core.clustering.keras.clustering_registry.ClusteringLookupRegistry', 'clustering_registry.ClusteringLookupRegistry', ([], {}), False, 'from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry\n'), (417, 'tensorflow.multiply', 'tf.multiply', (['inputs', 'weights[SPARSITY_MASK]'], {}), True, 'import tensorflow as tf\n'), (396, 'tensorflow.multiply', 'tf.multiply', (['weights[ORIGINAL_WEIGHTS]', 'weights[SPARSITY_MASK]'], {}), True, 'import tensorflow as tf\n')] |
jdehotin/TensorFlow | a6c5f8e4e013e54fed8dfcf49fb6de365f018022 | # Copyright 2016 The TensorFlow 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 tensorflow as tf
distributions = tf.contrib.distributions
class QuantizedDistributionTest(tf.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=tf.zeros(
batch_shape, dtype=tf.float32),
b=10 * tf.ones(
batch_shape, dtype=tf.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=tf.zeros(
batch_shape, dtype=tf.float32),
sigma=tf.ones(
batch_shape, dtype=tf.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 = tf.Variable(0., name="mu", dtype=dtype)
sigma = tf.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)
tf.initialize_all_variables().run()
proba = qdist.log_prob(x)
grads = tf.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 = tf.Variable(0.0, name="mu")
sigma = tf.Variable(1.0, name="sigma")
qdist = distributions.QuantizedDistribution(
base_dist_cls=distributions.Normal,
mu=mu,
sigma=sigma)
x = tf.ceil(4 * self._rng.rand(100).astype(np.float32) - 2)
tf.initialize_all_variables().run()
proba = qdist.prob(x)
self._assert_all_finite(proba.eval())
grads = tf.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=tf.zeros(batch_shape),
sigma=tf.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__":
tf.test.main()
| [
"numpy.sqrt",
"tensorflow.Variable",
"numpy.isfinite",
"tensorflow.zeros",
"numpy.arange",
"tensorflow.gradients",
"tensorflow.test.main",
"tensorflow.ones",
"numpy.ones",
"scipy.stats.norm",
"tensorflow.initialize_all_variables",
"numpy.random.RandomState"
] | tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py | [(459, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (30, 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), True, 'import numpy as np\n'), (250, 'scipy.stats.norm', 'stats.norm', (['mu', 'sigma'], {}), False, 'from scipy import stats\n'), (272, 'scipy.stats.norm', 'stats.norm', (['mu', 'sigma'], {}), False, 'from scipy import stats\n'), (293, 'scipy.stats.norm', 'stats.norm', (['(0.0)', '(1.0)'], {}), False, 'from scipy import stats\n'), (327, 'scipy.stats.norm', 'stats.norm', (['(0.0)', '(1.0)'], {}), False, 'from scipy import stats\n'), (374, 'tensorflow.Variable', 'tf.Variable', (['(0.0)'], {'name': '"""mu"""'}), True, 'import tensorflow as tf\n'), (375, 'tensorflow.Variable', 'tf.Variable', (['(1.0)'], {'name': '"""sigma"""'}), True, 'import tensorflow as tf\n'), (387, 'tensorflow.gradients', 'tf.gradients', (['proba', '[mu, sigma]'], {}), True, 'import tensorflow as tf\n'), (148, 'numpy.ones', 'np.ones', (['batch_shape'], {}), True, 'import numpy as np\n'), (355, 'tensorflow.Variable', 'tf.Variable', (['(0.0)'], {'name': '"""mu"""', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.Variable', 'tf.Variable', (['(1.0)'], {'name': '"""sigma"""', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (366, 'tensorflow.gradients', 'tf.gradients', (['proba', '[mu, sigma]'], {}), True, 'import tensorflow as tf\n'), (33, 'numpy.isfinite', 'np.isfinite', (['array'], {}), True, 'import numpy as np\n'), (138, 'tensorflow.zeros', 'tf.zeros', (['batch_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.zeros', 'tf.zeros', (['batch_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (172, 'tensorflow.ones', 'tf.ones', (['batch_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (229, 'numpy.sqrt', 'np.sqrt', (['n_samples'], {}), True, 'import numpy as np\n'), (382, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n'), (441, 'tensorflow.zeros', 'tf.zeros', (['batch_shape'], {}), True, 'import tensorflow as tf\n'), (442, 'tensorflow.ones', 'tf.ones', (['batch_shape'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.ones', 'tf.ones', (['batch_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (361, 'numpy.arange', 'np.arange', (['(-100)', '(100)', '(2)'], {}), True, 'import numpy as np\n'), (363, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n')] |
slomrafgrav/models | e498d28503fd4a12d1fa9ade41891f2f9601c674 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
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 = tf.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 tf.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()
| [
"tensorflow.variable_scope"
] | research/object_detection/models/ssd_inception_v2_feature_extractor.py | [(107, 'object_detection.utils.shape_utils.check_min_image_dim', 'shape_utils.check_min_image_dim', (['(33)', 'preprocessed_inputs'], {}), False, 'from object_detection.utils import shape_utils\n'), (118, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""InceptionV2"""'], {'reuse': 'self._reuse_weights'}), True, 'import tensorflow as tf\n'), (126, 'object_detection.models.feature_map_generators.multi_resolution_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'}), False, 'from object_detection.models import feature_map_generators\n'), (121, 'object_detection.utils.ops.pad_to_multiple', 'ops.pad_to_multiple', (['preprocessed_inputs', 'self._pad_to_multiple'], {}), False, 'from object_detection.utils import ops\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 tensorflow as tf
import tensorflow.contrib.metrics as metrics
import tensorflow.contrib.rnn as rnn
tf.logging.set_verbosity(tf.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 = tf.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 = tf.stack(inputs, axis = 0)
labels = tf.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 = tf.gfile.Glob(filename)
# Create dataset from file list
dataset = tf.data.TextLineDataset(file_list).map(decode_csv)
if mode == tf.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 tensorflow 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 = tf.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 = tf.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 = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS]))
bias = tf.Variable(tf.random_normal([N_OUTPUTS]))
predictions = tf.matmul(outputs, weight) + bias
# 2. Loss function, training/eval ops
if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL:
loss = tf.losses.mean_squared_error(labels, predictions)
train_op = tf.contrib.layers.optimize_loss(
loss = loss,
global_step = tf.train.get_global_step(),
learning_rate = 0.01,
optimizer = "SGD")
eval_metric_ops = {
"rmse": tf.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": tf.estimator.export.PredictOutput(outputs = predictions)}
# 4. Return EstimatorSpec
return tf.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: tf.placeholder(tf.float32, [None, N_INPUTS])
}
features = {
key: tf.expand_dims(tensor, -1)
for key, tensor in feature_placeholders.items()
}
features[TIMESERIES_COL] = tf.squeeze(features[TIMESERIES_COL], axis = [2])
return tf.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 = tf.estimator.Estimator(model_fn = simple_rnn,
model_dir = output_dir)
train_spec = tf.estimator.TrainSpec(read_dataset('train.csv',
tf.estimator.ModeKeys.TRAIN,
512),
max_steps = 1000)
exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)
eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv',
tf.estimator.ModeKeys.EVAL,
512),
steps = None,
exporters = exporter)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
| [
"tensorflow.stack",
"tensorflow.data.TextLineDataset",
"tensorflow.keras.estimator.model_to_estimator",
"tensorflow.estimator.train_and_evaluate",
"tensorflow.decode_csv",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.squeeze",
"tensorflow.train.get_global_step",
"tensorflow.logging.set_verbosity",
"tensorflow.estimator.export.ServingInputReceiver",
"tensorflow.keras.models.Sequential",
"tensorflow.estimator.LatestExporter",
"tensorflow.matmul",
"tensorflow.estimator.Estimator",
"tensorflow.keras.layers.Dense",
"tensorflow.metrics.root_mean_squared_error",
"tensorflow.placeholder",
"tensorflow.gfile.Glob",
"tensorflow.contrib.rnn.static_rnn",
"tensorflow.split",
"tensorflow.losses.mean_squared_error",
"tensorflow.keras.layers.Activation",
"tensorflow.contrib.rnn.BasicLSTMCell",
"tensorflow.expand_dims",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.random_normal"
] | courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py | [(21, 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.keras.models.Sequential', 'keras.models.Sequential', ([], {}), False, 'from tensorflow import keras\n'), (82, 'tensorflow.keras.estimator.model_to_estimator', 'keras.estimator.model_to_estimator', (['model'], {'model_dir': 'output_dir'}), False, 'from tensorflow import keras\n'), (87, 'tensorflow.split', 'tf.split', (['features[TIMESERIES_COL]', 'N_INPUTS', '(1)'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.contrib.rnn.BasicLSTMCell', 'rnn.BasicLSTMCell', (['LSTM_SIZE'], {'forget_bias': '(1.0)'}), True, 'import tensorflow.contrib.rnn as rnn\n'), (91, 'tensorflow.contrib.rnn.static_rnn', 'rnn.static_rnn', (['lstm_cell', 'x'], {'dtype': 'tf.float32'}), True, 'import tensorflow.contrib.rnn as rnn\n'), (125, 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'predictions': 'predictions_dict', 'loss': 'loss', 'train_op': 'train_op', 'eval_metric_ops': 'eval_metric_ops', 'export_outputs': 'export_outputs'}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.squeeze', 'tf.squeeze', (['features[TIMESERIES_COL]'], {'axis': '[2]'}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.estimator.export.ServingInputReceiver', 'tf.estimator.export.ServingInputReceiver', (['features', 'feature_placeholders'], {}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.estimator.LatestExporter', 'tf.estimator.LatestExporter', (['"""exporter"""', 'serving_input_fn'], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.estimator.train_and_evaluate', 'tf.estimator.train_and_evaluate', (['estimator', 'train_spec', 'eval_spec'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.gfile.Glob', 'tf.gfile.Glob', (['filename'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(32)'], {'input_shape': '(N_INPUTS,)', 'name': 'TIMESERIES_INPUT_LAYER'}), False, 'from tensorflow import keras\n'), (77, 'tensorflow.keras.layers.Activation', 'keras.layers.Activation', (['"""relu"""'], {}), False, 'from tensorflow import keras\n'), (78, 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {}), False, 'from tensorflow import keras\n'), (98, 'tensorflow.random_normal', 'tf.random_normal', (['[LSTM_SIZE, N_OUTPUTS]'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.random_normal', 'tf.random_normal', (['[N_OUTPUTS]'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.matmul', 'tf.matmul', (['outputs', 'weight'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['labels', 'predictions'], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.estimator.export.PredictOutput', 'tf.estimator.export.PredictOutput', ([], {'outputs': 'predictions'}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, N_INPUTS]'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.expand_dims', 'tf.expand_dims', (['tensor', '(-1)'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.estimator.Estimator', 'tf.estimator.Estimator', ([], {'model_fn': 'simple_rnn', 'model_dir': 'output_dir'}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.decode_csv', 'tf.decode_csv', (['line'], {'record_defaults': 'DEFAULTS'}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.stack', 'tf.stack', (['inputs'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.stack', 'tf.stack', (['labels'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.metrics.root_mean_squared_error', 'tf.metrics.root_mean_squared_error', (['labels', 'predictions'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.data.TextLineDataset', 'tf.data.TextLineDataset', (['file_list'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), True, 'import tensorflow as tf\n')] |
hartmanwilliam/federated | ecf51cdf8b86cbd000f6edc5715dc904bce07540 | # Lint as: python3
# Copyright 2019, The TensorFlow 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 tensorflow as tf
import tensorflow_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 = tf.map_fn(lambda x: x[:-1], chunk)
target_text = tf.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 = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(vocab, table_values),
num_oov_buckets=1)
def to_ids(example):
sentence = tf.reshape(example['tokens'], shape=[1])
words = tf.strings.split(sentence, sep=' ').values
truncated_words = words[:max_seq_len]
tokens = table.lookup(truncated_words) + 1
tokens = tf.cond(
tf.less(tf.size(tokens), max_seq_len),
lambda: tf.concat([tokens, [eos]], 0), lambda: tokens)
return tf.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=tf.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=tf.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 TFF.
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=tf.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=tf.data.experimental.AUTOTUNE),
max_seq_len, batch_size)
| [
"tensorflow.concat",
"tensorflow.reshape",
"tensorflow.strings.split",
"tensorflow.map_fn",
"tensorflow.lookup.KeyValueTensorInitializer",
"tensorflow.size"
] | tensorflow_federated/python/research/optimization/stackoverflow/dataset.py | [(27, 'tensorflow_federated.simulation.datasets.stackoverflow.load_word_counts', 'tff.simulation.datasets.stackoverflow.load_word_counts', ([], {}), True, 'import tensorflow_federated as tff\n'), (42, 'tensorflow.map_fn', 'tf.map_fn', (['(lambda x: x[:-1])', 'chunk'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.map_fn', 'tf.map_fn', (['(lambda x: x[1:])', 'chunk'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow_federated.simulation.datasets.stackoverflow.load_data', 'tff.simulation.datasets.stackoverflow.load_data', ([], {}), True, 'import tensorflow_federated as tff\n'), (252, 'tensorflow_federated.simulation.datasets.stackoverflow.load_data', 'tff.simulation.datasets.stackoverflow.load_data', ([], {}), True, 'import tensorflow_federated as tff\n'), (53, 'tensorflow.lookup.KeyValueTensorInitializer', 'tf.lookup.KeyValueTensorInitializer', (['vocab', 'table_values'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.reshape', 'tf.reshape', (["example['tokens']"], {'shape': '[1]'}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.concat', 'tf.concat', (['[[bos], tokens]', '(0)'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.strings.split', 'tf.strings.split', (['sentence'], {'sep': '""" """'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.size', 'tf.size', (['tokens'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.concat', 'tf.concat', (['[tokens, [eos]]', '(0)'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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
tf.app.flags.DEFINE_integer(
'num_readers', 16,#16
'The number of parallel readers that read data from the dataset.')
tf.app.flags.DEFINE_integer(
'num_preprocessing_threads', 48,#48
'The number of threads used to create the batches.')
tf.app.flags.DEFINE_integer(
'num_cpu_threads', 0,
'The number of cpu cores used to train.')
tf.app.flags.DEFINE_float(
'gpu_memory_fraction', 1., 'GPU memory fraction to use.')
# scaffold related configuration
tf.app.flags.DEFINE_string(
'data_dir', '../Datasets/tfrecords',#'/media/rs/0E06CD1706CD0127/Kapok/Chi/Datasets/tfrecords',
'The directory where the dataset input data is stored.')
tf.app.flags.DEFINE_string(
'dataset_name', '{}_????', 'The pattern of the dataset name to load.')
tf.app.flags.DEFINE_string(
'model_dir', './logs_sext_cpn/',
'The parent directory where the model will be stored.')
tf.app.flags.DEFINE_integer(
'log_every_n_steps', 10,
'The frequency with which logs are print.')
tf.app.flags.DEFINE_integer(
'save_summary_steps', 100,
'The frequency with which summaries are saved, in seconds.')
tf.app.flags.DEFINE_integer(
'save_checkpoints_secs', 3600,
'The frequency with which the model is saved, in seconds.')
# model related configuration
tf.app.flags.DEFINE_integer(
'train_image_size', 384,
'The size of the input image for the model to use.')
tf.app.flags.DEFINE_integer(
'heatmap_size', 96,
'The size of the output heatmap of the model.')
tf.app.flags.DEFINE_string(
'backbone', 'seresnext50',#or seresnext50 seresnet50
'The backbone network to use for feature pyramid.')
tf.app.flags.DEFINE_float(
'heatmap_sigma', 1.,
'The sigma of Gaussian which generate the target heatmap.')
tf.app.flags.DEFINE_float(
'bbox_border', 25.,
'The nearest distance of the crop border to al keypoints.')
tf.app.flags.DEFINE_integer(
'train_epochs', 50,
'The number of epochs to use for training.')
tf.app.flags.DEFINE_integer(
'epochs_per_eval', 20,
'The number of training epochs to run between evaluations.')
tf.app.flags.DEFINE_integer(
'batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_integer(
'xt_batch_size', 10,
'Batch size for training and evaluation.')
tf.app.flags.DEFINE_boolean(
'use_ohkm', True,
'Wether we will use the ohkm for hard keypoints.')
tf.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 TensorFlow was built for CPU or GPU.')
# optimizer related configuration
tf.app.flags.DEFINE_integer(
'tf_random_seed', 20180417, 'Random seed for TensorFlow initializers.')
tf.app.flags.DEFINE_float(
'weight_decay', 1e-5, 'The weight decay on the model weights.')
tf.app.flags.DEFINE_float(
'mse_weight', 1., 'The weight decay on the model weights.')
tf.app.flags.DEFINE_float(
'momentum', 0.9,
'The momentum for the MomentumOptimizer and RMSPropOptimizer.')
tf.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')#1e-3
tf.app.flags.DEFINE_float(
'end_learning_rate', 0.000001,
'The minimal end learning rate used by a polynomial decay learning rate.')
tf.app.flags.DEFINE_float(
'warmup_learning_rate', 0.00001,
'The start warm-up learning rate to avoid NAN.')
tf.app.flags.DEFINE_integer(
'warmup_steps', 100,
'The total steps to warm-up.')
# for learning rate piecewise_constant decay
tf.app.flags.DEFINE_string(
'decay_boundaries', '2, 3',
'Learning rate decay boundaries by global_step (comma-separated list).')
tf.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
tf.app.flags.DEFINE_string(
'checkpoint_path', './model',
'The path to a checkpoint from which to fine-tune.')
tf.app.flags.DEFINE_string(
'checkpoint_model_scope', '',
'Model scope in the checkpoint. None if the same as the trained model.')
tf.app.flags.DEFINE_string(
#'blouse', 'dress', 'outwear', 'skirt', 'trousers', 'all'
'model_scope', None,
'Model scope name used to replace the name_scope in checkpoint.')
tf.app.flags.DEFINE_string(
'checkpoint_exclude_scopes', None,
'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.')
tf.app.flags.DEFINE_boolean(
'ignore_missing_vars', True,
'When restoring a checkpoint would ignore missing variables.')
tf.app.flags.DEFINE_boolean(
'run_on_cloud', False,
'Wether we will train on cloud.')
tf.app.flags.DEFINE_boolean(
'seq_train', False,
'Wether we will train a sequence model.')
tf.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 = tf.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 = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),
tf.constant(config.global_norm_lvalues, dtype=tf.int64)), 0)
rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),
tf.constant(config.global_norm_rvalues, dtype=tf.int64)), 1)
else:
lnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),
tf.constant(config.local_norm_lvalues, dtype=tf.int64)), 0)
rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),
tf.constant(config.local_norm_rvalues, dtype=tf.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 = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])
pred_max = tf.reduce_max(predictions, axis=-1)
pred_indices = tf.argmax(predictions, axis=-1)
pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)
width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)
pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)
if clip_at_zero:
pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)
if config.PRED_DEBUG:
pred_indices_ = tf.squeeze(pred_indices)
image_ = tf.squeeze(image) * 255.
pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)
pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size])
if data_format == 'channels_first':
image_ = tf.transpose(image_, perm=(1, 2, 0))
save_image_op = tf.py_func(save_image_with_heatmap,
[image_, height, width,
heatmap_size,
tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),
tf.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]],
tf.int64, stateful=True)
with tf.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 tf.name_scope(name, "gaussian_blur", [inputs]):
data_format_ = 'NHWC' if data_format=='channels_last' else 'NCHW'
if data_format_ == 'NHWC':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
ksize = int(6 * sigma + 1.)
x = tf.expand_dims(tf.range(ksize, delta=1, dtype=tf.float32), axis=1)
y = tf.transpose(x, [1, 0])
kernel_matrix = tf.exp(- ((x - ksize/2.) ** 2 + (y - ksize/2.) ** 2) / (2 * sigma ** 2))
#print(kernel_matrix)
kernel_filter = tf.reshape(kernel_matrix, [ksize, ksize, 1, 1])
kernel_filter = tf.tile(kernel_filter, [1, 1, inputs_filters, 1])
#kernel_filter = tf.transpose(kernel_filter, [1, 0, 2, 3])
outputs = tf.nn.depthwise_conv2d(inputs, kernel_filter, strides=[1, 1, 1, 1], padding='SAME', data_format=data_format_, name='blur')
if data_format_ == 'NHWC':
outputs = tf.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 = tf.shape(features)[0]
#features= tf.ones_like(features)
with tf.variable_scope(params['model_scope'], default_name=None, values=[features], reuse=tf.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 == tf.estimator.ModeKeys.TRAIN), params['data_format'])
if params['data_format'] == 'channels_last':
pred_outputs = [tf.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 = tf.reshape(255.*tf.one_hot(tf.ones_like(key_v,tf.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 = tf.ones_like(norm_value)
# score_map = tf.reshape(tf.one_hot(tf.ones_like(key_v,tf.int64)*(31*64+31), params['heatmap_size']*params['heatmap_size']), [cur_batch_size,-1,params['heatmap_size'],params['heatmap_size']])
#with tf.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 = tf.metrics.mean_squared_error(score_map, targets,
# weights=1.0 / tf.cast(cur_batch_size, tf.float32),
# name='last_pred_mse')
# filter all invisible keypoint maybe better for this task
# all_visible = tf.logical_and(key_v>0, isvalid>0)
# targets_list = [tf.boolean_mask(targets_list[ind], all_visible) for ind in list(range(len(targets_list)))]
# pred_outputs = [tf.boolean_mask(pred_outputs[ind], all_visible, name='boolean_mask_{}'.format(ind)) for ind in list(range(len(pred_outputs)))]
all_visible = tf.expand_dims(tf.expand_dims(tf.cast(tf.logical_and(key_v>0, isvalid>0), tf.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 = tf.reduce_sum(tf.squared_difference(targets, pred_outputs[-1]), axis=-1)
last_pred_mse = tf.metrics.mean_absolute_error(sq_diff, tf.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 = tf.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 * tf.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind],
weights=1.0 / tf.cast(cur_batch_size, tf.float32),
scope='loss_{}'.format(pred_ind),
loss_collection=None,#tf.GraphKeys.LOSSES,
# mean all elements of all pixels in all batch
reduction=tf.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements
temp_loss = tf.reduce_mean(tf.reshape(tf.losses.mean_squared_error(targets_list[-1], pred_outputs[-1], weights=1.0, loss_collection=None, reduction=tf.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 = tf.nn.top_k(temp_loss, k=num_topk, sorted=True)[1]
gather_row = tf.reshape(tf.tile(tf.reshape(tf.range(cur_batch_size), [-1, 1]), [1, num_topk]), [-1, 1])
gather_indcies = tf.stop_gradient(tf.stack([gather_row, tf.reshape(gather_col, [-1, 1])], axis=-1))
select_targets = tf.gather_nd(targets_list[-1], gather_indcies)
select_heatmap = tf.gather_nd(pred_outputs[-1], gather_indcies)
mse_loss_list.append(tf.losses.mean_squared_error(select_targets, select_heatmap,
weights=1.0 / tf.cast(cur_batch_size, tf.float32),
scope='loss_{}'.format(len(pred_outputs) - 1),
loss_collection=None,#tf.GraphKeys.LOSSES,
# mean all elements of all pixels in all batch
reduction=tf.losses.Reduction.MEAN))
else:
for pred_ind in list(range(len(pred_outputs))):
mse_loss_list.append(tf.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind],
weights=1.0 / tf.cast(cur_batch_size, tf.float32),
scope='loss_{}'.format(pred_ind),
loss_collection=None,#tf.GraphKeys.LOSSES,
# mean all elements of all pixels in all batch
reduction=tf.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements
mse_loss = tf.multiply(params['mse_weight'], tf.add_n(mse_loss_list), name='mse_loss')
tf.summary.scalar('mse', mse_loss)
tf.losses.add_loss(mse_loss)
# bce_loss_list = []
# for pred_ind in list(range(len(pred_outputs))):
# bce_loss_list.append(tf.reduce_mean(tf.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 = tf.multiply(params['mse_weight'] / params['num_stacks'], tf.add_n(bce_loss_list), name='mse_loss')
# tf.summary.scalar('mse', mse_loss)
# tf.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'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name])
total_loss = tf.identity(loss, name='total_loss')
tf.summary.scalar('loss', total_loss)
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)
if mode == tf.estimator.ModeKeys.TRAIN:
global_step = tf.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 = tf.train.piecewise_constant(tf.cast(global_step, tf.int32),
[params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']],
lr_values)
truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate')
tf.summary.scalar('lr', truncated_learning_rate)
optimizer = tf.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 = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss, global_step)
else:
train_op = None
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=loss,
train_op=train_op,
eval_metric_ops=metrics,
scaffold=tf.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 = tf.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),
})
tf.gfile.MakeDirs(model_dir)
tf.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 = tf.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:tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[0] = 0 is not in [0, 0)
tf.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))
tf.logging.info('Starting to evaluate.')
eval_results = fashionAI.evaluate(input_fn=lambda : input_pipeline(False, model_scope, 1))
tf.logging.info(eval_results)
tf.logging.info('Finished model {}.'.format(model_scope))
def main(_):
# Using the Winograd non-fused algorithms provides a small performance boost.
os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction)
sess_config = tf.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 = tf.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__':
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run()
# 0.04473711425469029
# blouse: 0.042138283111307795
# dress: 0.04147867224643174
# outwear: 0.04511445541161763
# skirt: 0.05388678376709799
# trousers: 0.04985801318493035
| [
"tensorflow.floordiv",
"tensorflow.control_dependencies",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.gfile.MakeDirs",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.GPUOptions",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.estimator.RunConfig",
"tensorflow.summary.scalar",
"tensorflow.nn.depthwise_conv2d",
"tensorflow.add_n",
"numpy.clip",
"tensorflow.get_collection",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.squeeze",
"tensorflow.train.get_or_create_global_step",
"tensorflow.ConfigProto",
"tensorflow.nn.top_k",
"tensorflow.train.MomentumOptimizer",
"tensorflow.logging.set_verbosity",
"tensorflow.name_scope",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.tile",
"tensorflow.app.run",
"tensorflow.floormod",
"tensorflow.gather_nd",
"tensorflow.shape",
"tensorflow.identity",
"tensorflow.exp",
"tensorflow.zeros_like",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.losses.add_loss",
"numpy.sum",
"tensorflow.reduce_max",
"scipy.misc.imresize",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.range",
"tensorflow.losses.mean_squared_error",
"tensorflow.reshape",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.squared_difference",
"tensorflow.logical_and"
] | train_senet_cpn_onebyone.py | [(34, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_readers"""', '(16)', '"""The number of parallel readers that read data from the dataset."""'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_preprocessing_threads"""', '(48)', '"""The number of threads used to create the batches."""'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_cpu_threads"""', '(0)', '"""The number of cpu cores used to train."""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""gpu_memory_fraction"""', '(1.0)', '"""GPU memory fraction to use."""'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""data_dir"""', '"""../Datasets/tfrecords"""', '"""The directory where the dataset input data is stored."""'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""dataset_name"""', '"""{}_????"""', '"""The pattern of the dataset name to load."""'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""model_dir"""', '"""./logs_sext_cpn/"""', '"""The parent directory where the model will be stored."""'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""log_every_n_steps"""', '(10)', '"""The frequency with which logs are print."""'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_summary_steps"""', '(100)', '"""The frequency with which summaries are saved, in seconds."""'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_checkpoints_secs"""', '(3600)', '"""The frequency with which the model is saved, in seconds."""'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""train_image_size"""', '(384)', '"""The size of the input image for the model to use."""'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""heatmap_size"""', '(96)', '"""The size of the output heatmap of the model."""'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""backbone"""', '"""seresnext50"""', '"""The backbone network to use for feature pyramid."""'], {}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""heatmap_sigma"""', '(1.0)', '"""The sigma of Gaussian which generate the target heatmap."""'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""bbox_border"""', '(25.0)', '"""The nearest distance of the crop border to al keypoints."""'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""train_epochs"""', '(50)', '"""The number of epochs to use for training."""'], {}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""epochs_per_eval"""', '(20)', '"""The number of training epochs to run between evaluations."""'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""batch_size"""', '(10)', '"""Batch size for training and evaluation."""'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""xt_batch_size"""', '(10)', '"""Batch size for training and evaluation."""'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""use_ohkm"""', '(True)', '"""Wether we will use the ohkm for hard keypoints."""'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""data_format"""', '"""channels_first"""', '"""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 TensorFlow was built for CPU or GPU."""'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""tf_random_seed"""', '(20180417)', '"""Random seed for TensorFlow initializers."""'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""weight_decay"""', '(1e-05)', '"""The weight decay on the model weights."""'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""mse_weight"""', '(1.0)', '"""The weight decay on the model weights."""'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""momentum"""', '(0.9)', '"""The momentum for the MomentumOptimizer and RMSPropOptimizer."""'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""learning_rate"""', '(0.0001)', '"""Initial learning rate."""'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""end_learning_rate"""', '(1e-06)', '"""The minimal end learning rate used by a polynomial decay learning rate."""'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""warmup_learning_rate"""', '(1e-05)', '"""The start warm-up learning rate to avoid NAN."""'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""warmup_steps"""', '(100)', '"""The total steps to warm-up."""'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""decay_boundaries"""', '"""2, 3"""', '"""Learning rate decay boundaries by global_step (comma-separated list)."""'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.app.flags.DEFINE_string', 'tf.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)."""'], {}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_path"""', '"""./model"""', '"""The path to a checkpoint from which to fine-tune."""'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_model_scope"""', '""""""', '"""Model scope in the checkpoint. None if the same as the trained model."""'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""model_scope"""', 'None', '"""Model scope name used to replace the name_scope in checkpoint."""'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_exclude_scopes"""', 'None', '"""Comma-separated list of scopes of variables to exclude when restoring from a checkpoint."""'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""ignore_missing_vars"""', '(True)', '"""When restoring a checkpoint would ignore missing variables."""'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""run_on_cloud"""', '(False)', '"""Wether we will train on cloud."""'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""seq_train"""', '(False)', '"""Wether we will train a sequence model."""'], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""model_to_train"""', '"""blouse, dress, outwear, skirt, trousers"""', '"""The sub-model to train (comma-separated list)."""'], {}), True, 'import tensorflow as tf\n'), (170, 'preprocessing.dataset.slim_get_split', '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'}), False, 'from preprocessing import dataset\n'), (213, 'tensorflow.reshape', 'tf.reshape', (['predictions', '[1, -1, heatmap_size * heatmap_size]'], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.reduce_max', 'tf.reduce_max', (['predictions'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.argmax', 'tf.argmax', (['predictions'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (310, 'utility.mertric.normalized_error', '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[\n 'model_scope'] else '*']", "params['heatmap_size']", "params['train_image_size']"], {}), False, 'from utility import mertric\n'), (332, 'tensorflow.identity', 'tf.identity', (['ne_mertric[1]'], {'name': '"""ne_mertric"""'}), True, 'import tensorflow as tf\n'), (372, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""mse"""', 'mse_loss'], {}), True, 'import tensorflow as tf\n'), (373, 'tensorflow.losses.add_loss', 'tf.losses.add_loss', (['mse_loss'], {}), True, 'import tensorflow as tf\n'), (386, 'tensorflow.identity', 'tf.identity', (['loss'], {'name': '"""total_loss"""'}), True, 'import tensorflow as tf\n'), (387, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'total_loss'], {}), True, 'import tensorflow as tf\n'), (451, 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['model_dir'], {}), True, 'import tensorflow as tf\n'), (476, 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'FLAGS.gpu_memory_fraction'}), True, 'import tensorflow as tf\n'), (477, 'tensorflow.ConfigProto', 'tf.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'}), True, 'import tensorflow as tf\n'), (633, 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), True, 'import tensorflow as tf\n'), (634, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (168, 'preprocessing.preprocessing.preprocess_image', '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'}), False, 'from preprocessing import preprocessing\n'), (190, 'scipy.misc.imresize', 'imresize', (['img_to_save', '(height, width)'], {'interp': '"""lanczos"""'}), False, 'from scipy.misc import imread, imsave, imshow, imresize\n'), (191, 'scipy.misc.imresize', 'imresize', (['heatmap0', '(height, width)'], {'interp': '"""lanczos"""'}), False, 'from scipy.misc import imread, imsave, imshow, imresize\n'), (192, 'scipy.misc.imresize', 'imresize', (['heatmap1', '(height, width)'], {'interp': '"""lanczos"""'}), False, 'from scipy.misc import imread, imsave, imshow, imresize\n'), (193, 'scipy.misc.imresize', 'imresize', (['heatmap2', '(height, width)'], {'interp': '"""lanczos"""'}), False, 'from scipy.misc import imread, imsave, imshow, imresize\n'), (196, 'numpy.clip', 'np.clip', (['(img_to_save[:, :, (0)] + heatmap0 + heatmap2)', '(0)', '(255)'], {}), True, 'import numpy as np\n'), (197, 'numpy.clip', 'np.clip', (['(img_to_save[:, :, (1)] + heatmap1 + heatmap2)', '(0)', '(255)'], {}), True, 'import numpy as np\n'), (219, 'tensorflow.cast', 'tf.cast', (['width', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.cast', 'tf.cast', (['height', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.squeeze', 'tf.squeeze', (['pred_indices'], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.one_hot', 'tf.one_hot', (['pred_indices_', '(heatmap_size * heatmap_size)'], {'on_value': '(1.0)', 'off_value': '(0.0)', 'axis': '(-1)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.reshape', 'tf.reshape', (['pred_heatmap', '[-1, heatmap_size, heatmap_size]'], {}), True, 'import tensorflow as tf\n'), (249, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""gaussian_blur"""', '[inputs]'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.transpose', 'tf.transpose', (['x', '[1, 0]'], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.exp', 'tf.exp', (['(-((x - ksize / 2.0) ** 2 + (y - ksize / 2.0) ** 2) / (2 * sigma ** 2))'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.reshape', 'tf.reshape', (['kernel_matrix', '[ksize, ksize, 1, 1]'], {}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.tile', 'tf.tile', (['kernel_filter', '[1, 1, inputs_filters, 1]'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.nn.depthwise_conv2d', 'tf.nn.depthwise_conv2d', (['inputs', 'kernel_filter'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""', 'data_format': 'data_format_', 'name': '"""blur"""'}), True, 'import tensorflow as tf\n'), (278, 'tensorflow.shape', 'tf.shape', (['features'], {}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.variable_scope', 'tf.variable_scope', (["params['model_scope']"], {'default_name': 'None', 'values': '[features]', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (327, 'tensorflow.squared_difference', 'tf.squared_difference', (['targets', 'pred_outputs[-1]'], {}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.zeros_like', 'tf.zeros_like', (['sq_diff'], {}), True, 'import tensorflow as tf\n'), (353, 'tensorflow.gather_nd', 'tf.gather_nd', (['targets_list[-1]', 'gather_indcies'], {}), True, 'import tensorflow as tf\n'), (354, 'tensorflow.gather_nd', 'tf.gather_nd', (['pred_outputs[-1]', 'gather_indcies'], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.add_n', 'tf.add_n', (['mse_loss_list'], {}), True, 'import tensorflow as tf\n'), (390, 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'predictions': 'predictions', 'eval_metric_ops': 'metrics'}), True, 'import tensorflow as tf\n'), (393, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (400, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""lr"""', 'truncated_learning_rate'], {}), True, 'import tensorflow as tf\n'), (402, 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', ([], {'learning_rate': 'truncated_learning_rate', 'momentum': "params['momentum']"}), True, 'import tensorflow as tf\n'), (406, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), True, 'import tensorflow as tf\n'), (464, 'tensorflow.logging.info', 'tf.logging.info', (['"""Starting a training cycle."""'], {}), True, 'import tensorflow as tf\n'), (467, 'tensorflow.logging.info', 'tf.logging.info', (['"""Starting to evaluate."""'], {}), True, 'import tensorflow as tf\n'), (469, 'tensorflow.logging.info', 'tf.logging.info', (['eval_results'], {}), True, 'import tensorflow as tf\n'), (188, 'numpy.zeros', 'np.zeros', (['(heatmap_size, heatmap_size)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (200, 'os.path.join', 'os.path.join', (['config.DEBUG_DIR', 'file_name'], {}), False, 'import os\n'), (217, 'tensorflow.floormod', 'tf.floormod', (['pred_indices', 'heatmap_size'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.floordiv', 'tf.floordiv', (['pred_indices', 'heatmap_size'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.cast', 'tf.cast', (['heatmap_size', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.cast', 'tf.cast', (['heatmap_size', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.squeeze', 'tf.squeeze', (['image'], {}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.transpose', 'tf.transpose', (['image_'], {'perm': '(1, 2, 0)'}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[save_image_op]'], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.transpose', 'tf.transpose', (['inputs', '[0, 2, 3, 1]'], {}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.range', 'tf.range', (['ksize'], {'delta': '(1)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.transpose', 'tf.transpose', (['outputs', '[0, 3, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.nn.top_k', 'tf.nn.top_k', (['temp_loss'], {'k': 'num_topk', 'sorted': '(True)'}), True, 'import tensorflow as tf\n'), (396, 'tensorflow.cast', 'tf.cast', (['global_step', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (399, 'tensorflow.constant', 'tf.constant', (["params['end_learning_rate']"], {'dtype': 'learning_rate.dtype'}), True, 'import tensorflow as tf\n'), (407, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['update_ops'], {}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.constant', 'tf.constant', (['config.global_norm_key'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.constant', 'tf.constant', (['config.global_norm_lvalues'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.constant', 'tf.constant', (['config.global_norm_key'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.constant', 'tf.constant', (['config.global_norm_rvalues'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.constant', 'tf.constant', (['config.local_norm_key'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.constant', 'tf.constant', (['config.local_norm_lvalues'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.constant', 'tf.constant', (['config.local_norm_key'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.constant', 'tf.constant', (['config.local_norm_rvalues'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (186, 'numpy.sum', 'np.sum', (['targets[indR, ...]'], {'axis': '(0)'}), True, 'import numpy as np\n'), (187, 'numpy.sum', 'np.sum', (['targets[indG, ...]'], {'axis': '(0)'}), True, 'import numpy as np\n'), (209, 'os.path.join', 'os.path.join', (['config.DEBUG_DIR', 'file_name'], {}), False, 'import os\n'), (223, 'tensorflow.cast', 'tf.cast', (['(pred_max > 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.cast', 'tf.cast', (['(pred_max > 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.cast', 'tf.cast', (['(pred_max > 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.cast', 'tf.cast', (['(pred_max <= 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.cast', 'tf.cast', (['(pred_max > 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.cast', 'tf.cast', (['(pred_max <= 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.reshape', 'tf.reshape', (['(pred_heatmap * 255.0)', '[-1, heatmap_size, heatmap_size]'], {}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.reshape', 'tf.reshape', (['predictions', '[-1, heatmap_size, heatmap_size]'], {}), True, 'import tensorflow as tf\n'), (323, 'tensorflow.logical_and', 'tf.logical_and', (['(key_v > 0)', '(isvalid > 0)'], {}), True, 'import tensorflow as tf\n'), (346, 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['targets_list[-1]', 'pred_outputs[-1]'], {'weights': '(1.0)', 'loss_collection': 'None', 'reduction': 'tf.losses.Reduction.NONE'}), True, 'import tensorflow as tf\n'), (492, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (504, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""blouse"""'], {}), False, 'import os\n'), (510, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (516, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""dress"""'], {}), False, 'import os\n'), (522, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (528, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""outwear"""'], {}), False, 'import os\n'), (534, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (540, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""skirt"""'], {}), False, 'import os\n'), (546, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (552, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""trousers"""'], {}), False, 'import os\n'), (558, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""all"""'], {}), False, 'import os\n'), (567, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""blouse"""'], {}), False, 'import os\n'), (579, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""dress"""'], {}), False, 'import os\n'), (591, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""outwear"""'], {}), False, 'import os\n'), (603, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""skirt"""'], {}), False, 'import os\n'), (615, 'os.path.join', 'os.path.join', (['FLAGS.model_dir', '"""trousers"""'], {}), False, 'import os\n'), (188, 'numpy.sum', 'np.sum', (['targets[indB, ...]'], {'axis': '(0)'}), True, 'import numpy as np\n'), (350, 'tensorflow.range', 'tf.range', (['cur_batch_size'], {}), True, 'import tensorflow as tf\n'), (351, 'tensorflow.reshape', 'tf.reshape', (['gather_col', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (385, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['v'], {}), True, 'import tensorflow as tf\n'), (418, 'utility.train_helper.get_init_fn_for_scaffold_', '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']"], {}), False, 'from utility import train_helper\n'), (573, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'FLAGS.backbone'], {}), False, 'import os\n'), (573, 'os.path.join', 'os.path.join', (['FLAGS.checkpoint_path', 'FLAGS.backbone'], {}), False, 'import os\n'), (585, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'FLAGS.backbone'], {}), False, 'import os\n'), (585, 'os.path.join', 'os.path.join', (['FLAGS.checkpoint_path', 'FLAGS.backbone'], {}), False, 'import os\n'), (597, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'FLAGS.backbone'], {}), False, 'import os\n'), (597, 'os.path.join', 'os.path.join', (['FLAGS.checkpoint_path', 'FLAGS.backbone'], {}), False, 'import os\n'), (609, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'FLAGS.backbone'], {}), False, 'import os\n'), (609, 'os.path.join', 'os.path.join', (['FLAGS.checkpoint_path', 'FLAGS.backbone'], {}), False, 'import os\n'), (621, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'FLAGS.backbone'], {}), False, 'import os\n'), (621, 'os.path.join', 'os.path.join', (['FLAGS.checkpoint_path', 'FLAGS.backbone'], {}), False, 'import os\n'), (357, 'tensorflow.cast', 'tf.cast', (['cur_batch_size', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (385, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (365, 'tensorflow.cast', 'tf.cast', (['cur_batch_size', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.cast', 'tf.cast', (['cur_batch_size', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (480, 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', ([], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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)
tf.set_random_seed(1234)
sess = tf.Session(graph=tf.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)
| [
"numpy.random.seed",
"numpy.arange",
"tensorflow.set_random_seed",
"tensorflow.get_default_graph",
"numpy.array"
] | task4_crnn.py | [(23, 'dcase_util.utils.setup_logging', 'dcase_util.utils.setup_logging', ([], {'logging_file': '"""task4.log"""'}), False, 'import dcase_util\n'), (26, 'random.seed', 'random.seed', (['(10)'], {}), False, 'import random\n'), (27, 'numpy.random.seed', 'numpy.random.seed', (['(42)'], {}), False, 'import numpy\n'), (29, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), True, 'import tensorflow as tf\n'), (31, 'keras.backend.set_session', 'K.set_session', (['sess'], {}), True, 'from keras import backend as K\n'), (35, 'dcase_util.ui.ui.FancyLogger', 'dcase_util.ui.ui.FancyLogger', ([], {}), False, 'import dcase_util\n'), (199, 'dcase_util.processors.ProcessingChain', 'dcase_util.processors.ProcessingChain', ([], {}), False, 'import dcase_util\n'), (30, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (46, 'dcase_util.containers.DCASEAppParameterContainer', 'dcase_util.containers.DCASEAppParameterContainer', (['parameters'], {'path_structure': "{'FEATURE_EXTRACTOR': ['DATASET', 'FEATURE_EXTRACTOR'],\n 'FEATURE_NORMALIZER': ['DATASET', 'FEATURE_EXTRACTOR'], 'LEARNER': [\n 'DATASET', 'FEATURE_EXTRACTOR', 'FEATURE_NORMALIZER',\n 'FEATURE_SEQUENCER', 'LEARNER'], 'RECOGNIZER': ['DATASET',\n 'FEATURE_EXTRACTOR', 'FEATURE_NORMALIZER', 'FEATURE_SEQUENCER',\n 'LEARNER', 'RECOGNIZER']}"}), False, 'import dcase_util\n'), (76, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {}), False, 'import dcase_util\n'), (168, 'dcase_util.data.Normalizer', 'dcase_util.data.Normalizer', ([], {'filename': 'features_norm_filename'}), False, 'import dcase_util\n'), (434, 'numpy.arange', 'numpy.arange', (['(0.0)', '(1 + 1e-06)', '(0.1)'], {}), False, 'import numpy\n'), (476, 'dcase_util.containers.MetaDataContainer', 'dcase_util.containers.MetaDataContainer', ([], {'filename': 'fold_results_filename'}), False, 'import dcase_util\n'), (746, 'dcase_util.containers.MetaDataContainer', 'dcase_util.containers.MetaDataContainer', ([], {'filename': 'fold_results_filename'}), False, 'import dcase_util\n'), (848, 'evaluation_measures.event_based_evaluation', 'event_based_evaluation', (['reference_event_list', 'estimated_event_list'], {}), False, 'from evaluation_measures import get_f_measure_by_class, event_based_evaluation\n'), (888, 'random.shuffle', 'random.shuffle', (['items'], {}), False, 'import random\n'), (925, 'dcase_util.containers.DictContainer', 'dcase_util.containers.DictContainer', ([], {}), False, 'import dcase_util\n'), (932, 'sys.exit', 'sys.exit', (['e'], {}), False, 'import sys\n'), (167, 'os.path.isfile', 'os.path.isfile', (['features_norm_filename'], {}), False, 'import os\n'), (246, 'os.path.isfile', 'os.path.isfile', (['fold1_model_filename'], {}), False, 'import os\n'), (415, 'os.path.isfile', 'os.path.isfile', (['thresholds_filename'], {}), False, 'import os\n'), (430, 'keras.models.load_model', 'keras.models.load_model', (['fold1_model_filename'], {}), False, 'import keras\n'), (474, 'os.path.isfile', 'os.path.isfile', (['fold_results_filename'], {}), False, 'import os\n'), (482, 'keras.models.load_model', 'keras.models.load_model', (['fold1_model_filename'], {}), False, 'import keras\n'), (546, 'os.path.isfile', 'os.path.isfile', (['fold2_model_filename'], {}), False, 'import os\n'), (740, 'os.path.isfile', 'os.path.isfile', (['fold_results_filename'], {}), False, 'import os\n'), (743, 'keras.models.load_model', 'keras.models.load_model', (['fold2_model_filename'], {}), False, 'import keras\n'), (833, 'os.path.isfile', 'os.path.isfile', (['stats_filename'], {}), False, 'import os\n'), (124, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {'path': 'audio_filename'}), False, 'import dcase_util\n'), (131, 'os.path.isfile', 'os.path.isfile', (['feature_filename'], {}), False, 'import os\n'), (581, 'dcase_util.containers.MetaDataContainer', 'dcase_util.containers.MetaDataContainer', ([], {'filename': 'fold1_results_filename'}), False, 'import dcase_util\n'), (843, 'dcase_util.containers.MetaDataContainer', 'dcase_util.containers.MetaDataContainer', ([], {}), False, 'import dcase_util\n'), (891, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {'path': 'item.filename'}), False, 'import dcase_util\n'), (93, 'os.path.join', 'os.path.join', (['"""dataset"""', '"""audio"""', '"""train"""', '"""weak"""'], {}), False, 'import os\n'), (94, 'os.path.join', 'os.path.join', (['"""dataset"""', '"""audio"""', '"""train"""', '"""unlabel_in_domain"""'], {}), False, 'import os\n'), (95, 'os.path.join', 'os.path.join', (['"""dataset"""', '"""audio"""', '"""train"""', '"""unlabel_out_of_domain"""'], {}), False, 'import os\n'), (96, 'os.path.join', 'os.path.join', (['"""dataset"""', '"""audio"""', '"""test"""'], {}), False, 'import os\n'), (138, 'dcase_util.containers.AudioContainer', 'dcase_util.containers.AudioContainer', ([], {}), False, 'import dcase_util\n'), (487, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {'path': 'item.filename'}), False, 'import dcase_util\n'), (505, 'dcase_util.data.ProbabilityEncoder', 'dcase_util.data.ProbabilityEncoder', ([], {}), False, 'import dcase_util\n'), (753, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {'path': 'item.filename'}), False, 'import dcase_util\n'), (133, 'os.path.split', 'os.path.split', (['audio_filename'], {}), False, 'import os\n'), (176, 'dcase_util.utils.Path', 'dcase_util.utils.Path', ([], {'path': 'filename'}), False, 'import dcase_util\n'), (184, 'dcase_util.containers.FeatureContainer', 'dcase_util.containers.FeatureContainer', ([], {}), False, 'import dcase_util\n'), (777, 'dcase_util.data.ProbabilityEncoder', 'dcase_util.data.ProbabilityEncoder', ([], {}), False, 'import dcase_util\n'), (784, 'dcase_util.data.ProbabilityEncoder', 'dcase_util.data.ProbabilityEncoder', ([], {}), False, 'import dcase_util\n'), (916, 'numpy.array', 'numpy.array', (['batch_X'], {}), False, 'import numpy\n'), (916, 'numpy.array', 'numpy.array', (['batch_y'], {}), False, 'import numpy\n')] |
jdavidagudelo/tensorflow-models | 6f019beec73b01861363bf717706e27f4210b979 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
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 tf.name_scope(self.name_scope()):
anchors_list = self._generate(feature_map_shape_list, **params)
if self.check_num_anchors:
with tf.control_dependencies([
self._assert_correct_number_of_anchors(
anchors_list, feature_map_shape_list)]):
for item in anchors_list:
item.set(tf.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 tf.assert_equal(expected_num_anchors, actual_num_anchors)
| [
"tensorflow.assert_equal"
] | research/object_detection/core/anchor_generator.py | [(149, 'tensorflow.assert_equal', 'tf.assert_equal', (['expected_num_anchors', 'actual_num_anchors'], {}), True, 'import tensorflow as tf\n')] |
jdavidagudelo/tensorflow-models | 6f019beec73b01861363bf717706e27f4210b979 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
from research.slim.nets import mobilenet_v1
slim = tf.contrib.slim
class MobilenetV1Test(tf.test.TestCase):
def testBuildClassificationNetwork(self):
batch_size = 5
height, width = 224, 224
num_classes = 1000
inputs = tf.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 = tf.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 = tf.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 tf.Graph().as_default():
inputs = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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 = tf.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):
tf.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 = tf.placeholder(tf.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}
tf.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):
tf.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 = tf.placeholder(tf.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}
tf.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 = tf.placeholder(tf.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 = tf.random_uniform((batch_size, height, width, 3))
with self.test_session() as sess:
sess.run(tf.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 = tf.random_uniform((batch_size, height, width, 3))
logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes,
is_training=False)
predictions = tf.argmax(logits, 1)
with self.test_session() as sess:
sess.run(tf.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 = tf.random_uniform((train_batch_size, height, width, 3))
mobilenet_v1.mobilenet_v1(train_inputs, num_classes)
eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3))
logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes,
reuse=True)
predictions = tf.argmax(logits, 1)
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
output = sess.run(predictions)
self.assertEqual(output.shape, (eval_batch_size,))
def testLogitsNotSqueezed(self):
num_classes = 25
images = tf.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:
tf.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__':
tf.test.main()
| [
"tensorflow.Graph",
"tensorflow.test.main",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"numpy.random.uniform",
"tensorflow.argmax",
"tensorflow.random_uniform"
] | research/slim/nets/mobilenet_v1_test.py | [(535, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (37, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (51, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (52, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (62, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (63, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (119, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (120, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': '"""Conv2d_3_pointwise"""', 'conv_defs': 'conv_defs'}), False, 'from research.slim.nets import mobilenet_v1\n'), (135, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (360, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (361, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (365, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {'scope': '"""depth_multiplied_net"""', 'depth_multiplier': '(0.5)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (379, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (380, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (385, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {'scope': '"""depth_multiplied_net"""', 'depth_multiplier': '(2.0)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (399, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (412, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (413, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (422, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (426, 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(batch_size, height, width, 3)'], {}), True, 'import numpy as np\n'), (440, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (444, 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(batch_size, height, width, 3)'], {}), True, 'import numpy as np\n'), (463, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (464, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (468, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (480, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (481, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['eval_inputs', 'num_classes'], {'is_training': '(False)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (483, 'tensorflow.argmax', 'tf.argmax', (['logits', '(1)'], {}), True, 'import tensorflow as tf\n'), (496, 'tensorflow.random_uniform', 'tf.random_uniform', (['(train_batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (497, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['train_inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (498, 'tensorflow.random_uniform', 'tf.random_uniform', (['(eval_batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (499, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['eval_inputs', 'num_classes'], {'reuse': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (501, 'tensorflow.argmax', 'tf.argmax', (['logits', '(1)'], {}), True, 'import tensorflow as tf\n'), (510, 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, 224, 224, 3]'], {}), True, 'import tensorflow as tf\n'), (511, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['images'], {'num_classes': 'num_classes', 'spatial_squeeze': '(False)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (521, 'research.slim.nets.mobilenet_v1.mobilenet_v1_arg_scope', 'mobilenet_v1.mobilenet_v1_arg_scope', ([], {'is_training': 'None'}), False, 'from research.slim.nets import mobilenet_v1\n'), (526, 'research.slim.nets.mobilenet_v1.mobilenet_v1_arg_scope', 'mobilenet_v1.mobilenet_v1_arg_scope', ([], {'is_training': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (528, 'research.slim.nets.mobilenet_v1.mobilenet_v1_arg_scope', 'mobilenet_v1.mobilenet_v1_arg_scope', ([], {'is_training': '(False)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (530, 'research.slim.nets.mobilenet_v1.mobilenet_v1_arg_scope', 'mobilenet_v1.mobilenet_v1_arg_scope', ([], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (113, 'research.slim.nets.mobilenet_v1.Conv', 'mobilenet_v1.Conv', ([], {'kernel': '[3, 3]', 'stride': '(2)', 'depth': '(32)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (114, 'research.slim.nets.mobilenet_v1.DepthSepConv', 'mobilenet_v1.DepthSepConv', ([], {'kernel': '[3, 3]', 'stride': '(1)', 'depth': '(64)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (115, 'research.slim.nets.mobilenet_v1.DepthSepConv', 'mobilenet_v1.DepthSepConv', ([], {'kernel': '[3, 3]', 'stride': '(2)', 'depth': '(128)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (116, 'research.slim.nets.mobilenet_v1.DepthSepConv', 'mobilenet_v1.DepthSepConv', ([], {'kernel': '[3, 3]', 'stride': '(1)', 'depth': '(512)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (138, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': '"""Conv2d_13_pointwise"""'}), False, 'from research.slim.nets import mobilenet_v1\n'), (140, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': '"""Conv2d_13_pointwise"""', 'use_explicit_padding': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (191, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'output_stride': 'output_stride', 'final_endpoint': '"""Conv2d_13_pointwise"""'}), False, 'from research.slim.nets import mobilenet_v1\n'), (194, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'output_stride': 'output_stride', 'final_endpoint': '"""Conv2d_13_pointwise"""', 'use_explicit_padding': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (245, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'output_stride': 'output_stride', 'final_endpoint': '"""Conv2d_13_pointwise"""'}), False, 'from research.slim.nets import mobilenet_v1\n'), (248, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'output_stride': 'output_stride', 'final_endpoint': '"""Conv2d_13_pointwise"""', 'use_explicit_padding': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (298, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': '"""Conv2d_13_pointwise"""', 'depth_multiplier': '(0.75)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (300, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': '"""Conv2d_13_pointwise"""', 'depth_multiplier': '(0.75)', 'use_explicit_padding': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (350, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (401, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {'depth_multiplier': '(-0.1)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (404, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {'depth_multiplier': '(0.0)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (428, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(batch_size, None, None, 3)'}), True, 'import tensorflow as tf\n'), (429, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {}), False, 'from research.slim.nets import mobilenet_v1\n'), (446, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(batch_size, None, None, 3)'}), True, 'import tensorflow as tf\n'), (447, 'research.slim.nets.mobilenet_v1.mobilenet_v1', 'mobilenet_v1.mobilenet_v1', (['inputs', 'num_classes'], {'global_pool': '(True)'}), False, 'from research.slim.nets import mobilenet_v1\n'), (102, 'tensorflow.random_uniform', 'tf.random_uniform', (['(batch_size, height, width, 3)'], {}), True, 'import tensorflow as tf\n'), (103, 'research.slim.nets.mobilenet_v1.mobilenet_v1_base', 'mobilenet_v1.mobilenet_v1_base', (['inputs'], {'final_endpoint': 'endpoint'}), False, 'from research.slim.nets import mobilenet_v1\n'), (471, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (486, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (504, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (435, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (454, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (516, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n')] |
MohamedAli1995/Cifar-100-Classifier | 924704a81ce13062825a88b90b80e8ac2ba45d63 | import tensorflow as tf
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: Tensorflow 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 = tf.group(tf.global_variables_initializer(), tf.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 tensorflow 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 tensorflow session
-Returns:
Any of the metrics needs to be summarized.
"""
raise NotImplemented
| [
"tensorflow.global_variables_initializer",
"tensorflow.local_variables_initializer"
] | src/base/base_train.py | [(23, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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 = tf.reshape(input_, [-1, np.prod(self.inp_modes)])
self.image_max_size = max(self.image_max_size, np.prod(self.inp_modes))
out = tf.transpose(out, [1, 0])
for i in range(dim):
out = tf.reshape(out, [self.mat_ranks[i] * self.inp_modes[i], -1])
out = tf.matmul(self.mat_cores[i], out)
out = tf.reshape(out, [self.out_modes[i], -1])
out = tf.transpose(out, [1, 0])
out = tf.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 = tf.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
| [
"tensorflow.matmul",
"tensorflow.transpose",
"tensorflow.reshape",
"tensorflow.add",
"numpy.prod",
"numpy.array"
] | code/palmnet/layers/tt_layer_dense.py | [(24, 'keras.activations.get', 'activations.get', (['activation'], {}), False, 'from keras import backend as K, activations, initializers\n'), (26, 'keras.initializers.get', 'initializers.get', (['kernel_initializer'], {}), False, 'from keras import backend as K, activations, initializers\n'), (27, 'keras.initializers.get', 'initializers.get', (['bias_initializer'], {}), False, 'from keras import backend as K, activations, initializers\n'), (86, 'tensorflow.transpose', 'tf.transpose', (['out', '[1, 0]'], {}), True, 'import tensorflow as tf\n'), (67, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\n'), (68, 'numpy.prod', 'np.prod', (['self.inp_modes'], {}), True, 'import numpy as np\n'), (85, 'numpy.prod', 'np.prod', (['self.inp_modes'], {}), True, 'import numpy as np\n'), (88, 'tensorflow.reshape', 'tf.reshape', (['out', '[self.mat_ranks[i] * self.inp_modes[i], -1]'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.matmul', 'tf.matmul', (['self.mat_cores[i]', 'out'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.reshape', 'tf.reshape', (['out', '[self.out_modes[i], -1]'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.transpose', 'tf.transpose', (['out', '[1, 0]'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.add', 'tf.add', (['out', 'self.bias'], {'name': '"""out"""'}), True, 'import tensorflow as tf\n'), (103, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\n'), (31, 'numpy.array', 'np.array', (['mat_ranks'], {}), True, 'import numpy as np\n'), (64, 'palmnet.utils.get_facto_for_channel_and_order', 'get_facto_for_channel_and_order', (['inp_ch', 'self.order'], {'dct_predefined_facto': 'DCT_CHANNEL_PREDEFINED_FACTORIZATIONS'}), False, 'from palmnet.utils import get_facto_for_channel_and_order, DCT_CHANNEL_PREDEFINED_FACTORIZATIONS\n'), (65, 'palmnet.utils.get_facto_for_channel_and_order', 'get_facto_for_channel_and_order', (['self.nb_units', 'self.order'], {'dct_predefined_facto': 'DCT_CHANNEL_PREDEFINED_FACTORIZATIONS'}), False, 'from palmnet.utils import get_facto_for_channel_and_order, DCT_CHANNEL_PREDEFINED_FACTORIZATIONS\n'), (84, 'numpy.prod', 'np.prod', (['self.inp_modes'], {}), True, 'import numpy as np\n'), (93, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\n'), (113, 'keras.initializers.serialize', 'initializers.serialize', (['self.bias_initializer'], {}), False, 'from keras import backend as K, activations, initializers\n'), (114, 'keras.initializers.serialize', 'initializers.serialize', (['self.kernel_initializer'], {}), False, 'from keras import backend as K, activations, initializers\n'), (116, 'keras.activations.serialize', 'activations.serialize', (['self.activation'], {}), False, 'from keras import backend as K, activations, initializers\n'), (45, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\n'), (41, 'numpy.array', 'np.array', (['inp_modes'], {}), True, 'import numpy as np\n'), (42, 'numpy.array', 'np.array', (['out_modes'], {}), True, 'import numpy as np\n'), (77, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\n'), (46, 'numpy.prod', 'np.prod', (['self.out_modes'], {}), True, 'import numpy as np\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 tensorflow 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_tf.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 = tf.placeholder(tf.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 tf.Session() as sess:
sess.run(tf.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 = tf.image.non_max_suppression(tf.convert_to_tensor(bboxes[:, :4], dtype=tf.float32),
tf.convert_to_tensor(bboxes[:, 4], dtype=tf.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 tf.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
| [
"tensorflow.convert_to_tensor",
"numpy.hstack",
"matplotlib.pyplot.imshow",
"tensorflow.Graph",
"scipy.special.expit",
"numpy.power",
"numpy.vstack",
"tensorflow.placeholder",
"numpy.ceil",
"tensorflow.global_variables_initializer",
"numpy.max",
"tensorflow.Session",
"numpy.exp",
"matplotlib.pyplot.show",
"numpy.where",
"numpy.empty"
] | eval_tiny_one_image.py | [(78, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[1, None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (81, 'tiny_face_model.Model', 'tiny_face_model.Model', (['weight_file_path'], {}), False, 'import tiny_face_model\n'), (92, 'numpy.where', 'np.where', (['(clusters[:, (4)] == 1)'], {}), True, 'import numpy as np\n'), (41, 'scipy.special.expit', 'expit', (['r[4]'], {}), False, 'from scipy.special import expit\n'), (51, 'cv2.rectangle', 'cv2.rectangle', (['raw_img', '(_r[0], _r[1])', '(_r[2], _r[3])', 'rect_color', '_lw'], {}), False, 'import cv2\n'), (86, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (95, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (97, 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), False, 'import cv2\n'), (114, 'numpy.empty', 'np.empty', ([], {'shape': '(0, 5)'}), True, 'import numpy as np\n'), (42, 'numpy.ceil', 'np.ceil', (['(_score * 255)'], {}), True, 'import numpy as np\n'), (96, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (105, 'pylab.frange', 'pl.frange', (['min_scale', '(0)', '(1.0)'], {}), True, 'import pylab as pl\n'), (106, 'pylab.frange', 'pl.frange', (['(0.5)', 'max_scale', '(0.5)'], {}), True, 'import pylab as pl\n'), (107, 'numpy.hstack', 'np.hstack', (['(scales_down, scales_up)'], {}), True, 'import numpy as np\n'), (108, 'numpy.power', 'np.power', (['(2.0)', 'scales_pow'], {}), True, 'import numpy as np\n'), (118, 'cv2.resize', 'cv2.resize', (['raw_img_f', '(0, 0)'], {'fx': 's', 'fy': 's', 'interpolation': 'cv2.INTER_LINEAR'}), False, 'import cv2\n'), (131, 'scipy.special.expit', 'expit', (['score_cls_tf'], {}), False, 'from scipy.special import expit\n'), (166, 'numpy.vstack', 'np.vstack', (['(bboxes, tmp_bboxes)'], {}), True, 'import numpy as np\n'), (170, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['bboxes[:, :4]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['bboxes[:, (4)]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (178, 'matplotlib.pyplot.imshow', 'plt.imshow', (['raw_img'], {}), True, 'import matplotlib.pyplot as plt\n'), (179, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (43, 'numpy.ceil', 'np.ceil', (['(x * 255)'], {}), True, 'import numpy as np\n'), (48, 'numpy.ceil', 'np.ceil', (['(_lw * _score)'], {}), True, 'import numpy as np\n'), (136, 'numpy.where', 'np.where', (['(prob_cls_tf > prob_thresh)'], {}), True, 'import numpy as np\n'), (160, 'numpy.vstack', 'np.vstack', (['(rcx - rcw / 2, rcy - rch / 2, rcx + rcw / 2, rcy + rch / 2)'], {}), True, 'import numpy as np\n'), (161, 'numpy.vstack', 'np.vstack', (['(tmp_bboxes / s, scores)'], {}), True, 'import numpy as np\n'), (185, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (156, 'numpy.exp', 'np.exp', (['tw[fy, fx, fc]'], {}), True, 'import numpy as np\n'), (157, 'numpy.exp', 'np.exp', (['th[fy, fx, fc]'], {}), True, 'import numpy as np\n'), (102, 'numpy.max', 'np.max', (['(clusters_w[normal_idx] / raw_w)'], {}), True, 'import numpy as np\n'), (103, 'numpy.max', 'np.max', (['(clusters_h[normal_idx] / raw_h)'], {}), True, 'import numpy as np\n')] |
bestetc/batchflow | d2a843640383fbe860654236881483f755227e06 | """ Helpers for training """
from math import pi
import tensorflow as tf
def piecewise_constant(global_step, *args, **kwargs):
""" Constant learning rate decay (uses global_step param instead of x) """
return tf.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 tf.Tensor
The minimum learning rate boundary.
global_step : int or tf.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 tf.Tensor
The maximum learning rate boundary.
step_size : int or tf.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
-------
tf.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 tf.name_scope(name):
learning_rate = tf.cast(learning_rate, dtype=tf.float32)
global_step = tf.cast(global_step, dtype=tf.float32)
step_size = tf.cast(step_size, dtype=tf.float32)
max_lr = tf.cast(max_lr, dtype=tf.float32)
if mode == 'tri':
periodic_comp = tf.mod((global_step + step_size / 4) / step_size, 1)
first_factor = tf.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 = tf.sin((pi * global_step) / step_size)
second_comp = (learning_rate + max_lr) / 2.
elif mode == 'saw':
first_factor = max_lr - learning_rate
second_factor = tf.mod(global_step / step_size, 1)
second_comp = learning_rate
return first_factor * second_factor + second_comp
| [
"tensorflow.sin",
"tensorflow.cast",
"tensorflow.mod",
"tensorflow.train.piecewise_constant",
"tensorflow.name_scope",
"tensorflow.abs"
] | batchflow/models/tf/nn/train.py | [(8, 'tensorflow.train.piecewise_constant', 'tf.train.piecewise_constant', (['global_step', '*args'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.cast', 'tf.cast', (['learning_rate'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.cast', 'tf.cast', (['global_step'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.cast', 'tf.cast', (['step_size'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.cast', 'tf.cast', (['max_lr'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.mod', 'tf.mod', (['((global_step + step_size / 4) / step_size)', '(1)'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.abs', 'tf.abs', (['(periodic_comp - 0.5)'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.sin', 'tf.sin', (['(pi * global_step / step_size)'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.mod', 'tf.mod', (['(global_step / step_size)', '(1)'], {}), True, 'import tensorflow as tf\n')] |
ishine/malaya-speech | fd34afc7107af1656dff4b3201fa51dda54fde18 | import tensorflow as tf
from .layer import *
class Discriminator:
def __init__(self, inputs, targets, ndf=64):
n_layers = 3
layers = []
input = tf.concat([inputs, targets], axis=3)
with tf.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 tf.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 tf.variable_scope('layer_%d' % (len(layers) + 1)):
convolved = discrim_conv(rectified, out_channels=1, stride=1)
output = tf.sigmoid(convolved)
layers.append(output)
self.logits = layers[-1]
| [
"tensorflow.variable_scope",
"tensorflow.sigmoid",
"tensorflow.concat"
] | malaya_speech/train/model/pix2pix/discriminator.py | [(9, 'tensorflow.concat', 'tf.concat', (['[inputs, targets]'], {'axis': '(3)'}), True, 'import tensorflow as tf\n'), (10, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer_1"""'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.sigmoid', 'tf.sigmoid', (['convolved'], {}), True, 'import tensorflow as tf\n')] |
Ascend/modelzoo | f018cfed33dbb1cc2110b9ea2e233333f71cc509 | # Copyright 2017 The TensorFlow 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 tensorflow as tf
import random
from tensorflow.contrib import slim
from npu_bridge.estimator import npu_ops
from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig
tf.app.flags.DEFINE_integer('input_size', 512, '')
tf.app.flags.DEFINE_integer('batch_size_per_gpu', 14, '')
tf.app.flags.DEFINE_integer('num_readers', 16, '')
tf.app.flags.DEFINE_float('learning_rate', 0.0001, '')
tf.app.flags.DEFINE_integer('max_steps', 100000, '')
tf.app.flags.DEFINE_integer('loss_scale', 1024, '')
tf.app.flags.DEFINE_float('moving_average_decay', 0.997, '')
tf.app.flags.DEFINE_string('gpu_list', '1', '')
tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '')
tf.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint')
tf.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '')
tf.app.flags.DEFINE_integer('save_summary_steps', 100, '')
tf.app.flags.DEFINE_string('pretrained_model_path', None, '')
tf.app.flags.DEFINE_boolean('allow_mix_precision', False, 'whether to allow mix precision')
tf.app.flags.DEFINE_boolean('auto_tune', False, 'whether to autotune')
tf.app.flags.DEFINE_boolean('use_processed_data', False, 'whether to use processed data')
tf.app.flags.DEFINE_string('processed_data', './processed_dataset/', 'where to save preprocessed datasets')
import model
import icdar
FLAGS = tf.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 tf.variable_scope(tf.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 = tf.add_n([model_loss] + tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
# add summary
if reuse_variables is None:
tf.summary.image('input', images)
tf.summary.image('score_map', score_maps)
tf.summary.image('score_map_pred', f_score * 255)
tf.summary.image('geo_map_0', geo_maps[:, :, :, 0:1])
tf.summary.image('geo_map_0_pred', f_geometry[:, :, :, 0:1])
tf.summary.image('training_masks', training_masks)
tf.summary.scalar('model_loss', model_loss)
tf.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 = tf.expand_dims(g, 0)
grads.append(expanded_g)
grad = tf.concat(grads, 0)
grad = tf.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(tf.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 = (
tf.trainable_variables() +
tf.get_collection(tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))
replaced_list = var_list
if self._scale != 1.0:
loss = tf.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 = tf.cast(grad, orig_var.dtype)
if self._scale != 1.0:
grad = tf.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 tf.gfile.Exists(FLAGS.checkpoint_path):
tf.gfile.MkDir(FLAGS.checkpoint_path)
else:
if not FLAGS.restore:
tf.gfile.DeleteRecursively(FLAGS.checkpoint_path)
tf.gfile.MkDir(FLAGS.checkpoint_path)
input_images = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_images')
input_score_maps = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_score_maps')
if FLAGS.geometry == 'RBOX':
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 5], name='input_geo_maps')
else:
input_geo_maps = tf.placeholder(tf.float32, shape=[None, None, None, 8], name='input_geo_maps')
input_training_masks = tf.placeholder(tf.float32, shape=[None, None, None, 1], name='input_training_masks')
global_step = tf.get_variable('global_step', [], initializer=tf.constant_initializer(0), trainable=False)
learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps=10000, decay_rate=0.94, staircase=True)
# add summary
tf.summary.scalar('learning_rate', learning_rate)
opt = tf.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 = tf.split(input_images, len(gpus))
input_score_maps_split = tf.split(input_score_maps, len(gpus))
input_geo_maps_split = tf.split(input_geo_maps, len(gpus))
input_training_masks_split = tf.split(input_training_masks, len(gpus))
tower_grads = []
reuse_variables = None
for i, gpu_id in enumerate(gpus):
#with tf.device('/gpu:%d' % gpu_id):
with tf.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 = tf.group(*tf.get_collection(tf.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 = tf.summary.merge_all()
# save moving average
variable_averages = tf.train.ExponentialMovingAverage(
FLAGS.moving_average_decay, global_step)
variables_averages_op = variable_averages.apply(tf.trainable_variables())
# batch norm updates
with tf.control_dependencies([variables_averages_op, apply_gradient_op, batch_norm_updates_op]):
train_op = tf.no_op(name='train_op')
saver = tf.train.Saver(tf.global_variables())
summary_writer = tf.summary.FileWriter(FLAGS.checkpoint_path, tf.get_default_graph())
init = tf.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 = tf.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 = tf.compat.as_bytes("allow_mix_precision")
if FLAGS.auto_tune:
custom_op.parameter_map["auto_tune_mode"].s = tf.compat.as_bytes("RL,GA")
with tf.Session(config=config) as sess:
if FLAGS.restore:
print('continue training from previous checkpoint')
ckpt = tf.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__':
tf.app.run()
| [
"tensorflow.concat",
"tensorflow.gfile.DeleteRecursively",
"tensorflow.control_dependencies",
"tensorflow.gfile.Exists",
"tensorflow.gfile.MkDir",
"tensorflow.global_variables",
"tensorflow.cast",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.train.AdamOptimizer",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.get_default_graph",
"tensorflow.summary.scalar",
"tensorflow.get_collection",
"tensorflow.summary.image",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.train.exponential_decay",
"tensorflow.ConfigProto",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.trainable_variables",
"tensorflow.app.run",
"tensorflow.scalar_mul",
"numpy.isnan",
"tensorflow.placeholder",
"tensorflow.compat.as_bytes",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"tensorflow.no_op",
"tensorflow.contrib.slim.get_trainable_variables",
"tensorflow.train.latest_checkpoint",
"tensorflow.reduce_mean",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.get_variable_scope"
] | contrib/TensorFlow/Official/cv/east/EAST_ID0238_for_TensorFlow/npu_train.py | [(38, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""input_size"""', '(512)', '""""""'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""batch_size_per_gpu"""', '(14)', '""""""'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_readers"""', '(16)', '""""""'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""learning_rate"""', '(0.0001)', '""""""'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""max_steps"""', '(100000)', '""""""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""loss_scale"""', '(1024)', '""""""'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""moving_average_decay"""', '(0.997)', '""""""'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""gpu_list"""', '"""1"""', '""""""'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""checkpoint_path"""', '"""/tmp/east_resnet_v1_50_rbox/"""', '""""""'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""restore"""', '(False)', '"""whether to resotre from checkpoint"""'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_checkpoint_steps"""', '(1000)', '""""""'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""save_summary_steps"""', '(100)', '""""""'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""pretrained_model_path"""', 'None', '""""""'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""allow_mix_precision"""', '(False)', '"""whether to allow mix precision"""'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""auto_tune"""', '(False)', '"""whether to autotune"""'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""use_processed_data"""', '(False)', '"""whether to use processed data"""'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""processed_data"""', '"""./processed_dataset/"""', '"""where to save preprocessed datasets"""'], {}), True, 'import tensorflow as tf\n'), (69, 'model.loss', 'model.loss', (['score_maps', 'f_score', 'geo_maps', 'f_geometry', 'training_masks'], {}), False, 'import model\n'), (144, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (154, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None, None, 3]', 'name': '"""input_images"""'}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None, None, 1]', 'name': '"""input_score_maps"""'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None, None, 1]', 'name': '"""input_training_masks"""'}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['FLAGS.learning_rate', 'global_step'], {'decay_steps': '(10000)', 'decay_rate': '(0.94)', 'staircase': '(True)'}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""learning_rate"""', 'learning_rate'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), True, 'import tensorflow as tf\n'), (169, 'npu_bridge.estimator.npu.npu_optimizer.NPUDistributedOptimizer', 'NPUDistributedOptimizer', (['opt'], {}), False, 'from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer\n'), (195, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.train.ExponentialMovingAverage', 'tf.train.ExponentialMovingAverage', (['FLAGS.moving_average_decay', 'global_step'], {}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (67, 'model.model', 'model.model', (['images'], {'is_training': '(True)'}), False, 'import model\n'), (76, 'tensorflow.summary.image', 'tf.summary.image', (['"""input"""', 'images'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.summary.image', 'tf.summary.image', (['"""score_map"""', 'score_maps'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.summary.image', 'tf.summary.image', (['"""score_map_pred"""', '(f_score * 255)'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.summary.image', 'tf.summary.image', (['"""geo_map_0"""', 'geo_maps[:, :, :, 0:1]'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.summary.image', 'tf.summary.image', (['"""geo_map_0_pred"""', 'f_geometry[:, :, :, 0:1]'], {}), True, 'import tensorflow as tf\n'), (81, 'tensorflow.summary.image', 'tf.summary.image', (['"""training_masks"""', 'training_masks'], {}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""model_loss"""', 'model_loss'], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""total_loss"""', 'total_loss'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.concat', 'tf.concat', (['grads', '(0)'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['grad', '(0)'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['FLAGS.checkpoint_path'], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.gfile.MkDir', 'tf.gfile.MkDir', (['FLAGS.checkpoint_path'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None, None, 5]', 'name': '"""input_geo_maps"""'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None, None, 8]', 'name': '"""input_geo_maps"""'}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[variables_averages_op, apply_gradient_op, batch_norm_updates_op]'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.no_op', 'tf.no_op', ([], {'name': '"""train_op"""'}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.compat.as_bytes', 'tf.compat.as_bytes', (['"""allow_mix_precision"""'], {}), True, 'import tensorflow as tf\n'), (221, 'tensorflow.compat.as_bytes', 'tf.compat.as_bytes', (['"""RL,GA"""'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (237, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (280, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (66, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.expand_dims', 'tf.expand_dims', (['g', '(0)'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.scalar_mul', 'tf.scalar_mul', (['self._scale', 'loss'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.gfile.DeleteRecursively', 'tf.gfile.DeleteRecursively', (['FLAGS.checkpoint_path'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.gfile.MkDir', 'tf.gfile.MkDir', (['FLAGS.checkpoint_path'], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), True, 'import tensorflow as tf\n'), (180, 'tensorflow.name_scope', 'tf.name_scope', (["('model_%d' % gpu_id)"], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.contrib.slim.get_trainable_variables', 'slim.get_trainable_variables', ([], {}), False, 'from tensorflow.contrib import slim\n'), (226, 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['FLAGS.checkpoint_path'], {}), True, 'import tensorflow as tf\n'), (257, 'numpy.isnan', 'np.isnan', (['tl'], {}), True, 'import numpy as np\n'), (120, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.cast', 'tf.cast', (['grad', 'orig_var.dtype'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.scalar_mul', 'tf.scalar_mul', (['(1.0 / self._scale)', 'grad'], {}), True, 'import tensorflow as tf\n'), (242, 'random.randint', 'random.randint', (['(0)', '(1000 - 1)'], {}), False, 'import random\n'), (266, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (186, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS', 'scope'], {}), True, 'import tensorflow as tf\n'), (262, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (263, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (264, 'time.time', 'time.time', ([], {}), False, 'import time\n')] |
Ascend/modelzoo | f018cfed33dbb1cc2110b9ea2e233333f71cc509 | # Copyright 2016 The TensorFlow 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:
tensorflow/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 tensorflow as tf
from tensorflow.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 TensorFlow 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 = tf.TFRecordReader
keys_to_features = {
'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
'image/format': tf.FixedLenFeature((), tf.string, default_value='png'),
'image/class/label': tf.FixedLenFeature(
[], tf.int64, default_value=tf.zeros([], dtype=tf.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.TFExampleDecoder(
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,
)
| [
"tensorflow.FixedLenFeature",
"tensorflow.zeros"
] | built-in/TensorFlow/Official/cv/image_classification/MobileNetV2_for_TensorFlow/datasets/cifar10.py | [(82, 'os.path.join', 'os.path.join', (['dataset_dir', '(file_pattern % split_name)'], {}), False, 'import os\n'), (104, 'datasets.dataset_utils.has_labels', 'dataset_utils.has_labels', (['dataset_dir'], {}), False, 'from datasets import dataset_utils\n'), (89, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string'], {'default_value': '""""""'}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string'], {'default_value': '"""png"""'}), True, 'import tensorflow as tf\n'), (105, 'datasets.dataset_utils.read_label_file', 'dataset_utils.read_label_file', (['dataset_dir'], {}), False, 'from datasets import dataset_utils\n'), (92, 'tensorflow.zeros', 'tf.zeros', (['[]'], {'dtype': 'tf.int64'}), True, 'import tensorflow as tf\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 tensorflow as tf
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 = tf.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] = tf.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] = tf.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] = tf.get_variable(
name=('action-' + name),
shape=(self.capacity,) + tuple(action['shape']),
dtype=util.tf_dtype(action['type']),
trainable=False
)
# Terminal
self.terminal_memory = tf.get_variable(
name='terminal',
shape=(self.capacity,),
dtype=util.tf_dtype('bool'),
initializer=tf.constant_initializer(
value=False,
dtype=util.tf_dtype('bool')
),
trainable=False
)
# Reward
self.reward_memory = tf.get_variable(
name='reward',
shape=(self.capacity,),
dtype=util.tf_dtype('float'),
trainable=False
)
# Memory index
self.memory_index = tf.get_variable(
name='memory-index',
dtype=util.tf_dtype('int'),
initializer=0,
trainable=False
)
# Episode indices
self.episode_indices = tf.get_variable(
name='episode-indices',
shape=(self.capacity + 1,),
dtype=util.tf_dtype('int'),
initializer=tf.constant_initializer(value=(self.capacity - 1), dtype=util.tf_dtype('int')),
trainable=False
)
# Episodes index
self.episode_count = tf.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 = tf.shape(input=terminal)[0]
with tf.control_dependencies([tf.assert_less_equal(num_instances, self.capacity)]):
indices = tf.range(self.memory_index, self.memory_index + num_instances) % self.capacity
# Remove episode indices.
num_episodes = tf.count_nonzero(
input_tensor=tf.gather(params=self.terminal_memory, indices=indices),
axis=0,
dtype=util.tf_dtype('int')
)
num_episodes = tf.minimum(x=num_episodes, y=self.episode_count)
assignment = tf.assign(
ref=self.episode_indices[:self.episode_count - num_episodes],
value=self.episode_indices[num_episodes: self.episode_count]
)
# Decrement episode count.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign_sub(ref=self.episode_count, value=num_episodes)
# Assign new observations.
with tf.control_dependencies(control_inputs=(assignment,)):
assignments = list()
for name in sorted(states):
assignments.append(tf.scatter_update(
ref=self.states_memory[name],
indices=indices,
updates=states[name]
))
for name in sorted(internals):
assignments.append(tf.scatter_update(
ref=self.internals_memory[name],
indices=indices,
updates=internals[name]
))
for name in sorted(actions):
assignments.append(tf.scatter_update(
ref=self.actions_memory[name],
indices=indices,
updates=actions[name]
))
assignments.append(tf.scatter_update(ref=self.terminal_memory, indices=indices, updates=terminal))
assignments.append(tf.scatter_update(ref=self.reward_memory, indices=indices, updates=reward))
# Add episode indices.
with tf.control_dependencies(control_inputs=assignments):
num_episodes = tf.count_nonzero(input_tensor=terminal, axis=0, dtype=util.tf_dtype('int'))
assignment = tf.assign(
ref=self.episode_indices[self.episode_count: self.episode_count + num_episodes],
value=tf.boolean_mask(tensor=indices, mask=terminal)
)
# Increment episode count.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign_add(ref=self.episode_count, value=num_episodes)
# Increment memory index.
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign(
ref=self.episode_indices[-1],
value=tf.where(self.memory_index + num_instances > self.capacity,
self.episode_indices[self.episode_count - 1], self.capacity - 1)
)
with tf.control_dependencies(control_inputs=(assignment,)):
assignment = tf.assign(ref=self.memory_index, value=((self.memory_index + num_instances) % self.capacity))
with tf.control_dependencies(control_inputs=(assignment,)):
return tf.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] = tf.gather(params=self.states_memory[name], indices=indices)
internals = dict()
for name in sorted(self.internals_memory):
internals[name] = tf.gather(params=self.internals_memory[name], indices=indices)
actions = dict()
for name in sorted(self.actions_memory):
actions[name] = tf.gather(params=self.actions_memory[name], indices=indices)
terminal = tf.gather(params=self.terminal_memory, indices=indices)
reward = tf.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] = tf.gather(params=self.states_memory[name], indices=next_indices)
next_internals = dict()
for name in sorted(self.internals_memory):
next_internals[name] = tf.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
)
| [
"tensorflow.scatter_update",
"tensorflow.boolean_mask",
"tensorflow.assign_add",
"tensorflow.control_dependencies",
"tensorflow.shape",
"tensorflow.range",
"tensorflow.minimum",
"tensorflow.assign",
"tensorflow.assert_less_equal",
"tensorflow.gather",
"tensorflow.no_op",
"tensorflow.make_template",
"tensorflow.assign_sub",
"tensorflow.where"
] | tensorforce/core/memories/queue.py | [(65, 'tensorflow.make_template', 'tf.make_template', ([], {'name_': "(self.scope + '/retrieve_indices')", 'func_': 'self.tf_retrieve_indices', 'custom_getter_': 'custom_getter'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.minimum', 'tf.minimum', ([], {'x': 'num_episodes', 'y': 'self.episode_count'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.assign', 'tf.assign', ([], {'ref': 'self.episode_indices[:self.episode_count - num_episodes]', 'value': 'self.episode_indices[num_episodes:self.episode_count]'}), True, 'import tensorflow as tf\n'), (240, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.terminal_memory', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.reward_memory', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.shape', 'tf.shape', ([], {'input': 'terminal'}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.assign_sub', 'tf.assign_sub', ([], {'ref': 'self.episode_count', 'value': 'num_episodes'}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'assignments'}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.assign_add', 'tf.assign_add', ([], {'ref': 'self.episode_count', 'value': 'num_episodes'}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.assign', 'tf.assign', ([], {'ref': 'self.memory_index', 'value': '((self.memory_index + num_instances) % self.capacity)'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '(assignment,)'}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.states_memory[name]', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.internals_memory[name]', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.actions_memory[name]', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (106, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""bool"""'], {}), False, 'from tensorforce import util\n'), (118, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""float"""'], {}), False, 'from tensorforce import util\n'), (125, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n'), (134, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n'), (142, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n'), (151, 'tensorflow.range', 'tf.range', (['self.memory_index', '(self.memory_index + num_instances)'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.terminal_memory', 'indices': 'indices'}), True, 'import tensorflow as tf\n'), (157, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n'), (190, 'tensorflow.scatter_update', 'tf.scatter_update', ([], {'ref': 'self.terminal_memory', 'indices': 'indices', 'updates': 'terminal'}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.scatter_update', 'tf.scatter_update', ([], {'ref': 'self.reward_memory', 'indices': 'indices', 'updates': 'reward'}), True, 'import tensorflow as tf\n'), (244, 'tensorforce.util.rank', 'util.rank', (['indices'], {}), False, 'from tensorforce import util\n'), (249, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.states_memory[name]', 'indices': 'next_indices'}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.gather', 'tf.gather', ([], {'params': 'self.internals_memory[name]', 'indices': 'next_indices'}), True, 'import tensorflow as tf\n'), (78, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (["state['type']"], {}), False, 'from tensorforce import util\n'), (88, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (["internal['type']"], {}), False, 'from tensorforce import util\n'), (98, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (["action['type']"], {}), False, 'from tensorforce import util\n'), (150, 'tensorflow.assert_less_equal', 'tf.assert_less_equal', (['num_instances', 'self.capacity'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.scatter_update', 'tf.scatter_update', ([], {'ref': 'self.states_memory[name]', 'indices': 'indices', 'updates': 'states[name]'}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.scatter_update', 'tf.scatter_update', ([], {'ref': 'self.internals_memory[name]', 'indices': 'indices', 'updates': 'internals[name]'}), True, 'import tensorflow as tf\n'), (185, 'tensorflow.scatter_update', 'tf.scatter_update', ([], {'ref': 'self.actions_memory[name]', 'indices': 'indices', 'updates': 'actions[name]'}), True, 'import tensorflow as tf\n'), (195, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n'), (198, 'tensorflow.boolean_mask', 'tf.boolean_mask', ([], {'tensor': 'indices', 'mask': 'terminal'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.where', 'tf.where', (['(self.memory_index + num_instances > self.capacity)', 'self.episode_indices[self.episode_count - 1]', '(self.capacity - 1)'], {}), True, 'import tensorflow as tf\n'), (109, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""bool"""'], {}), False, 'from tensorforce import util\n'), (135, 'tensorforce.util.tf_dtype', 'util.tf_dtype', (['"""int"""'], {}), False, 'from tensorforce import util\n')] |
samgregoost/self_supervised_large | 9c0c33cf374a1d5112519939012a64bca98c5f8d | from __future__ import print_function
import tensorflow as tf
import numpy as np
import random
import TensorflowUtils as utils
import read_MITSceneParsingDataParis as scene_parsing
import datetime
import BatchDatsetReader as dataset
from six.moves import xrange
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("batch_size", "50", "batch size for training")
tf.flags.DEFINE_string("logs_dir", "/scratch1/ram095/nips20/logs_mnist128/", "path to logs directory")
tf.flags.DEFINE_string("data_dir", "/scratch1/ram095/nips20/paris_street", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer")
tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat")
tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False")
tf.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]
# tensorflow: 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 = tf.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 tf.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 tf.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 = tf.nn.relu(conv6, name="relu6")
if FLAGS.debug:
utils.add_activation_summary(relu6)
relu_dropout6 = tf.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 = tf.nn.relu(conv7, name="relu7")
if FLAGS.debug:
utils.add_activation_summary(relu7)
relu_dropout7 = tf.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 = tf.reshape(utils.conv2d_basic(relu_dropout7, W8, b8),[-1,4*4*150])
fc1 = tf.reshape(tf.layers.dense(conv8,4*4*150,activation = tf.nn.relu),[-1,4,4,150])
concat1 = tf.concat([fc1, z],axis = 3)
# annotation_pred1 = tf.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=tf.shape(image_net["pool4"]))
fuse_1 = tf.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=tf.shape(image_net["pool3"]))
fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2")
shape = tf.shape(image)
deconv_shape3 = tf.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 = tf.nn.relu(utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8))
annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction")
return tf.expand_dims(annotation_pred, dim=3), conv_t3
def train(loss_val, var_list):
optimizer = tf.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 tf.gradients(ys = loss, xs = Z)
def main(argv=None):
keep_probability = tf.placeholder(tf.float32, name="keep_probabilty")
image = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image")
annotation = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation")
z = tf.placeholder(tf.float32, shape=[None, 4, 4, 128], name="z")
# pred_annotation, logits = inference(image, keep_probability,z)
# tf.summary.image("input_image", image, max_outputs=2)
# tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2)
# tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2)
# loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits,
# labels=tf.squeeze(annotation, squeeze_dims=[3]),
# name="entropy")))
mask_ = tf.ones([FLAGS.batch_size,64,64,3])
mask = tf.pad(mask_, [[0,0],[32,32],[32,32],[0,0]])
mask2__ = tf.ones([FLAGS.batch_size,78,78,3])
mask2_ = tf.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)
tf.summary.image("input_image", image, max_outputs=2)
tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2)
tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2)
# loss0 = tf.reduce_mean(tf.abs(z))
loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square((image - logits)),[1,2,3])))
# loss2 = tf.reduce_mean(tf.square((image - logits)*mask2))
# loss = loss1 + loss2 + loss0
# loss = tf.reduce_mean(tf.squared_difference(logits ,annotation ))
loss_summary = tf.summary.scalar("entropy", loss)
grads = train_z(loss,z)
trainable_var = tf.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 = tf.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 = tf.Session()
print("Setting up Saver...")
saver = tf.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 = tf.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph)
validation_writer = tf.summary.FileWriter(FLAGS.logs_dir + '/validation')
sess.run(tf.global_variables_initializer())
ckpt = tf.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__":
tf.app.run()
| [
"tensorflow.concat",
"tensorflow.stack",
"numpy.squeeze",
"tensorflow.cast",
"numpy.mean",
"tensorflow.train.AdamOptimizer",
"tensorflow.flags.DEFINE_float",
"tensorflow.pad",
"tensorflow.summary.scalar",
"tensorflow.summary.image",
"tensorflow.gradients",
"tensorflow.layers.dense",
"numpy.copy",
"tensorflow.add",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.trainable_variables",
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.app.run",
"tensorflow.nn.dropout",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"numpy.transpose",
"tensorflow.flags.DEFINE_bool",
"tensorflow.flags.DEFINE_integer",
"tensorflow.train.get_checkpoint_state",
"tensorflow.nn.relu",
"tensorflow.summary.FileWriter",
"tensorflow.flags.DEFINE_string",
"tensorflow.ones",
"tensorflow.expand_dims",
"tensorflow.variable_scope",
"numpy.random.uniform"
] | mnist128.py | [(12, 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""batch_size"""', '"""50"""', '"""batch size for training"""'], {}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""logs_dir"""', '"""/scratch1/ram095/nips20/logs_mnist128/"""', '"""path to logs directory"""'], {}), True, 'import tensorflow as tf\n'), (14, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""data_dir"""', '"""/scratch1/ram095/nips20/paris_street"""', '"""path to dataset"""'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""learning_rate"""', '"""1e-4"""', '"""Learning rate for Adam Optimizer"""'], {}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""model_dir"""', '"""Model_zoo/"""', '"""Path to vgg model mat"""'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""debug"""', '"""False"""', '"""Debug mode: True/ False"""'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""mode"""', '"""train"""', '"""Mode train/ test/ visualize"""'], {}), True, 'import tensorflow as tf\n'), (95, 'TensorflowUtils.get_model_data', 'utils.get_model_data', (['FLAGS.model_dir', 'MODEL_URL'], {}), True, 'import TensorflowUtils as utils\n'), (98, 'numpy.mean', 'np.mean', (['mean'], {'axis': '(0, 1)'}), True, 'import numpy as np\n'), (100, 'numpy.squeeze', 'np.squeeze', (["model_data['layers']"], {}), True, 'import numpy as np\n'), (102, 'TensorflowUtils.process_image', 'utils.process_image', (['image', 'mean_pixel'], {}), True, 'import TensorflowUtils as utils\n'), (164, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['FLAGS.learning_rate'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.gradients', 'tf.gradients', ([], {'ys': 'loss', 'xs': 'Z'}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""keep_probabilty"""'}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, IMAGE_SIZE, IMAGE_SIZE, 3]', 'name': '"""input_image"""'}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, IMAGE_SIZE, IMAGE_SIZE, 3]', 'name': '"""annotation"""'}), True, 'import tensorflow as tf\n'), (180, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 4, 4, 128]', 'name': '"""z"""'}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.ones', 'tf.ones', (['[FLAGS.batch_size, 64, 64, 3]'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.pad', 'tf.pad', (['mask_', '[[0, 0], [32, 32], [32, 32], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.ones', 'tf.ones', (['[FLAGS.batch_size, 78, 78, 3]'], {}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.pad', 'tf.pad', (['mask2__', '[[0, 0], [25, 25], [25, 25], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.summary.image', 'tf.summary.image', (['"""input_image"""', 'image'], {'max_outputs': '(2)'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""entropy"""', 'loss'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (223, 'read_MITSceneParsingDataParis.read_dataset', 'scene_parsing.read_dataset', (['FLAGS.data_dir'], {}), True, 'import read_MITSceneParsingDataParis as scene_parsing\n'), (231, 'BatchDatsetReader.BatchDatset', 'dataset.BatchDatset', (['valid_records', 'image_options'], {}), True, 'import BatchDatsetReader as dataset\n'), (233, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (240, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(FLAGS.logs_dir + '/train')", 'sess.graph'], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(FLAGS.logs_dir + '/validation')"], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['FLAGS.logs_dir'], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""inference"""'], {}), True, 'import tensorflow as tf\n'), (108, 'TensorflowUtils.max_pool_2x2', 'utils.max_pool_2x2', (['conv_final_layer'], {}), True, 'import TensorflowUtils as utils\n'), (110, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[7, 7, 512, 4096]'], {'name': '"""W6"""'}), True, 'import TensorflowUtils as utils\n'), (111, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[4096]'], {'name': '"""b6"""'}), True, 'import TensorflowUtils as utils\n'), (112, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['pool5', 'W6', 'b6'], {}), True, 'import TensorflowUtils as utils\n'), (113, 'tensorflow.nn.relu', 'tf.nn.relu', (['conv6'], {'name': '"""relu6"""'}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['relu6'], {'keep_prob': 'keep_prob'}), True, 'import tensorflow as tf\n'), (118, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[1, 1, 4096, 4096]'], {'name': '"""W7"""'}), True, 'import TensorflowUtils as utils\n'), (119, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[4096]'], {'name': '"""b7"""'}), True, 'import TensorflowUtils as utils\n'), (120, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['relu_dropout6', 'W7', 'b7'], {}), True, 'import TensorflowUtils as utils\n'), (121, 'tensorflow.nn.relu', 'tf.nn.relu', (['conv7'], {'name': '"""relu7"""'}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['relu7'], {'keep_prob': 'keep_prob'}), True, 'import tensorflow as tf\n'), (126, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[1, 1, 4096, 150]'], {'name': '"""W8"""'}), True, 'import TensorflowUtils as utils\n'), (127, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[150]'], {'name': '"""b8"""'}), True, 'import TensorflowUtils as utils\n'), (135, 'tensorflow.concat', 'tf.concat', (['[fc1, z]'], {'axis': '(3)'}), True, 'import tensorflow as tf\n'), (141, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[4, 4, deconv_shape1[3].value, 278]'], {'name': '"""W_t1"""'}), True, 'import TensorflowUtils as utils\n'), (142, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[deconv_shape1[3].value]'], {'name': '"""b_t1"""'}), True, 'import TensorflowUtils as utils\n'), (144, 'tensorflow.add', 'tf.add', (['conv_t1', "image_net['pool4']"], {'name': '"""fuse_1"""'}), True, 'import tensorflow as tf\n'), (147, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[4, 4, deconv_shape2[3].value, deconv_shape1[3].value]'], {'name': '"""W_t2"""'}), True, 'import TensorflowUtils as utils\n'), (148, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[deconv_shape2[3].value]'], {'name': '"""b_t2"""'}), True, 'import TensorflowUtils as utils\n'), (150, 'tensorflow.add', 'tf.add', (['conv_t2', "image_net['pool3']"], {'name': '"""fuse_2"""'}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.stack', 'tf.stack', (['[shape[0], shape[1], shape[2], 3]'], {}), True, 'import tensorflow as tf\n'), (154, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[16, 16, 3, deconv_shape2[3].value]'], {'name': '"""W_t3"""'}), True, 'import TensorflowUtils as utils\n'), (155, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[3]'], {'name': '"""b_t3"""'}), True, 'import TensorflowUtils as utils\n'), (158, 'tensorflow.argmax', 'tf.argmax', (['conv_t3'], {'dimension': '(3)', 'name': '"""prediction"""'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.expand_dims', 'tf.expand_dims', (['annotation_pred'], {'dim': '(3)'}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.cast', 'tf.cast', (['annotation', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.cast', 'tf.cast', (['pred_annotation', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (230, 'BatchDatsetReader.BatchDatset', 'dataset.BatchDatset', (['train_records', 'image_options'], {}), True, 'import BatchDatsetReader as dataset\n'), (243, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (250, 'six.moves.xrange', 'xrange', (['MAX_ITERATION'], {}), False, 'from six.moves import xrange\n'), (53, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['current', 'kernels', 'bias'], {}), True, 'import TensorflowUtils as utils\n'), (115, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['relu6'], {}), True, 'import TensorflowUtils as utils\n'), (123, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['relu7'], {}), True, 'import TensorflowUtils as utils\n'), (130, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['relu_dropout7', 'W8', 'b8'], {}), True, 'import TensorflowUtils as utils\n'), (131, 'tensorflow.layers.dense', 'tf.layers.dense', (['conv8', '(4 * 4 * 150)'], {'activation': 'tf.nn.relu'}), True, 'import tensorflow as tf\n'), (156, 'TensorflowUtils.conv2d_transpose_strided', 'utils.conv2d_transpose_strided', (['fuse_2', 'W_t3', 'b_t3'], {'output_shape': 'deconv_shape3', 'stride': '(8)'}), True, 'import TensorflowUtils as utils\n'), (169, 'TensorflowUtils.add_gradient_summary', 'utils.add_gradient_summary', (['grad', 'var'], {}), True, 'import TensorflowUtils as utils\n'), (216, 'TensorflowUtils.add_to_regularization_and_summary', 'utils.add_to_regularization_and_summary', (['var'], {}), True, 'import TensorflowUtils as utils\n'), (253, 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-1.0)', 'high': '(1.0)', 'size': '(FLAGS.batch_size, 4, 4, 128)'}), True, 'import numpy as np\n'), (296, 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-1.0)', 'high': '(1.0)', 'size': '(FLAGS.batch_size, 4, 4, 128)'}), True, 'import numpy as np\n'), (51, 'numpy.transpose', 'np.transpose', (['kernels', '(1, 0, 2, 3)'], {}), True, 'import numpy as np\n'), (55, 'tensorflow.nn.relu', 'tf.nn.relu', (['current'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.shape', 'tf.shape', (["image_net['pool4']"], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.shape', 'tf.shape', (["image_net['pool3']"], {}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.square', 'tf.square', (['(image - logits)'], {}), True, 'import tensorflow as tf\n'), (260, 'numpy.copy', 'np.copy', (['z_'], {}), True, 'import numpy as np\n'), (266, 'numpy.copy', 'np.copy', (['v'], {}), True, 'import numpy as np\n'), (300, 'numpy.copy', 'np.copy', (['z_'], {}), True, 'import numpy as np\n'), (306, 'numpy.copy', 'np.copy', (['v'], {}), True, 'import numpy as np\n'), (57, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['current'], {}), True, 'import TensorflowUtils as utils\n'), (59, 'TensorflowUtils.avg_pool_2x2', 'utils.avg_pool_2x2', (['current'], {}), True, 'import TensorflowUtils as utils\n'), (288, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n')] |
uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | # Copyright 2017 The TensorFlow 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 TensorFlow 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 tensorflow as tf
import tensorflow.contrib.eager as tfe
from tensorflow.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(tf.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 = tf.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(tf.float32, xs.dtype)
self.assertEqual(tf.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 tf.device(device()):
optimizer = tf.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(tf.test.Benchmark):
def benchmarkEagerLinearRegression(self):
num_epochs = 10
num_batches = 200
batch_size = 64
dataset = linear_regression.synthetic_dataset(
w=tf.random_uniform([3, 1]),
b=tf.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 tf.device(device()):
optimizer = tf.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__":
tf.enable_eager_execution()
tf.test.main()
| [
"tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.fit",
"tensorflow.enable_eager_execution",
"tensorflow.contrib.eager.Iterator",
"tensorflow.test.main",
"tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.synthetic_dataset",
"tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.LinearModel",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.contrib.eager.num_gpus",
"tensorflow.random_uniform"
] | tensorflow/contrib/eager/python/examples/linear_regression/linear_regression_test.py | [(120, 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (41, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (44, 'shutil.rmtree', 'shutil.rmtree', (['self._tmp_logdir'], {}), False, 'import shutil\n'), (48, 'tensorflow.random_uniform', 'tf.random_uniform', (['[3, 1]'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.synthetic_dataset', 'linear_regression.synthetic_dataset', (['true_w', 'true_b', 'noise_level', 'batch_size', 'num_batches'], {}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (56, 'tensorflow.contrib.eager.Iterator', 'tfe.Iterator', (['dataset'], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (70, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.LinearModel', 'linear_regression.LinearModel', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (71, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.synthetic_dataset', 'linear_regression.synthetic_dataset', (['true_w', 'true_b'], {'noise_level': '(0.0)', 'batch_size': '(64)', 'num_batches': '(40)'}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (97, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.LinearModel', 'linear_regression.LinearModel', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (34, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (75, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.1)'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.fit', 'linear_regression.fit', (['model', 'dataset', 'optimizer'], {'logdir': 'self._tmp_logdir'}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (100, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.1)'}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.fit', 'linear_regression.fit', (['model', 'burn_in_dataset', 'optimizer'], {}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (105, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (90, 'tensorflow.random_uniform', 'tf.random_uniform', (['[3, 1]'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.random_uniform', 'tf.random_uniform', (['[1]'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.fit', 'linear_regression.fit', (['model', 'dataset', 'optimizer'], {}), False, 'from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression\n'), (108, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (80, 'os.path.join', 'os.path.join', (['self._tmp_logdir', '"""events.out.*"""'], {}), False, 'import os\n'), (113, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n')] |
uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | # Copyright 2018 The TensorFlow 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 tensorflow as tf
from tensorflow.contrib.eager.python.examples.revnet import blocks_test
from tensorflow.contrib.eager.python.examples.revnet import config as config_
from tensorflow.contrib.eager.python.examples.revnet import revnet
from tensorflow.python.client import device_lib
tfe = tf.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(tf.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 = tf.float64
config.fused = False # Fused batch norm does not support tf.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 = tf.random_normal(shape=shape, dtype=tf.float64)
self.t = tf.random_uniform(
shape=[config.batch_size],
minval=0,
maxval=config.n_classes,
dtype=tf.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 [tf.reshape(g, [-1]) for g in gs]
g1_all = tf.concat(_combine(grads), axis=0)
g2_all = tf.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 tf.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
# tf.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 tf.Graph().as_default():
config = config_.get_hparams_cifar_38()
config.add_hparam("n_classes", 10)
config.add_hparam("dataset", "cifar-10")
x = tf.random_normal(
shape=(self.config.batch_size,) + self.config.input_shape)
t = tf.random_uniform(
shape=(self.config.batch_size,),
minval=0,
maxval=self.config.n_classes,
dtype=tf.int32)
global_step = tf.Variable(0., trainable=False)
model = revnet.RevNet(config=config)
_, saved_hidden = model(x)
grads, _ = model.compute_gradients(saved_hidden=saved_hidden, labels=t)
optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)
train_op = optimizer.apply_gradients(
zip(grads, model.trainable_variables), global_step=global_step)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for _ in range(1):
sess.run(train_op)
# Benchmark related
def device_and_data_format():
return ("/gpu:0",
"channels_first") if tf.test.is_gpu_available() else ("/cpu:0",
"channels_last")
def random_batch(batch_size, config):
shape = (batch_size,) + config.input_shape
images = tf.random_uniform(shape)
labels = tf.random_uniform(
[batch_size], minval=0, maxval=config.n_classes, dtype=tf.int32)
return images, labels
class MockIterator(object):
def __init__(self, tensors):
self._tensors = [tf.identity(x) for x in tensors]
def next(self):
return self._tensors
class RevNetBenchmark(tf.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 tf.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 tf.DeviceSpec.from_string(device.name).device_type == "TPU":
return (32,)
return (16, 32)
def _force_device_sync(self):
"""Shamelessly copied from `resnet50_test.py`."""
tf.constant(1.).cpu()
def _report(self, label, start, num_iters, device, batch_size, data_format):
avg_time = (time.time() - start) / num_iters
dev = tf.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 tf.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 = tf.train.GradientDescentOptimizer(0.1)
if defun:
model.call = tfe.function(model.call)
num_burn = 3
num_iters = 10
with tf.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 tf.device("/device:CPU:0"):
ds = tf.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__":
tf.enable_eager_execution()
tf.test.main()
| [
"tensorflow.device",
"tensorflow.enable_eager_execution",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.DeviceSpec.from_string",
"tensorflow.train.AdamOptimizer",
"tensorflow.Graph",
"tensorflow.Variable",
"tensorflow.test.main",
"tensorflow.Session",
"tensorflow.contrib.eager.python.examples.revnet.blocks_test.compute_degree",
"tensorflow.data.Dataset.from_tensors",
"tensorflow.identity",
"tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_imagenet_56",
"tensorflow.GradientTape",
"tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_cifar_38",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.test.is_gpu_available",
"tensorflow.random_uniform",
"tensorflow.random_normal"
] | tensorflow/contrib/eager/python/examples/revnet/revnet_test.py | [(180, 'tensorflow.random_uniform', 'tf.random_uniform', (['shape'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.random_uniform', 'tf.random_uniform', (['[batch_size]'], {'minval': '(0)', 'maxval': 'config.n_classes', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_cifar_38', 'config_.get_hparams_cifar_38', ([], {}), True, 'from tensorflow.contrib.eager.python.examples.revnet import config as config_\n'), (57, 'tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet', 'revnet.RevNet', ([], {'config': 'config'}), False, 'from tensorflow.contrib.eager.python.examples.revnet import revnet\n'), (58, 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': 'shape', 'dtype': 'tf.float64'}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '[config.batch_size]', 'minval': '(0)', 'maxval': 'config.n_classes', 'dtype': 'tf.int64'}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.contrib.eager.python.examples.revnet.blocks_test.compute_degree', 'blocks_test.compute_degree', (['g1_all', 'g2_all'], {}), False, 'from tensorflow.contrib.eager.python.examples.revnet import blocks_test\n'), (174, 'tensorflow.test.is_gpu_available', 'tf.test.is_gpu_available', ([], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', ([], {}), False, 'from tensorflow.python.client import device_lib\n'), (235, 'tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_imagenet_56', 'config_.get_hparams_imagenet_56', ([], {}), True, 'from tensorflow.contrib.eager.python.examples.revnet import config as config_\n'), (280, 'tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_imagenet_56', 'config_.get_hparams_imagenet_56', ([], {}), True, 'from tensorflow.contrib.eager.python.examples.revnet import config as config_\n'), (115, 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.contrib.eager.python.examples.revnet.config.get_hparams_cifar_38', 'config_.get_hparams_cifar_38', ([], {}), True, 'from tensorflow.contrib.eager.python.examples.revnet import config as config_\n'), (150, 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '((self.config.batch_size,) + self.config.input_shape)'}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.random_uniform', 'tf.random_uniform', ([], {'shape': '(self.config.batch_size,)', 'minval': '(0)', 'maxval': 'self.config.n_classes', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.Variable', 'tf.Variable', (['(0.0)'], {'trainable': '(False)'}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet', 'revnet.RevNet', ([], {'config': 'config'}), False, 'from tensorflow.contrib.eager.python.examples.revnet import revnet\n'), (161, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.001)'}), True, 'import tensorflow as tf\n'), (190, 'tensorflow.identity', 'tf.identity', (['x'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet', 'revnet.RevNet', ([], {'config': 'config'}), False, 'from tensorflow.contrib.eager.python.examples.revnet import revnet\n'), (91, 'tensorflow.reshape', 'tf.reshape', (['g', '[-1]'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (223, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (245, 'tensorflow.device', 'tf.device', (['device'], {}), True, 'import tensorflow as tf\n'), (251, 'gc.collect', 'gc.collect', ([], {}), False, 'import gc\n'), (252, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (285, 'tensorflow.contrib.eager.python.examples.revnet.revnet.RevNet', 'revnet.RevNet', ([], {'config': 'config'}), False, 'from tensorflow.contrib.eager.python.examples.revnet import revnet\n'), (286, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(0.1)'], {}), True, 'import tensorflow as tf\n'), (330, 'tensorflow.device', 'tf.device', (['"""/device:CPU:0"""'], {}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.DeviceSpec.from_string', 'tf.DeviceSpec.from_string', (['device.name'], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.DeviceSpec.from_string', 'tf.DeviceSpec.from_string', (['device.name'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.DeviceSpec.from_string', 'tf.DeviceSpec.from_string', (['device'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.device', 'tf.device', (['device'], {}), True, 'import tensorflow as tf\n'), (300, 'gc.collect', 'gc.collect', ([], {}), False, 'import gc\n'), (302, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (331, 'tensorflow.data.Dataset.from_tensors', 'tf.data.Dataset.from_tensors', (['tensors'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
# 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 = tf.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()
| [
"tensorflow.contrib.layers.xavier_initializer"
] | baselines/pois2/run.py | [(108, 'baselines.common.tf_util.make_session', 'U.make_session', (['affinity'], {}), True, 'import baselines.common.tf_util as U\n'), (111, 'baselines.common.set_global_seeds', 'set_global_seeds', (['seed'], {}), False, 'from baselines.common import set_global_seeds\n'), (113, 'gym.logger.setLevel', 'gym.logger.setLevel', (['logging.WARN'], {}), False, 'import gym\n'), (115, 'baselines.pois2.pois2.learn', 'pois2.learn', (['parallel_env', 'make_policy'], {}), False, 'from baselines.pois2 import pois2\n'), (119, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), False, 'import argparse\n'), (148, 'baselines.logger.configure', 'logger.configure', ([], {'dir': 'args.logdir', 'format_strs': "['stdout', 'csv', 'tensorboard']", 'file_name': 'file_name'}), False, 'from baselines import logger\n'), (34, 'baselines.common.rllab_utils.rllab_env_from_name', 'rllab_env_from_name', (['env_name'], {}), False, 'from baselines.common.rllab_utils import Rllab2GymWrapper, rllab_env_from_name\n'), (47, 'baselines.common.cmd_util.get_env_type', 'get_env_type', (['env'], {}), False, 'from baselines.common.cmd_util import get_env_type\n'), (82, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (84, 'baselines.common.tf_util.normc_initializer', 'U.normc_initializer', (['(0.0)'], {}), True, 'import baselines.common.tf_util as U\n'), (92, 'baselines.policy.mlp_policy.MlpPolicy', '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'}), False, 'from baselines.policy.mlp_policy import MlpPolicy\n'), (105, 'os.sched_getaffinity', 'os.sched_getaffinity', (['(0)'], {}), False, 'import sys, re, os, time, logging\n'), (33, 're.match', 're.match', (['"""rllab.(\\\\S+)"""', 'env'], {}), False, 'import sys, re, os, time, logging\n'), (86, 'baselines.common.tf_util.normc_initializer', 'U.normc_initializer', (['(0.1)'], {}), True, 'import baselines.common.tf_util as U\n'), (97, 'baselines.policy.cnn_policy.CnnPolicy', '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'}), False, 'from baselines.policy.cnn_policy import CnnPolicy\n'), (145, 'time.time', 'time.time', ([], {}), False, 'import sys, re, os, time, logging\n'), (54, 'baselines.common.atari_wrappers.make_atari', 'make_atari', (['env'], {}), False, 'from baselines.common.atari_wrappers import make_atari, wrap_deepmind\n'), (56, 'baselines.common.atari_wrappers.wrap_deepmind', 'wrap_deepmind', (['_env'], {}), False, 'from baselines.common.atari_wrappers import make_atari, wrap_deepmind\n'), (63, 'gym.make', 'gym.make', (['env'], {}), False, 'import gym\n')] |
gitter-badger/mlmodels | f70f1da7434e8855eed50adc67b49cc169f2ea24 | # coding: utf-8
# In[1]:
import os
import numpy as np
import tensorflow as tf
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]:
tf.reset_default_graph()
sess = tf.InteractiveSession()
model = Model()
sess.run(tf.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))
| [
"numpy.pad",
"tensorflow.InteractiveSession",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"numpy.load"
] | mlmodels/model_tf/misc/tf_nlp/speech-to-text/1.tacotron/train.py | [(43, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), True, 'import tensorflow as tf\n'), (45, 'model.Model', 'Model', ([], {}), False, 'from model import Model\n'), (46, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (19, 'os.listdir', 'os.listdir', (['"""spectrogram"""'], {}), False, 'import os\n'), (34, 'numpy.load', 'np.load', (["('spectrogram/' + path + '.npy')"], {}), True, 'import numpy as np\n'), (62, 'numpy.pad', 'np.pad', (['files[n]', '((max_x - files[n].shape[0], 0), (0, 0))'], {'mode': '"""constant"""'}), True, 'import numpy as np\n')] |
gitter-badger/mlmodels | f70f1da7434e8855eed50adc67b49cc169f2ea24 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import tensorflow as tf
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 tf.variable_scope(scope):
outputs = tf.layers.dense(inputs, units=num_units[0], activation=tf.nn.relu, name="dense1")
outputs = tf.layers.dropout(
outputs, rate=dropout_rate, training=is_training, name="dropout1"
)
outputs = tf.layers.dense(outputs, units=num_units[1], activation=tf.nn.relu, name="dense2")
outputs = tf.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 tf.variable_scope(scope):
H = tf.layers.dense(inputs, units=num_units, activation=tf.nn.relu, name="dense1")
T = tf.layers.dense(
inputs,
units=num_units,
activation=tf.nn.sigmoid,
bias_initializer=tf.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 tf.variable_scope(scope):
outputs = tf.layers.conv1d(inputs, embed_size // 2, 1, padding="SAME")
for k in range(2, K + 1):
with tf.variable_scope("num_{}".format(k)):
output = tf.layers.conv1d(inputs, embed_size // 2, k, padding="SAME")
outputs = tf.concat((outputs, output), -1)
outputs = tf.nn.relu(tf.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 = tf.placeholder(tf.int32, (None, None))
self.training = tf.placeholder(tf.bool, None)
lookup_table = tf.get_variable(
"lookup_table",
dtype=tf.float32,
shape=[len(vocab), size_layers],
initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.01),
)
lookup_table = tf.concat((tf.zeros(shape=[1, size_layers]), lookup_table[1:, :]), 0)
forward = tf.nn.embedding_lookup(lookup_table, self.X)
self.Y = tf.placeholder(tf.float32, (None, None, n_mels * resampled))
self.decoder_inputs = tf.concat((tf.zeros_like(self.Y[:, :1, :]), self.Y[:, :-1, :]), 1)
self.decoder_inputs = self.decoder_inputs[:, :, -n_mels:]
self.Z = tf.placeholder(tf.float32, (None, None, fourier_window_size // 2 + 1))
batch_size = tf.shape(self.X)[0]
seq_lens = tf.count_nonzero(tf.reduce_sum(self.decoder_inputs, -1), 1, dtype=tf.int32) + 1
def cells(reuse=False):
return tf.contrib.rnn.DropoutWrapper(
tf.nn.rnn_cell.LSTMCell(
size_layers, initializer=tf.orthogonal_initializer(), reuse=reuse
),
state_keep_prob=dropout,
output_keep_prob=dropout,
)
def attention(encoder_out, seq_len, reuse=False):
attention_mechanism = tf.contrib.seq2seq.LuongAttention(
num_units=size_layers, memory=encoder_out, memory_sequence_length=seq_len
)
return tf.contrib.seq2seq.AttentionWrapper(
cell=tf.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 = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])
encoder_out, encoder_state = tf.nn.dynamic_rnn(
cell=encoder_cells, inputs=forward, sequence_length=seq_lens, dtype=tf.float32
)
encoder_state = tuple(encoder_state[-1] for _ in range(num_layers))
decoder_cell = attention(encoder_out, seq_lens)
dense_layer = tf.layers.Dense(n_mels * resampled)
training_helper = tf.contrib.seq2seq.TrainingHelper(
inputs=self.decoder_inputs, sequence_length=seq_lens, time_major=False
)
training_decoder = tf.contrib.seq2seq.BasicDecoder(
cell=decoder_cell,
helper=training_helper,
initial_state=decoder_cell.zero_state(batch_size, tf.float32).clone(
cell_state=encoder_state
),
output_layer=dense_layer,
)
training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(
decoder=training_decoder,
impute_finished=True,
maximum_iterations=tf.reduce_max(seq_lens),
)
self.Y_hat = training_decoder_output.rnn_output
out_decoder2 = tf.reshape(self.Y_hat, [tf.shape(self.Y_hat)[0], -1, n_mels])
dec = conv1d_banks(out_decoder2, K=decoder_num_banks, is_training=self.training)
dec = tf.layers.max_pooling1d(dec, pool_size=2, strides=1, padding="same")
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-1", padding="SAME")
dec = tf.nn.relu(tf.layers.batch_normalization(dec, training=self.training))
dec = tf.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-2", padding="SAME")
dec = tf.layers.batch_normalization(dec, training=self.training)
dec = tf.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 tf.variable_scope("decoder-gru", reuse=False):
cell = tf.contrib.rnn.GRUCell(embed_size // 2)
cell_bw = tf.contrib.rnn.GRUCell(embed_size // 2)
outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell, cell_bw, dec, dtype=tf.float32)
outputs = tf.concat(outputs, 2)
self.Z_hat = tf.layers.dense(outputs, 1 + fourier_window_size // 2)
self.loss1 = tf.reduce_mean(tf.abs(self.Y_hat - self.Y))
self.loss2 = tf.reduce_mean(tf.abs(self.Z_hat - self.Z))
self.loss = self.loss1 + self.loss2
self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss)
# In[3]:
tf.reset_default_graph()
sess = tf.InteractiveSession()
size_layers = 128
learning_rate = 1e-3
num_layers = 2
model = Model(num_layers, size_layers, learning_rate)
sess.run(tf.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[ ]:
| [
"tensorflow.layers.conv1d",
"tensorflow.nn.dynamic_rnn",
"tensorflow.concat",
"tensorflow.contrib.rnn.GRUCell",
"tensorflow.zeros",
"tensorflow.layers.dropout",
"tensorflow.reduce_sum",
"tensorflow.nn.bidirectional_dynamic_rnn",
"tensorflow.orthogonal_initializer",
"tensorflow.train.AdamOptimizer",
"tensorflow.layers.max_pooling1d",
"tensorflow.layers.batch_normalization",
"tensorflow.contrib.seq2seq.LuongAttention",
"tensorflow.layers.dense",
"tensorflow.truncated_normal_initializer",
"tensorflow.reset_default_graph",
"tensorflow.InteractiveSession",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.layers.Dense",
"tensorflow.global_variables_initializer",
"tensorflow.zeros_like",
"tensorflow.nn.embedding_lookup",
"tensorflow.contrib.seq2seq.TrainingHelper",
"tensorflow.reduce_max",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.abs"
] | mlmodels/model_tf/misc/tf_nlp/text-to-speech/3.seq2seq-luong.py | [(154, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (250, 'os.path.join', 'os.path.join', (['"""test.wav"""'], {}), False, 'import os\n'), (21, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (22, 'tensorflow.layers.dense', 'tf.layers.dense', (['inputs'], {'units': 'num_units[0]', 'activation': 'tf.nn.relu', 'name': '"""dense1"""'}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.layers.dropout', 'tf.layers.dropout', (['outputs'], {'rate': 'dropout_rate', 'training': 'is_training', 'name': '"""dropout1"""'}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.layers.dense', 'tf.layers.dense', (['outputs'], {'units': 'num_units[1]', 'activation': 'tf.nn.relu', 'name': '"""dense2"""'}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.layers.dropout', 'tf.layers.dropout', (['outputs'], {'rate': 'dropout_rate', 'training': 'is_training', 'name': '"""dropout2"""'}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.layers.dense', 'tf.layers.dense', (['inputs'], {'units': 'num_units', 'activation': 'tf.nn.relu', 'name': '"""dense1"""'}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.layers.conv1d', 'tf.layers.conv1d', (['inputs', '(embed_size // 2)', '(1)'], {'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '(None, None)'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool', 'None'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['lookup_table', 'self.X'], {}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, None, n_mels * resampled)'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, None, fourier_window_size // 2 + 1)'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', ([], {'cell': 'encoder_cells', 'inputs': 'forward', 'sequence_length': 'seq_lens', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.layers.Dense', 'tf.layers.Dense', (['(n_mels * resampled)'], {}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.contrib.seq2seq.TrainingHelper', 'tf.contrib.seq2seq.TrainingHelper', ([], {'inputs': 'self.decoder_inputs', 'sequence_length': 'seq_lens', 'time_major': '(False)'}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.layers.max_pooling1d', 'tf.layers.max_pooling1d', (['dec'], {'pool_size': '(2)', 'strides': '(1)', 'padding': '"""same"""'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.layers.conv1d', 'tf.layers.conv1d', (['dec', '(embed_size // 2)', '(3)'], {'name': '"""decoder-conv1-1"""', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.layers.conv1d', 'tf.layers.conv1d', (['dec', '(embed_size // 2)', '(3)'], {'name': '"""decoder-conv1-2"""', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['dec'], {'training': 'self.training'}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.layers.dense', 'tf.layers.dense', (['dec', '(embed_size // 2)'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.layers.dense', 'tf.layers.dense', (['outputs', '(1 + fourier_window_size // 2)'], {}), True, 'import tensorflow as tf\n'), (169, 'os.listdir', 'os.listdir', (['"""mel"""'], {}), False, 'import os\n'), (56, 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['outputs'], {'training': 'is_training'}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.shape', 'tf.shape', (['self.X'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.contrib.seq2seq.LuongAttention', 'tf.contrib.seq2seq.LuongAttention', ([], {'num_units': 'size_layers', 'memory': 'encoder_out', 'memory_sequence_length': 'seq_len'}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['dec'], {'training': 'self.training'}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder-gru"""'], {'reuse': '(False)'}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.contrib.rnn.GRUCell', 'tf.contrib.rnn.GRUCell', (['(embed_size // 2)'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.contrib.rnn.GRUCell', 'tf.contrib.rnn.GRUCell', (['(embed_size // 2)'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.nn.bidirectional_dynamic_rnn', 'tf.nn.bidirectional_dynamic_rnn', (['cell', 'cell_bw', 'dec'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.concat', 'tf.concat', (['outputs', '(2)'], {}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.abs', 'tf.abs', (['(self.Y_hat - self.Y)'], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.abs', 'tf.abs', (['(self.Z_hat - self.Z)'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(-1.0)'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.layers.conv1d', 'tf.layers.conv1d', (['inputs', '(embed_size // 2)', 'k'], {'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.concat', 'tf.concat', (['(outputs, output)', '(-1)'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'mean': '(0.0)', 'stddev': '(0.01)'}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '[1, size_layers]'}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.zeros_like', 'tf.zeros_like', (['self.Y[:, :1, :]'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self.decoder_inputs', '(-1)'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.reduce_max', 'tf.reduce_max', (['seq_lens'], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.shape', 'tf.shape', (['self.Y_hat'], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.orthogonal_initializer', 'tf.orthogonal_initializer', ([], {}), True, 'import tensorflow as tf\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 tensorflow.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"))
| [
"matplotlib.pyplot.legend",
"numpy.random.seed",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"numpy.random.normal",
"numpy.random.permutation",
"numpy.savetxt",
"numpy.random.uniform",
"matplotlib.pyplot.xticks",
"numpy.array",
"numpy.zeros",
"numpy.loadtxt",
"matplotlib.pyplot.figure"
] | andres@programo.ual.es/evaluatePCA.py | [(17, 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), True, 'import numpy as np\n'), (50, 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""MNIST_data/"""'], {}), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), (71, 'numpy.zeros', 'np.zeros', (['(10)'], {}), True, 'import numpy as np\n'), (74, 'numpy.array', 'np.array', (['[25, 50, 100, 250, 500, 750, 1000]'], {}), True, 'import numpy as np\n'), (78, 'numpy.zeros', 'np.zeros', (['samples.shape[0]'], {}), True, 'import numpy as np\n'), (80, 'numpy.zeros', 'np.zeros', (['(4, samples.shape[0])'], {}), True, 'import numpy as np\n'), (109, 'numpy.savetxt', 'np.savetxt', (['"""./figs/PCA_MINST_clustererror.txt"""', 'clusterError'], {}), True, 'import numpy as np\n'), (110, 'numpy.savetxt', 'np.savetxt', (['"""./figs/PCA_MINST_data.txt"""', 'test_ll'], {}), True, 'import numpy as np\n'), (112, 'numpy.loadtxt', 'np.loadtxt', (['"""./datareduction/figs/PCA_MINST_data.txt"""'], {}), True, 'import numpy as np\n'), (113, 'numpy.loadtxt', 'np.loadtxt', (['"""./datareduction/figs/PCA_MINST_clustererror.txt"""'], {}), True, 'import numpy as np\n'), (117, 'matplotlib.pyplot.figure', 'plt.figure', (['(0)'], {}), True, 'import matplotlib.pyplot as plt\n'), (118, 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'test_ll[(1), :]'], {'c': '"""b"""', 'label': '"""DR-SS"""'}), True, 'import matplotlib.pyplot as plt\n'), (119, 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'test_ll[(2), :]'], {'c': '"""g"""', 'label': '"""DR-NoSS"""'}), True, 'import matplotlib.pyplot as plt\n'), (120, 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'test_ll[(3), :]'], {'c': '"""y"""', 'label': '"""DR-Random"""'}), True, 'import matplotlib.pyplot as plt\n'), (121, 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""', 'shadow': '(True)'}), True, 'import matplotlib.pyplot as plt\n'), (122, 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', 'test_ll[(0), :]'], {}), True, 'import matplotlib.pyplot as plt\n'), (123, 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-5000000.0)', '(2000000.0)', '(100)'], {}), True, 'import matplotlib.pyplot as plt\n'), (124, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./datareduction/figs/PCA_MINST_LL.pdf"""'], {'bbox_inches': '"""tight"""'}), True, 'import matplotlib.pyplot as plt\n'), (126, 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), True, 'import matplotlib.pyplot as plt\n'), (127, 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'test_ll[(1), :]'], {'c': '"""b"""', 'label': '"""Log-Likelihood"""'}), True, 'import matplotlib.pyplot as plt\n'), (128, 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'clusterError'], {'c': '"""k"""', 'label': '"""ClusterError"""'}), True, 'import matplotlib.pyplot as plt\n'), (129, 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center right"""', 'shadow': '(True)'}), True, 'import matplotlib.pyplot as plt\n'), (130, 'matplotlib.pyplot.xticks', 'plt.xticks', (['x', 'test_ll[(0), :]'], {}), True, 'import matplotlib.pyplot as plt\n'), (131, 'matplotlib.pyplot.ylim', 'plt.ylim', (['(200000.0)', '(2000000.0)', '(100)'], {}), True, 'import matplotlib.pyplot as plt\n'), (132, 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./datareduction/figs/PCA_MINST_ClusterError.pdf"""'], {'bbox_inches': '"""tight"""'}), True, 'import matplotlib.pyplot as plt\n'), (133, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (26, 'numpy.random.normal', 'np.random.normal', ([], {'size': '(sample_size, ndim_hidden)'}), True, 'import numpy as np\n'), (27, 'numpy.random.uniform', 'np.random.uniform', (['(-5)', '(5)'], {'size': 'ndim_observe'}), True, 'import numpy as np\n'), (28, 'numpy.random.uniform', 'np.random.uniform', (['(-5)', '(5)', '(ndim_hidden, ndim_observe)'], {}), True, 'import numpy as np\n'), (40, 'numpy.random.permutation', 'np.random.permutation', (['data.shape[0]'], {}), True, 'import numpy as np\n'), (53, 'numpy.random.permutation', 'np.random.permutation', (['mnist.train.images.shape[0]'], {}), True, 'import numpy as np\n'), (54, 'numpy.random.permutation', 'np.random.permutation', (['mnist.test.images.shape[0]'], {}), True, 'import numpy as np\n'), (86, 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), True, 'import numpy as np\n'), (87, 'datareduction.bayesian_pca_DR.BayesianPCA_DR', 'BayesianPCA_DR', ([], {'n_components': 'K'}), False, 'from datareduction.bayesian_pca_DR import BayesianPCA_DR\n'), (95, 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), True, 'import numpy as np\n'), (96, 'datareduction.bayesian_pca_DR.BayesianPCA_DR', 'BayesianPCA_DR', ([], {'n_components': 'K'}), False, 'from datareduction.bayesian_pca_DR import BayesianPCA_DR\n'), (101, 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), True, 'import numpy as np\n'), (102, 'datareduction.bayesian_pca_DR.BayesianPCA_DR', 'BayesianPCA_DR', ([], {'n_components': 'K'}), False, 'from datareduction.bayesian_pca_DR import BayesianPCA_DR\n'), (137, 'tabulate.tabulate', 'tabulate', (['test_ll'], {'tablefmt': '"""latex"""', 'floatfmt': '""".2f"""'}), False, 'from tabulate import tabulate\n'), (138, 'tabulate.tabulate', 'tabulate', (['clusterError[(None), :]'], {'tablefmt': '"""latex"""', 'floatfmt': '""".2f"""'}), False, 'from tabulate import tabulate\n'), (30, 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'std', 'size': '(sample_size, ndim_observe)'}), True, 'import numpy as np\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 TensorFlow" tutorial '''
import numpy as np
import tensorflow as tf
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 = tf.Variable([0.0])
y = output + bias
loss = tf.reduce_sum(tf.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 = tf.Variable([0.0])
y = output + bias
sig_y = tf.clip_by_value(tf.sigmoid(y), 0.001, 0.999) # avoid NaNs
loss = -tf.reduce_sum(target*tf.log(sig_y) + (1-target)*tf.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 = tf.reshape(output, [-1,2]) # fold: 1 x n -> [n/2 x 2]
pos_scores, neg_scores = tf.split(1, 2, y_pairs) # separate pairs
hinge_losses = tf.nn.relu(margin - pos_scores + neg_scores)
total_hinge_loss = tf.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 = tf.nn.embedding_lookup(var_matrix, indices)
row_norms = tf.sqrt(tf.reduce_sum(tf.square(selected_rows), 1))
scaling = maxnorm / tf.maximum(row_norms, maxnorm)
scaled = selected_rows * tf.expand_dims(scaling, 1)
return tf.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 = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(row_norms, maxnorm)
scaled = var_matrix * tf.expand_dims(scaling, 1)
return tf.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 = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1))
scaling = maxnorm / tf.maximum(axis_norms, maxnorm)
return var_matrix * tf.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
tf.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 = tf.train.AdagradOptimizer(1.0)
self.opt = opt
self.sess = None
self.train_step = None
self.post_step = None
self.graph = tf.Graph()
with self.graph.as_default():
self.head_input = tf.placeholder(tf.int32, shape=[None])
self.rel_input = tf.placeholder(tf.int32, shape=[None])
self.tail_input = tf.placeholder(tf.int32, shape=[None])
self.target = tf.placeholder(tf.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, TF optimizers do not update variables with zero gradient
# except AdamOptimizer
if isinstance(self.opt, tf.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 TensorFlow 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 TensorFlow 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 = tf.Session(graph=self.graph)
with self.graph.as_default():
self._create_model(train_triples)
self.sess.run(tf.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
tf.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 = tf.truncated_normal([head_cnt, self.embedding_size], stddev=init_sd)
rel_init = tf.truncated_normal([rel_cnt, self.embedding_size], stddev=init_sd)
tail_init = tf.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 = tf.Variable(head_init)
self.rel_embedding_vars = tf.Variable(rel_init)
self.tail_embedding_vars = tf.Variable(tail_init)
# Embedding layer for each (head, rel, tail) triple being fed in as input
head_embed = tf.nn.embedding_lookup(self.head_embedding_vars, self.head_input)
rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)
tail_embed = tf.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input)
# Model output
raw_output = tf.reduce_sum(tf.mul(tf.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,
tf.unique(self.head_input)[0],
self.maxnorm)
rel_constraint = self._norm_constraint_op(self.rel_embedding_vars,
tf.unique(self.rel_input)[0],
self.maxnorm)
tail_constraint = self._norm_constraint_op(self.tail_embedding_vars,
tf.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
tf.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 = tf.truncated_normal(entity_embedding_shape, stddev=init_sd)
rel_init = tf.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 = tf.Variable(entity_init)
self.rel_embedding_vars = tf.Variable(rel_init)
# Embedding layer for each (head, rel, tail) triple being fed in as input
head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input)
tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input)
rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input)
# Reshape rel_embed into square D x D matrices
rel_embed_square = tf.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 = tf.expand_dims(head_embed, 1) # embeddings as row vectors
tail_embed_col = tf.expand_dims(tail_embed, 2) # embeddings as column vectors
head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square)
# Output needs a squeeze into a 1d vector
raw_output = tf.squeeze(tf.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 = tf.unique(tf.concat(0, [self.head_input, self.tail_input]))[0]
unique_rel_indices = tf.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
tf.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 = tf.truncated_normal(entity_var_shape, stddev=init_sd)
rel_init = tf.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 = tf.Variable(entity_init)
self.rel_embedding_vars = tf.Variable(rel_init)
# Embedding layer for each (head, rel, tail) triple being fed in as input
head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input)
tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input)
rel_embed = tf.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 = -tf.reduce_sum(tf.abs(diff_vec), 1)
elif self.dist == 'euclidean':
# +eps because gradients can misbehave for small values in sqrt
raw_output = -tf.sqrt(tf.reduce_sum(tf.square(diff_vec), 1) + self.EPS)
elif self.dist == 'sqeuclidean':
raw_output = -tf.reduce_sum(tf.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 = tf.unique(tf.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) | [
"tensorflow.scatter_update",
"tensorflow.concat",
"numpy.sqrt",
"tensorflow.reduce_sum",
"tensorflow.Graph",
"tensorflow.batch_matmul",
"tensorflow.Variable",
"tensorflow.initialize_all_variables",
"tensorflow.square",
"tensorflow.Session",
"tensorflow.train.AdagradOptimizer",
"tensorflow.truncated_normal",
"tensorflow.unique",
"tensorflow.placeholder",
"tensorflow.split",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.relu",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.assign",
"tensorflow.sigmoid",
"tensorflow.expand_dims",
"tensorflow.mul",
"tensorflow.log",
"tensorflow.abs"
] | tf_rl_tutorial/models.py | [(67, 'tensorflow.reshape', 'tf.reshape', (['output', '[-1, 2]'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.split', 'tf.split', (['(1)', '(2)', 'y_pairs'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.nn.relu', 'tf.nn.relu', (['(margin - pos_scores + neg_scores)'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['hinge_losses'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['var_matrix', 'indices'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.scatter_update', 'tf.scatter_update', (['var_matrix', 'indices', 'scaled'], {}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.assign', 'tf.assign', (['var_matrix', 'scaled'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.Variable', 'tf.Variable', (['[0.0]'], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.square', 'tf.square', (['(y - target)'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.Variable', 'tf.Variable', (['[0.0]'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.sigmoid', 'tf.sigmoid', (['y'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.maximum', 'tf.maximum', (['row_norms', 'maxnorm'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.expand_dims', 'tf.expand_dims', (['scaling', '(1)'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.maximum', 'tf.maximum', (['row_norms', 'maxnorm'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.expand_dims', 'tf.expand_dims', (['scaling', '(1)'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.maximum', 'tf.maximum', (['axis_norms', 'maxnorm'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.expand_dims', 'tf.expand_dims', (['scaling', '(1)'], {}), True, 'import tensorflow as tf\n'), (172, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[head_cnt, self.embedding_size]'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (327, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[rel_cnt, self.embedding_size]'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[tail_cnt, self.embedding_size]'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.Variable', 'tf.Variable', (['head_init'], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.Variable', 'tf.Variable', (['rel_init'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.Variable', 'tf.Variable', (['tail_init'], {}), True, 'import tensorflow as tf\n'), (338, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.head_embedding_vars', 'self.head_input'], {}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.rel_embedding_vars', 'self.rel_input'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.tail_embedding_vars', 'self.tail_input'], {}), True, 'import tensorflow as tf\n'), (431, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['entity_embedding_shape'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['rel_embedding_shape'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (437, 'tensorflow.Variable', 'tf.Variable', (['entity_init'], {}), True, 'import tensorflow as tf\n'), (438, 'tensorflow.Variable', 'tf.Variable', (['rel_init'], {}), True, 'import tensorflow as tf\n'), (440, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.entity_embedding_vars', 'self.head_input'], {}), True, 'import tensorflow as tf\n'), (441, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.entity_embedding_vars', 'self.tail_input'], {}), True, 'import tensorflow as tf\n'), (442, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.rel_embedding_vars', 'self.rel_input'], {}), True, 'import tensorflow as tf\n'), (444, 'tensorflow.reshape', 'tf.reshape', (['rel_embed', '(-1, self.embedding_size, self.embedding_size)'], {}), True, 'import tensorflow as tf\n'), (446, 'tensorflow.expand_dims', 'tf.expand_dims', (['head_embed', '(1)'], {}), True, 'import tensorflow as tf\n'), (447, 'tensorflow.expand_dims', 'tf.expand_dims', (['tail_embed', '(2)'], {}), True, 'import tensorflow as tf\n'), (448, 'tensorflow.batch_matmul', 'tf.batch_matmul', (['head_embed_row', 'rel_embed_square'], {}), True, 'import tensorflow as tf\n'), (517, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['entity_var_shape'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (518, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['rel_var_shape'], {'stddev': 'init_sd'}), True, 'import tensorflow as tf\n'), (521, 'tensorflow.Variable', 'tf.Variable', (['entity_init'], {}), True, 'import tensorflow as tf\n'), (522, 'tensorflow.Variable', 'tf.Variable', (['rel_init'], {}), True, 'import tensorflow as tf\n'), (524, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.entity_embedding_vars', 'self.head_input'], {}), True, 'import tensorflow as tf\n'), (525, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.entity_embedding_vars', 'self.tail_input'], {}), True, 'import tensorflow as tf\n'), (526, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.rel_embedding_vars', 'self.rel_input'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.square', 'tf.square', (['selected_rows'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.square', 'tf.square', (['var_matrix'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.square', 'tf.square', (['var_matrix'], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.train.AdagradOptimizer', 'tf.train.AdagradOptimizer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (324, 'numpy.sqrt', 'np.sqrt', (['self.embedding_size'], {}), True, 'import numpy as np\n'), (425, 'numpy.sqrt', 'np.sqrt', (['self.embedding_size'], {}), True, 'import numpy as np\n'), (450, 'tensorflow.batch_matmul', 'tf.batch_matmul', (['head_rel_mult', 'tail_embed_col'], {}), True, 'import tensorflow as tf\n'), (513, 'numpy.sqrt', 'np.sqrt', (['self.embedding_size'], {}), True, 'import numpy as np\n'), (266, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.mul', 'tf.mul', (['head_embed', 'rel_embed'], {}), True, 'import tensorflow as tf\n'), (458, 'tensorflow.unique', 'tf.unique', (['self.rel_input'], {}), True, 'import tensorflow as tf\n'), (543, 'tensorflow.concat', 'tf.concat', (['(0)', '[self.head_input, self.tail_input]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.log', 'tf.log', (['sig_y'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.log', 'tf.log', (['(1 - sig_y)'], {}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.unique', 'tf.unique', (['self.head_input'], {}), True, 'import tensorflow as tf\n'), (352, 'tensorflow.unique', 'tf.unique', (['self.rel_input'], {}), True, 'import tensorflow as tf\n'), (355, 'tensorflow.unique', 'tf.unique', (['self.tail_input'], {}), True, 'import tensorflow as tf\n'), (457, 'tensorflow.concat', 'tf.concat', (['(0)', '[self.head_input, self.tail_input]'], {}), True, 'import tensorflow as tf\n'), (531, 'tensorflow.abs', 'tf.abs', (['diff_vec'], {}), True, 'import tensorflow as tf\n'), (536, 'tensorflow.square', 'tf.square', (['diff_vec'], {}), True, 'import tensorflow as tf\n'), (534, 'tensorflow.square', 'tf.square', (['diff_vec'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
from i3d_cores.i3d import InceptionI3d
import os
os.environ['CUDA_VISIBLE_DEVICES'] = str(get_first_available_gpu())
with tf.Graph().as_default():
self.rgb_images_placeholder = tf.placeholder(dtype=tf.float32, shape=(None,
self.num_frame_per_clib,
self.frame_size_x,
self.frame_size_y,
self.rgb_channels))
is_training = False
with tf.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 = tf.global_variables_initializer()
config = tf.ConfigProto(log_device_placement=False)
if self.on_gpu:
config.gpu_options.allow_growth = True
self.sess = tf.Session(config=config)
self.sess.run(init)
checkpoint_file = self.model_dir
meta_graph_location = self.model_dir + '.meta'
saver = tf.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))
| [
"tensorflow.Graph",
"tensorflow.placeholder",
"tensorflow.train.import_meta_graph",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.variable_scope",
"numpy.array",
"numpy.zeros"
] | encoder/i3d/i3d_encoder.py | [(51, 'gnes.helper.get_first_available_gpu', 'get_first_available_gpu', ([], {}), False, 'from gnes.helper import batching, get_first_available_gpu\n'), (54, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, self.num_frame_per_clib, self.frame_size_x, self.frame_size_y, self.\n rgb_channels)'}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'log_device_placement': '(False)'}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (['meta_graph_location'], {'clear_devices': '(True)'}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""RGB"""'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (62, 'i3d_cores.i3d.InceptionI3d', 'InceptionI3d', ([], {'num_classes': 'self.num_classes', 'spatial_squeeze': '(True)', 'final_endpoint': 'self.output_layer', 'name': '"""inception_i3d"""'}), False, 'from i3d_cores.i3d import InceptionI3d\n'), (95, 'numpy.array', 'np.array', (['feature'], {}), True, 'import numpy as np\n'), (85, 'numpy.zeros', 'np.zeros', (['(self.num_frame_per_clib - d.shape[0], self.frame_size_x, self.frame_size_y,\n self.rgb_channels)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n')] |
jsdussanc/luminoth | dc1c1203a40e1ecf2aaca9647f3008ab72b41438 | import tensorflow as tf
def get_width_upright(bboxes):
with tf.name_scope('BoundingBoxTransform/get_width_upright'):
bboxes = tf.cast(bboxes, tf.float32)
x1, y1, x2, y2 = tf.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 tf.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 = tf.log(gt_boxes_width / bboxes_width) / variances[1]
targets_dh = tf.log(gt_boxes_height / bboxes_height) / variances[1]
targets = tf.concat(
[targets_dx, targets_dy, targets_dw, targets_dh], axis=1)
return targets
def decode(roi, deltas, variances=None):
with tf.name_scope('BoundingBoxTransform/decode'):
(roi_width, roi_height,
roi_urx, roi_ury) = get_width_upright(roi)
dx, dy, dw, dh = tf.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 = tf.exp(dw * variances[1]) * roi_width
pred_h = tf.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 = tf.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 tf.name_scope('BoundingBoxTransform/clip_bboxes'):
bboxes = tf.cast(bboxes, dtype=tf.float32)
imshape = tf.cast(imshape, dtype=tf.float32)
x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)
width = imshape[1]
height = imshape[0]
x1 = tf.maximum(tf.minimum(x1, width - 1.0), 0.0)
x2 = tf.maximum(tf.minimum(x2, width - 1.0), 0.0)
y1 = tf.maximum(tf.minimum(y1, height - 1.0), 0.0)
y2 = tf.maximum(tf.minimum(y2, height - 1.0), 0.0)
bboxes = tf.concat([x1, y1, x2, y2], axis=1)
return bboxes
def change_order(bboxes):
"""Change bounding box encoding order.
TensorFlow 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
TensorFlow'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 tf.name_scope('BoundingBoxTransform/change_order'):
first_min, second_min, first_max, second_max = tf.unstack(
bboxes, axis=1
)
bboxes = tf.stack(
[second_min, first_min, second_max, first_max], axis=1
)
return bboxes
if __name__ == '__main__':
import numpy as np
bboxes = tf.placeholder(tf.float32)
bboxes_val = [[10, 10, 20, 22]]
gt_boxes = tf.placeholder(tf.float32)
gt_boxes_val = [[11, 13, 34, 31]]
imshape = tf.placeholder(tf.int32)
imshape_val = (100, 100)
deltas = encode(bboxes, gt_boxes)
decoded_bboxes = decode(bboxes, deltas)
final_decoded_bboxes = clip_boxes(decoded_bboxes, imshape)
with tf.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)
| [
"tensorflow.concat",
"tensorflow.unstack",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.minimum",
"tensorflow.placeholder",
"tensorflow.exp",
"numpy.all",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.log",
"tensorflow.split"
] | luminoth/utils/bbox_transform_tf.py | [(132, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (5, 'tensorflow.name_scope', 'tf.name_scope', (['"""BoundingBoxTransform/get_width_upright"""'], {}), True, 'import tensorflow as tf\n'), (6, 'tensorflow.cast', 'tf.cast', (['bboxes', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (7, 'tensorflow.split', 'tf.split', (['bboxes', '(4)'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.name_scope', 'tf.name_scope', (['"""BoundingBoxTransform/encode"""'], {}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.concat', 'tf.concat', (['[targets_dx, targets_dy, targets_dw, targets_dh]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.name_scope', 'tf.name_scope', (['"""BoundingBoxTransform/decode"""'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.split', 'tf.split', (['deltas', '(4)'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.concat', 'tf.concat', (['[bbox_x1, bbox_y1, bbox_x2, bbox_y2]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.name_scope', 'tf.name_scope', (['"""BoundingBoxTransform/clip_bboxes"""'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.cast', 'tf.cast', (['bboxes'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.cast', 'tf.cast', (['imshape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.split', 'tf.split', (['bboxes', '(4)'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.concat', 'tf.concat', (['[x1, y1, x2, y2]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.name_scope', 'tf.name_scope', (['"""BoundingBoxTransform/change_order"""'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.unstack', 'tf.unstack', (['bboxes'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.stack', 'tf.stack', (['[second_min, first_min, second_max, first_max]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (152, 'numpy.all', 'np.all', (['(gt_boxes_val == final_decoded_bboxes)'], {}), True, 'import numpy as np\n'), (32, 'tensorflow.log', 'tf.log', (['(gt_boxes_width / bboxes_width)'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.log', 'tf.log', (['(gt_boxes_height / bboxes_height)'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.exp', 'tf.exp', (['(dw * variances[1])'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.exp', 'tf.exp', (['(dh * variances[1])'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.minimum', 'tf.minimum', (['x1', '(width - 1.0)'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.minimum', 'tf.minimum', (['x2', '(width - 1.0)'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.minimum', 'tf.minimum', (['y1', '(height - 1.0)'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.minimum', 'tf.minimum', (['y2', '(height - 1.0)'], {}), True, 'import tensorflow as tf\n')] |
harunpehlivan/tensorflow | d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f | # Copyright 2016 The TensorFlow 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 tf.Learn."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.contrib import framework
from tensorflow.contrib.factorization.python.ops import gmm_ops
from tensorflow.contrib.framework.python.framework import checkpoint_utils
from tensorflow.python.training import training_util
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import logging_ops as logging
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops.control_flow_ops import with_dependencies
from tensorflow.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.python.ops.math_ops.reduce_sum",
"tensorflow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps",
"tensorflow.python.ops.control_flow_ops.with_dependencies",
"tensorflow.python.training.training_util.get_global_step",
"numpy.squeeze",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.logging_ops.info",
"tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable",
"numpy.sum",
"tensorflow.python.framework.constant_op.constant"
] | tensorflow/contrib/factorization/python/ops/gmm.py | [(42, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['(0.0)'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (131, 'numpy.sum', 'np.sum', (['results[GMM.SCORES]'], {}), True, 'import numpy as np\n'), (135, 'tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', (['self.model_dir', 'gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT'], {}), False, 'from tensorflow.contrib.framework.python.framework import checkpoint_utils\n'), (140, 'tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', (['self.model_dir', 'gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE'], {}), False, 'from tensorflow.contrib.framework.python.framework import checkpoint_utils\n'), (142, 'numpy.squeeze', 'np.squeeze', (['clusters', '(1)'], {}), True, 'import numpy as np\n'), (146, 'tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', (['self.model_dir', 'gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE'], {}), False, 'from tensorflow.contrib.framework.python.framework import checkpoint_utils\n'), (56, 'tensorflow.python.framework.ops.get_default_graph', 'ops.get_default_graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (171, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['losses'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (172, 'tensorflow.python.ops.control_flow_ops.with_dependencies', 'with_dependencies', (['[training_op, incr_step]', 'loss'], {}), False, 'from tensorflow.python.ops.control_flow_ops import with_dependencies\n'), (182, 'tensorflow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps', 'model_fn_lib.ModelFnOps', ([], {'mode': 'mode', 'predictions': 'predictions', 'eval_metric_ops': 'eval_metric_ops', 'loss': 'loss', 'train_op': 'training_op', 'training_hooks': 'training_hooks'}), True, 'from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib\n'), (170, 'tensorflow.python.training.training_util.get_global_step', 'training_util.get_global_step', ([], {}), False, 'from tensorflow.python.training import training_util\n'), (67, 'tensorflow.python.ops.logging_ops.info', 'logging.info', (['e'], {}), True, 'from tensorflow.python.ops import logging_ops as logging\n'), (65, 'time.sleep', 'time.sleep', (['(1)'], {}), False, 'import time\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 tensorflow as tf
from settings import float_type
from quadrature import hermgauss
import numpy as np
def eye(N):
"""
An identitiy matrix
"""
return tf.diag(tf.ones(tf.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 = tf.shape(Fmu)
Fmu, Fvar = [tf.reshape(e, (-1, 1)) for e in (Fmu, Fvar)]
X = gh_x * tf.sqrt(2.0 * Fvar) + Fmu
logp = phi(X)
return tf.reshape(tf.matmul(logp, gh_w), shape)
import tensorflow as tf
def block_diagonal(matrices, dtype=tf.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 = [tf.convert_to_tensor(matrix, dtype=dtype) for matrix in matrices]
blocked_rows = tf.Dimension(0)
blocked_cols = tf.Dimension(0)
batch_shape = tf.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 = tf.shape(matrix)
ret_columns_list.append(matrix_shape[-1])
ret_columns = tf.add_n(ret_columns_list)
row_blocks = []
current_column = 0
for matrix in matrices:
matrix_shape = tf.shape(matrix)
row_before_length = current_column
current_column += matrix_shape[-1]
row_after_length = ret_columns - current_column
row_blocks.append(tf.pad(
tensor=matrix,
paddings=tf.concat(
[tf.zeros([tf.rank(matrix) - 1, 2], dtype=tf.int32),
[(row_before_length, row_after_length)]],
axis=0)))
blocked = tf.concat(row_blocks, -2)
blocked.set_shape(batch_shape.concatenate((blocked_rows, blocked_cols)))
return blocked | [
"tensorflow.convert_to_tensor",
"tensorflow.TensorShape",
"tensorflow.matmul",
"tensorflow.concat",
"numpy.sqrt",
"tensorflow.shape",
"tensorflow.Dimension",
"tensorflow.stack",
"tensorflow.reshape",
"tensorflow.rank",
"tensorflow.sqrt",
"tensorflow.add_n"
] | SVGPs/functions.py | [(43, 'quadrature.hermgauss', 'hermgauss', (['num_gauss_hermite_points'], {}), False, 'from quadrature import hermgauss\n'), (46, 'tensorflow.shape', 'tf.shape', (['Fmu'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.Dimension', 'tf.Dimension', (['(0)'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.Dimension', 'tf.Dimension', (['(0)'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.add_n', 'tf.add_n', (['ret_columns_list'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.concat', 'tf.concat', (['row_blocks', '(-2)'], {}), True, 'import tensorflow as tf\n'), (45, 'numpy.sqrt', 'np.sqrt', (['np.pi'], {}), True, 'import numpy as np\n'), (47, 'tensorflow.reshape', 'tf.reshape', (['e', '(-1, 1)'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.matmul', 'tf.matmul', (['logp', 'gh_w'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['matrix'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.shape', 'tf.shape', (['matrix'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.shape', 'tf.shape', (['matrix'], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.stack', 'tf.stack', (['[N]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.sqrt', 'tf.sqrt', (['(2.0 * Fvar)'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.rank', 'tf.rank', (['matrix'], {}), True, 'import tensorflow as tf\n')] |
Holmeswww/Text_Infilling | f63cd24bee5c62d7dedd8fb35c4e52aee20c39f3 | #
"""
Adversarial losses.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
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 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
logits=real_logits, labels=tf.ones_like(real_logits)))
fake_logits = discriminator_fn(fake_data)
if isinstance(fake_logits, (list, tuple)):
fake_logits = fake_logits[0]
fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
logits=fake_logits, labels=tf.zeros_like(fake_logits)))
d_loss = real_loss + fake_loss
if mode == "min_fake":
g_loss = - fake_loss
elif mode == "max_real":
g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
logits=fake_logits, labels=tf.ones_like(fake_logits)))
else:
raise ValueError("Unknown mode: %s. Only 'min_fake' and 'max_real' "
"are allowed.")
return g_loss, d_loss
| [
"tensorflow.zeros_like",
"tensorflow.ones_like"
] | texar/losses/adv_losses.py | [(44, 'tensorflow.ones_like', 'tf.ones_like', (['real_logits'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.zeros_like', 'tf.zeros_like', (['fake_logits'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.ones_like', 'tf.ones_like', (['fake_logits'], {}), True, 'import tensorflow as tf\n')] |
sweetpand/tensorflow_mri | 7a483cbbbe515ad395928311759505707bd72503 | import sonnet as snt
import tensorflow as tf
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 = tf.nn.relu
self._embedding_initializers = {
'embeddings': tf.truncated_normal_initializer(stddev=0.01),
}
self._embedding_regularizers = {}
self._initializers = {
"w": tf.contrib.layers.xavier_initializer(),
}
self._regularizers = {
'w': tf.contrib.layers.l2_regularizer(config.l2)
}
self._construct_placeholders()
self._construct_weights()
self._construct()
tf.summary.scalar('Model/Loss', tf.get_collection(GraphKeys.LOSSES)[0])
self.summary = tf.summary.merge_all()
def _construct(self):
"""
Construct the model; main part of it goes here
"""
self.v = DenseLayer(1, False, tf.nn.relu, initializers=self._initializers,
regularizers=self._regularizers, name='OutputVector')
self.score = tf.squeeze(self.v(self._cur_user * self._cur_item))
negative_output = tf.squeeze(self.v(self._cur_user * self._cur_item_negative))
tf.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 = tf.placeholder(tf.int32, [None], 'UserID')
self.input_items = tf.placeholder(tf.int32, [None], 'ItemID')
self.input_items_negative = tf.placeholder(tf.int32, [None], 'NegativeItemID')
# Add our placeholders
add_to_collection(GraphKeys.PLACEHOLDER, [self.input_users,
self.input_items,
self.input_items_negative])
| [
"tensorflow.get_collection",
"tensorflow.placeholder",
"tensorflow.truncated_normal_initializer",
"tensorflow.summary.merge_all",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.add_to_collection"
] | recommendation_system_demos/Basic-CMN-Demo/util/gmf.py | [(35, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (42, 'util.layers.DenseLayer', 'DenseLayer', (['(1)', '(False)', 'tf.nn.relu'], {'initializers': 'self._initializers', 'regularizers': 'self._regularizers', 'name': '"""OutputVector"""'}), False, 'from util.layers import DenseLayer, LossLayer, OptimizerLayer, ModelBase\n'), (46, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['GraphKeys.PREDICTION', 'self.score'], {}), True, 'import tensorflow as tf\n'), (48, 'util.layers.OptimizerLayer', 'OptimizerLayer', (['self.config.optimizer'], {'clip': '(5.0)', 'params': '{}'}), False, 'from util.layers import DenseLayer, LossLayer, OptimizerLayer, ModelBase\n'), (57, 'sonnet.Embed', 'snt.Embed', (['self.config.user_count', 'self.config.embed_size'], {'initializers': 'self._embedding_initializers', 'regularizers': 'self._embedding_regularizers', 'name': '"""MemoryEmbed"""'}), True, 'import sonnet as snt\n'), (62, 'sonnet.Embed', 'snt.Embed', (['self.config.item_count', 'self.config.embed_size'], {'initializers': 'self._embedding_initializers', 'regularizers': 'self._embedding_regularizers', 'name': '"""ItemMemory"""'}), True, 'import sonnet as snt\n'), (76, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]', '"""UserID"""'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]', '"""ItemID"""'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]', '"""NegativeItemID"""'], {}), True, 'import tensorflow as tf\n'), (81, 'util.helper.add_to_collection', 'add_to_collection', (['GraphKeys.PLACEHOLDER', '[self.input_users, self.input_items, self.input_items_negative]'], {}), False, 'from util.helper import GraphKeys, add_to_collection\n'), (18, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.01)'}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['config.l2'], {}), True, 'import tensorflow as tf\n'), (47, 'util.layers.LossLayer', 'LossLayer', ([], {}), False, 'from util.layers import DenseLayer, LossLayer, OptimizerLayer, ModelBase\n'), (34, 'tensorflow.get_collection', 'tf.get_collection', (['GraphKeys.LOSSES'], {}), True, 'import tensorflow as tf\n')] |
sweetpand/tensorflow_mri | 7a483cbbbe515ad395928311759505707bd72503 | import tensorflow as tf
from tensorflow.python.ops.rnn_cell import *
from tensorflow.python.ops.rnn_cell_impl import _Linear
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import array_ops
from tensorflow.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 tf.variable_scope(name_or_scope=scope, default_name="prelu"):
_alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1],
dtype=_x.dtype, initializer=tf.constant_initializer(0.1))
return tf.maximum(0.0, _x) + _alpha * tf.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 = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.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 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1))
w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1))
b = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
with tf.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 = tf.tensordot(facts, w1, axes=1)
tmp2 = tf.tensordot(query, w2, axes=1)
tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]])
tmp = tf.tanh((tmp1 + tmp2) + b)
# For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector
v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape
key_masks = mask # [B, 1, T]
# key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1)
v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T]
alphas = tf.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 = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1)
output = facts * tf.expand_dims(alphas, -1)
output = tf.reshape(output, tf.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 = tf.concat(facts, 2)
print ("querry_size mismatch")
query = tf.concat(values = [
query,
query,
], axis=1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
mask = tf.equal(mask, tf.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 = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.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 = tf.concat(facts, 2)
if len(facts.get_shape().as_list()) == 2:
facts = tf.expand_dims(facts, 1)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.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 = tf.layers.dense(query, facts_size, activation=None, name='f1' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag)
d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]])
scores = d_layer_3_all
# Mask
# key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
key_masks = tf.expand_dims(mask, 1) # [B, 1, T]
paddings = tf.ones_like(scores) * (-2 ** 32 + 1)
if not forCnn:
scores = tf.where(key_masks, scores, paddings) # [B, 1, T]
# Scale
# scores = scores / (facts.get_shape().as_list()[-1] ** 0.5)
# Activation
if softmax_stag:
scores = tf.nn.softmax(scores) # [B, 1, T]
# Weighted sum
if mode == 'SUM':
output = tf.matmul(scores, facts) # [B, 1, H]
# output = tf.reshape(output, [-1, tf.shape(facts)[-1]])
else:
scores = tf.reshape(scores, [-1, tf.shape(facts)[1]])
output = facts * tf.expand_dims(scores, -1)
output = tf.reshape(output, tf.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 = tf.expand_dims(facts, 1)
def cond(batch, output, i):
return tf.less(i, tf.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 = tf.reduce_sum(self_attention_tmp, 1)
output = output.write(i, self_attention_tmp)
return batch, output, i + 1
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.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 = tf.expand_dims(facts, 1)
def cond(batch, output, i):
return tf.less(i, tf.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 = tf.reduce_sum(self_attention_tmp, 1)
output = output.write(i, self_attention_tmp)
return batch, output, i + 1
output_ta = tf.TensorArray(dtype=tf.float32,
size=0,
dynamic_size=True,
element_shape=(facts[:, 0, :].get_shape()))
_, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0])
self_attention = output_op.stack()
self_attention = tf.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 = tf.concat(facts, 2)
if time_major:
# (T,B,D) => (B,T,D)
facts = tf.array_ops.transpose(facts, [1, 0, 2])
# Trainable parameters
mask = tf.equal(mask, tf.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 = tf.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag)
query = prelu(query)
queries = tf.tile(query, [1, tf.shape(facts)[1]])
queries = tf.reshape(queries, tf.shape(facts))
din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1)
d_layer_1_all = tf.layers.dense(din_all, facts_size, activation=tf.nn.sigmoid, name='f1_shine_att' + stag)
d_layer_2_all = tf.layers.dense(d_layer_1_all, facts_size, activation=tf.nn.sigmoid, name='f2_shine_att' + stag)
d_layer_2_all = tf.reshape(d_layer_2_all, tf.shape(facts))
output = d_layer_2_all
return output
| [
"tensorflow.concat",
"tensorflow.python.ops.array_ops.split",
"tensorflow.reduce_sum",
"tensorflow.minimum",
"tensorflow.tanh",
"tensorflow.where",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.ops.rnn_cell_impl._Linear",
"tensorflow.while_loop",
"tensorflow.layers.dense",
"tensorflow.name_scope",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.tensordot",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.maximum",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.array_ops.transpose",
"tensorflow.random_normal"
] | recommendation_system_demos/Basic-DIEN-Demo/source_code/utils.py | [(217, 'tensorflow.tensordot', 'tf.tensordot', (['tmp', 'v'], {'axes': '(1)', 'name': '"""v_dot_tmp"""'}), True, 'import tensorflow as tf\n'), (221, 'tensorflow.where', 'tf.where', (['key_masks', 'v_dot_tmp', 'paddings'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['v_dot_tmp'], {'name': '"""alphas"""'}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', '(80)'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_att' + stag)"}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', '(40)'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_att' + stag)"}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_2_all', '(1)'], {'activation': 'None', 'name': "('f3_att' + stag)"}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask', '(1)'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.where', 'tf.where', (['key_masks', 'scores', 'paddings'], {}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.layers.dense', 'tf.layers.dense', (['query', 'facts_size'], {'activation': 'None', 'name': "('f1' + stag)"}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', '(80)'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_att' + stag)"}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', '(40)'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_att' + stag)"}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_2_all', '(1)'], {'activation': 'None', 'name': "('f3_att' + stag)"}), True, 'import tensorflow as tf\n'), (307, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask', '(1)'], {}), True, 'import tensorflow as tf\n'), (350, 'tensorflow.while_loop', 'tf.while_loop', (['cond', 'body', '[facts, output_ta, 0]'], {}), True, 'import tensorflow as tf\n'), (352, 'tensorflow.transpose', 'tf.transpose', (['self_attention'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (374, 'tensorflow.while_loop', 'tf.while_loop', (['cond', 'body', '[facts, output_ta, 0]'], {}), True, 'import tensorflow as tf\n'), (376, 'tensorflow.transpose', 'tf.transpose', (['self_attention'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (391, 'tensorflow.layers.dense', 'tf.layers.dense', (['query', 'facts_size'], {'activation': 'None', 'name': "('f1_trans_shine' + stag)"}), True, 'import tensorflow as tf\n'), (395, 'tensorflow.concat', 'tf.concat', (['[queries, facts, queries - facts, queries * facts]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (396, 'tensorflow.layers.dense', 'tf.layers.dense', (['din_all', 'facts_size'], {'activation': 'tf.nn.sigmoid', 'name': "('f1_shine_att' + stag)"}), True, 'import tensorflow as tf\n'), (397, 'tensorflow.layers.dense', 'tf.layers.dense', (['d_layer_1_all', 'facts_size'], {'activation': 'tf.nn.sigmoid', 'name': "('f2_shine_att' + stag)"}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.python.ops.array_ops.split', 'array_ops.split', ([], {'value': 'value', 'num_or_size_splits': '(2)', 'axis': '(1)'}), False, 'from tensorflow.python.ops import array_ops\n'), (130, 'tensorflow.python.ops.array_ops.split', 'array_ops.split', ([], {'value': 'value', 'num_or_size_splits': '(2)', 'axis': '(1)'}), False, 'from tensorflow.python.ops import array_ops\n'), (148, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'scope', 'default_name': '"""prelu"""'}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (198, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.random_normal', 'tf.random_normal', (['[hidden_size, attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.random_normal', 'tf.random_normal', (['[input_size, attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.random_normal', 'tf.random_normal', (['[attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.random_normal', 'tf.random_normal', (['[attention_size]'], {'stddev': '(0.1)'}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.name_scope', 'tf.name_scope', (['"""v"""'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.tensordot', 'tf.tensordot', (['facts', 'w1'], {'axes': '(1)'}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.tensordot', 'tf.tensordot', (['query', 'w2'], {'axes': '(1)'}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.tanh', 'tf.tanh', (['(tmp1 + tmp2 + b)'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.ones_like', 'tf.ones_like', (['v_dot_tmp'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.expand_dims', 'tf.expand_dims', (['alphas', '(-1)'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.concat', 'tf.concat', ([], {'values': '[query, query]', 'axis': '(1)'}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (247, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.ones_like', 'tf.ones_like', (['scores'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scores'], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.matmul', 'tf.matmul', (['scores', 'facts'], {}), True, 'import tensorflow as tf\n'), (284, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (298, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (308, 'tensorflow.ones_like', 'tf.ones_like', (['scores'], {}), True, 'import tensorflow as tf\n'), (310, 'tensorflow.where', 'tf.where', (['key_masks', 'scores', 'paddings'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['scores'], {}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.matmul', 'tf.matmul', (['scores', 'facts'], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self_attention_tmp', '(1)'], {}), True, 'import tensorflow as tf\n'), (357, 'tensorflow.expand_dims', 'tf.expand_dims', (['facts', '(1)'], {}), True, 'import tensorflow as tf\n'), (366, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self_attention_tmp', '(1)'], {}), True, 'import tensorflow as tf\n'), (382, 'tensorflow.concat', 'tf.concat', (['facts', '(2)'], {}), True, 'import tensorflow as tf\n'), (386, 'tensorflow.array_ops.transpose', 'tf.array_ops.transpose', (['facts', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (388, 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), True, 'import tensorflow as tf\n'), (394, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (398, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.maximum', 'tf.maximum', (['(0.0)', '_x'], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.expand_dims', 'tf.expand_dims', (['scores', '(-1)'], {}), True, 'import tensorflow as tf\n'), (278, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (325, 'tensorflow.expand_dims', 'tf.expand_dims', (['scores', '(-1)'], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', (['(1.0)'], {'dtype': 'inputs.dtype'}), False, 'from tensorflow.python.ops import init_ops\n'), (55, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""gates"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (56, 'tensorflow.python.ops.rnn_cell_impl._Linear', '_Linear', (['[inputs, state]', '(2 * self._num_units)', '(True)'], {'bias_initializer': 'bias_ones', 'kernel_initializer': 'self._kernel_initializer'}), False, 'from tensorflow.python.ops.rnn_cell_impl import _Linear\n'), (68, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""candidate"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (69, 'tensorflow.python.ops.rnn_cell_impl._Linear', '_Linear', (['[inputs, r_state]', 'self._num_units', '(True)'], {'bias_initializer': 'self._bias_initializer', 'kernel_initializer': 'self._kernel_initializer'}), False, 'from tensorflow.python.ops.rnn_cell_impl import _Linear\n'), (120, 'tensorflow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', (['(1.0)'], {'dtype': 'inputs.dtype'}), False, 'from tensorflow.python.ops import init_ops\n'), (121, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""gates"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (122, 'tensorflow.python.ops.rnn_cell_impl._Linear', '_Linear', (['[inputs, state]', '(2 * self._num_units)', '(True)'], {'bias_initializer': 'bias_ones', 'kernel_initializer': 'self._kernel_initializer'}), False, 'from tensorflow.python.ops.rnn_cell_impl import _Linear\n'), (134, 'tensorflow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', (['"""candidate"""'], {}), True, 'from tensorflow.python.ops import variable_scope as vs\n'), (135, 'tensorflow.python.ops.rnn_cell_impl._Linear', '_Linear', (['[inputs, r_state]', 'self._num_units', '(True)'], {'bias_initializer': 'self._bias_initializer', 'kernel_initializer': 'self._kernel_initializer'}), False, 'from tensorflow.python.ops.rnn_cell_impl import _Linear\n'), (150, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.1)'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.minimum', 'tf.minimum', (['(0.0)', '_x'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (297, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (303, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.shape', 'tf.shape', (['batch'], {}), True, 'import tensorflow as tf\n'), (360, 'tensorflow.shape', 'tf.shape', (['batch'], {}), True, 'import tensorflow as tf\n'), (393, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.shape', 'tf.shape', (['tmp2'], {}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n'), (324, 'tensorflow.shape', 'tf.shape', (['facts'], {}), True, 'import tensorflow as tf\n')] |
mikimaus78/ml_monorepo | b2c2627ff0e86e27f6829170d0dac168d8e5783b | import tensorflow as tf
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 tf.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 = tf.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 * tf.nn.tanh(1. / scale * x)
bs, sl, vec = tf.shape(rep_tensor)[0], tf.shape(rep_tensor)[1], tf.shape(rep_tensor)[2]
ivec = hn or rep_tensor.get_shape().as_list()[2]
input_dim = rep_tensor.get_shape().as_list()[2]
with tf.variable_scope(scope or 'block_simple'):
# @1. split sequence
with tf.variable_scope('split_seq'):
block_num = tf.cast(tf.ceil(tf.divide(tf.cast(sl, tf.float32), tf.cast(block_len, tf.float32))), tf.int32)
comp_len = block_num * block_len - sl
rep_tensor_comp = tf.concat([rep_tensor, tf.zeros([bs, comp_len, input_dim], tf.float32)], 1)
rep_mask_comp = tf.concat([rep_mask, tf.cast(tf.zeros([bs, comp_len], tf.int32), tf.bool)], 1)
rep_tensor_split = tf.reshape(rep_tensor_comp, [bs, block_num, block_len, input_dim]) # bs,bn,bl,d
rep_mask_split = tf.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 = tf.tile(tf.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 tf.variable_scope('self_attention'):
# @2.self-attention in block
# mask generation
sl_indices = tf.range(block_len, dtype=tf.int32)
sl_col, sl_row = tf.meshgrid(sl_indices, sl_indices)
if direction == 'forward':
direct_mask = tf.greater(sl_row, sl_col) # bl,bl
else:
direct_mask = tf.greater(sl_col, sl_row) # bl,bl
direct_mask_tile = tf.tile(
tf.expand_dims(tf.expand_dims(direct_mask, 0), 0), [bs, bn, 1, 1]) # bs,bn,bl,bl
rep_mask_tile_1 = tf.tile(tf.expand_dims(rep_mask_split, 2), [1, 1, bl, 1]) # bs,bn,bl,bl
rep_mask_tile_2 = tf.tile(tf.expand_dims(rep_mask_split, 3), [1, 1, 1, bl]) # bs,bn,bl,bl
rep_mask_tile = tf.logical_and(rep_mask_tile_1, rep_mask_tile_2)
attn_mask = tf.logical_and(direct_mask_tile, rep_mask_tile, name='attn_mask') # bs,bn,bl,bl
# attention
f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.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 = tf.split(dependent_head, 2, 3)
dependent_etd = tf.expand_dims(dependent, 2) # bs,bn,1,bl,vec
head_etd = tf.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 = tf.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 = tf.reduce_sum(attn_score * rep_map_tile, 3) # bs,bn,bl,vec
with tf.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 = tf.nn.softmax(inter_block_logits_masked, 2) # bs,bn,bl,vec
inter_block_attn_output = tf.reduce_sum(self_attn_result * inter_block_soft, 2) # bs,bn,vec
with tf.variable_scope('self_attn_inter_block'):
inter_block_attn_output_mask = tf.cast(tf.ones([bs, bn], tf.int32), tf.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 = tf.tile(tf.expand_dims(block_ct_res, 2), [1, 1, bl, 1])#[bs,bn,vec]->[bs,bn,bl,vec]
with tf.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 = tf.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 = tf.split(new_context_and_gate, 2, 3) # bs,bn,bl,vec
if activation == "relu":
new_context_act = tf.nn.relu(new_context)
elif activation == "elu":
new_context_act = tf.nn.elu(new_context)
elif activation == "linear":
new_context_act = tf.identity(new_context)
else:
raise RuntimeError
gate_sig = tf.nn.sigmoid(gate)
combination_res = gate_sig * new_context_act + (1 - gate_sig) * rep_map # bs,bn,bl,vec
with tf.variable_scope('restore_original_length'):
combination_res_reshape = tf.reshape(combination_res, [bs, bn * bl, ivec]) # bs,bn*bl,vec
output = combination_res_reshape[:, :sl, :]
return output | [
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.greater",
"tensorflow.nn.elu",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"tensorflow.identity",
"tensorflow.nn.tanh",
"tensorflow.meshgrid",
"tensorflow.split",
"tensorflow.nn.relu",
"tensorflow.nn.softmax",
"tensorflow.range",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.ones",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.logical_and"
] | BiBloSA/exp_SQuAD_sim/src/nn_utils/baselines/block_attention.py | [(11, 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'bi_directional_simple_block_attn')"], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.concat', 'tf.concat', (['[fw_attn_res, bw_attn_res]', '(-1)'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'block_simple')"], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.nn.tanh', 'tf.nn.tanh', (['(1.0 / scale * x)'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.shape', 'tf.shape', (['rep_tensor'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.shape', 'tf.shape', (['rep_tensor'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.shape', 'tf.shape', (['rep_tensor'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""split_seq"""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.reshape', 'tf.reshape', (['rep_tensor_comp', '[bs, block_num, block_len, input_dim]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.reshape', 'tf.reshape', (['rep_mask_comp', '[bs, block_num, block_len]'], {}), True, 'import tensorflow as tf\n'), (47, 'src.nn_utils.nn.bn_dense_layer', 'bn_dense_layer', (['rep_tensor_split', 'ivec', '(True)', '(0.0)', '"""bn_dense_map"""', 'activation', '(False)', 'wd', 'keep_prob', 'is_train'], {}), False, 'from src.nn_utils.nn import bn_dense_layer, linear\n'), (54, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""self_attention"""'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.range', 'tf.range', (['block_len'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.meshgrid', 'tf.meshgrid', (['sl_indices', 'sl_indices'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.logical_and', 'tf.logical_and', (['rep_mask_tile_1', 'rep_mask_tile_2'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.logical_and', 'tf.logical_and', (['direct_mask_tile', 'rep_mask_tile'], {'name': '"""attn_mask"""'}), True, 'import tensorflow as tf\n'), (72, 'src.nn_utils.nn.linear', 'linear', (['rep_map', '(2 * ivec)', '(False)', '(0.0)', '"""linear_dependent_head"""', '(False)', 'wd', 'keep_prob', 'is_train'], {}), False, 'from src.nn_utils.nn import bn_dense_layer, linear\n'), (74, 'tensorflow.split', 'tf.split', (['dependent_head', '(2)', '(3)'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.expand_dims', 'tf.expand_dims', (['dependent', '(2)'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.expand_dims', 'tf.expand_dims', (['head', '(3)'], {}), True, 'import tensorflow as tf\n'), (78, 'src.nn_utils.general.exp_mask_for_high_rank', 'exp_mask_for_high_rank', (['logits', 'attn_mask'], {}), False, 'from src.nn_utils.general import exp_mask_for_high_rank, mask_for_high_rank\n'), (79, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits_masked', '(3)'], {}), True, 'import tensorflow as tf\n'), (80, 'src.nn_utils.general.mask_for_high_rank', 'mask_for_high_rank', (['attn_score', 'attn_mask'], {}), False, 'from src.nn_utils.general import exp_mask_for_high_rank, mask_for_high_rank\n'), (81, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(attn_score * rep_map_tile)', '(3)'], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""source2token_self_attn"""'], {}), True, 'import tensorflow as tf\n'), (84, 'src.nn_utils.nn.bn_dense_layer', 'bn_dense_layer', (['self_attn_result', 'ivec', '(True)', '(0.0)', '"""bn_dense_map"""', '"""linear"""', '(False)', 'wd', 'keep_prob', 'is_train'], {}), False, 'from src.nn_utils.nn import bn_dense_layer, linear\n'), (86, 'src.nn_utils.general.exp_mask_for_high_rank', 'exp_mask_for_high_rank', (['inter_block_logits', 'rep_mask_split'], {}), False, 'from src.nn_utils.general import exp_mask_for_high_rank, mask_for_high_rank\n'), (87, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['inter_block_logits_masked', '(2)'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(self_attn_result * inter_block_soft)', '(2)'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""self_attn_inter_block"""'], {}), True, 'import tensorflow as tf\n'), (92, 'src.nn_utils.integration_func.directional_attention_with_dense', 'directional_attention_with_dense', (['inter_block_attn_output', 'inter_block_attn_output_mask', 'direction', '"""disa"""', 'keep_prob', 'is_train', 'wd', 'activation'], {}), False, 'from src.nn_utils.integration_func import directional_attention_with_dense\n'), (99, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""combination"""'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.concat', 'tf.concat', (['[rep_map, self_attn_result, block_ct_res_tile]', '(-1)'], {}), True, 'import tensorflow as tf\n'), (102, 'src.nn_utils.nn.linear', 'linear', (['rep_tensor_with_ct', '(2 * ivec)', '(True)', '(0.0)', '"""linear_new_context_and_gate"""', '(False)', 'wd', 'keep_prob', 'is_train'], {}), False, 'from src.nn_utils.nn import bn_dense_layer, linear\n'), (104, 'tensorflow.split', 'tf.split', (['new_context_and_gate', '(2)', '(3)'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['gate'], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""restore_original_length"""'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.reshape', 'tf.reshape', (['combination_res', '[bs, bn * bl, ivec]'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.expand_dims', 'tf.expand_dims', (['rep_map', '(2)'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.greater', 'tf.greater', (['sl_row', 'sl_col'], {}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.greater', 'tf.greater', (['sl_col', 'sl_row'], {}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.expand_dims', 'tf.expand_dims', (['rep_mask_split', '(2)'], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.expand_dims', 'tf.expand_dims', (['rep_mask_split', '(3)'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.ones', 'tf.ones', (['[bs, bn]', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.expand_dims', 'tf.expand_dims', (['block_ct_res', '(2)'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.nn.relu', 'tf.nn.relu', (['new_context'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.zeros', 'tf.zeros', (['[bs, comp_len, input_dim]', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.expand_dims', 'tf.expand_dims', (['direct_mask', '(0)'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.nn.elu', 'tf.nn.elu', (['new_context'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.cast', 'tf.cast', (['sl', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.cast', 'tf.cast', (['block_len', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.zeros', 'tf.zeros', (['[bs, comp_len]', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.identity', 'tf.identity', (['new_context'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
from tqdm import trange
from .ops import gmf, loss_fn, train_fn
np.random.seed(self.seed)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
graph = tf.Graph()
with graph.as_default():
tf.set_random_seed(self.seed)
self.user_id = tf.placeholder(shape=[None, ], dtype=tf.int32, name='user_id')
self.item_id = tf.placeholder(shape=[None, ], dtype=tf.int32, name='item_id')
self.labels = tf.placeholder(shape=[None, 1], dtype=tf.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 = tf.layers.dense(self.interaction, units=1, name='logits',
kernel_initializer=tf.initializers.lecun_uniform(self.seed))
self.prediction = tf.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 = tf.global_variables_initializer()
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf.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()
| [
"tensorflow.Graph",
"tensorflow.nn.sigmoid",
"numpy.random.seed",
"numpy.arange",
"tensorflow.placeholder",
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.initializers.lecun_uniform",
"tensorflow.Session",
"tensorflow.set_random_seed"
] | cornac/models/ncf/recom_gmf.py | [(117, 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), True, 'import numpy as np\n'), (119, 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.ERROR'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph', 'config': 'config'}), True, 'import tensorflow as tf\n'), (147, 'tqdm.trange', 'trange', (['self.num_epochs'], {'disable': '(not self.verbose)'}), False, 'from tqdm import trange\n'), (123, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None]', 'dtype': 'tf.int32', 'name': '"""user_id"""'}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None]', 'dtype': 'tf.int32', 'name': '"""item_id"""'}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[None, 1]', 'dtype': 'tf.float32', 'name': '"""labels"""'}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['logits'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.initializers.lecun_uniform', 'tf.initializers.lecun_uniform', (['self.seed'], {}), True, 'import tensorflow as tf\n'), (208, 'numpy.arange', 'np.arange', (['self.train_set.num_items'], {}), True, 'import numpy as np\n')] |
EdwardFerdian/4DFlowNet | e9c8bf72660b41ef5c7b6c677a71283ead32bbab | import tensorflow as tf
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 = tf.keras.layers.concatenate([u,v,w])
pc = tf.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 = tf.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 = tf.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 TF '``'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 = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx')
resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align)
resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx')
# Reorient
reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4])
# squeeze and 2d resize
squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz')
resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align)
resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz')
output_tensor = tf.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-Tensorflow/blob/master/ops.py
For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad
"""
reg_l2 = tf.keras.regularizers.l2(5e-7)
if padding == 'SYMMETRIC' or padding == 'REFLECT':
p = (kernel_size - 1) // 2
x = tf.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding)
x = tf.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 = tf.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 = tf.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 = tf.keras.layers.LeakyReLU(alpha=0.2)(tmp)
return tmp
| [
"tensorflow.transpose",
"tensorflow.keras.layers.LeakyReLU",
"tensorflow.keras.regularizers.l2",
"tensorflow.reshape",
"tensorflow.keras.layers.Conv3D",
"tensorflow.keras.layers.concatenate",
"tensorflow.compat.v1.image.resize_bilinear",
"tensorflow.pad"
] | src/Network/SR4DFlowNet.py | [(77, 'tensorflow.reshape', 'tf.reshape', (['input_tensor', '[-1, y_size, z_size, c_size]'], {'name': '"""reshape_bx"""'}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.compat.v1.image.resize_bilinear', 'tf.compat.v1.image.resize_bilinear', (['squeeze_b_x', '[y_size_new, z_size_new]'], {'align_corners': 'align'}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.reshape', 'tf.reshape', (['resize_b_x', '[-1, x_size, y_size_new, z_size_new, c_size]'], {'name': '"""resume_bx"""'}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.transpose', 'tf.transpose', (['resume_b_x', '[0, 3, 2, 1, 4]'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.reshape', 'tf.reshape', (['reoriented', '[-1, y_size_new, x_size, c_size]'], {'name': '"""reshape_bz"""'}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.compat.v1.image.resize_bilinear', 'tf.compat.v1.image.resize_bilinear', (['squeeze_b_z', '[y_size_new, x_size_new]'], {'align_corners': 'align'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.reshape', 'tf.reshape', (['resize_b_z', '[-1, z_size_new, y_size_new, x_size_new, c_size]'], {'name': '"""resume_bz"""'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.transpose', 'tf.transpose', (['resume_b_z', '[0, 3, 2, 1, 4]'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.keras.regularizers.l2', 'tf.keras.regularizers.l2', (['(5e-07)'], {}), True, 'import tensorflow as tf\n'), (14, 'tensorflow.keras.layers.concatenate', 'tf.keras.layers.concatenate', (['[u, v, w]'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.keras.layers.concatenate', 'tf.keras.layers.concatenate', (['[pcmr, mag, speed]'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.keras.layers.concatenate', 'tf.keras.layers.concatenate', (['[phase, pc]'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.keras.layers.concatenate', 'tf.keras.layers.concatenate', (['[u_path, v_path, w_path]'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.pad', 'tf.pad', (['x', '[[0, 0], [p, p], [p, p], [p, p], [0, 0]]', 'padding'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {'alpha': '(0.2)'}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {'alpha': '(0.2)'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.keras.layers.Conv3D', 'tf.keras.layers.Conv3D', (['filters', 'kernel_size'], {'activation': 'activation', 'kernel_initializer': 'initialization', 'use_bias': 'use_bias', 'kernel_regularizer': 'reg_l2'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.keras.layers.Conv3D', 'tf.keras.layers.Conv3D', (['filters', 'kernel_size'], {'activation': 'activation', 'kernel_initializer': 'initialization', 'use_bias': 'use_bias', 'kernel_regularizer': 'reg_l2'}), True, 'import tensorflow as tf\n')] |
yyht/bert | 480c909e0835a455606e829310ff949c9dd23549 | try:
from .model_interface import model_zoo
except:
from model_interface import model_zoo
import tensorflow as tf
import numpy as np
from bunch import Bunch
from model_io import model_io
from task_module import classifier
import tensorflow as tf
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 - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
x = tf.nn.l2_normalize(x, -1)
y = tf.nn.l2_normalize(y, -1)
return -tf.reduce_sum(x*y, axis=-1) # higher the better
def kd(x, y):
x_prob = tf.nn.softmax(x)
print(x_prob.get_shape(), y.get_shape(), tf.reduce_sum(x_prob * y, axis=-1).get_shape())
return -tf.reduce_sum(x_prob * y, axis=-1) # higher the better
def mse(x, y):
x = x - tf.reduce_mean(x, axis=-1, keepdims=True)
y = y - tf.reduce_mean(y, axis=-1, keepdims=True)
return tf.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 == tf.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 tf.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 = tf.reduce_sum(per_example_loss * features["label_ratio"]) / (1e-10+tf.reduce_sum(features["label_ratio"]))
tf.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 == tf.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 = tf.log(features["label_probs"]+1e-10)/kargs.get("temperature", 2.0) # log_softmax logits
student_logit = tf.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":tf.ones_like(label_ids, dtype=tf.int32),
"teacher_label":tf.zeros_like(label_ids, dtype=tf.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 == tf.estimator.ModeKeys.TRAIN:
optimizer_fn = optimizer.Optimizer(opt_config)
model_io_fn.print_params(tvars, string=", trainable params")
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.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 = tf.estimator.EstimatorSpec(mode=mode,
loss=loss, train_op=train_op,
training_hooks=training_hooks)
if output_type == "sess":
try:
pred_label = tf.argmax(distillation_loss["st_logits"], axis=-1, output_type=tf.int32)
correct = tf.equal(
tf.cast(tf.ones_like(label_ids, dtype=tf.int32), tf.int32),
tf.cast(pred_label, tf.int32)
)
st_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
pred_label = tf.argmax(distillation_loss["te_logits"], axis=-1, output_type=tf.int32)
correct = tf.equal(
tf.cast(tf.zeros_like(label_ids, dtype=tf.int32), tf.int32),
tf.cast(pred_label, tf.int32)
)
te_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
except:
te_accuracy = tf.constant(0.0)
st_accuracy = tf.constant(0.0)
try:
st_accuracy = tf.reduce_mean(distillation_loss["src_f1_prob"])
te_accuracy = tf.reduce_mean(distillation_loss["tgt_f1_prob"])
except:
te_accuracy = tf.constant(0.0)
st_accuracy = tf.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":tf.reduce_sum(features["distillation_ratio"]),
"ce_num":tf.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 == tf.estimator.ModeKeys.PREDICT:
print(logits.get_shape(), "===logits shape===")
pred_label = tf.argmax(logits, axis=-1, output_type=tf.int32)
prob = tf.nn.softmax(logits)
max_prob = tf.reduce_max(prob, axis=-1)
estimator_spec = tf.estimator.EstimatorSpec(
mode=mode,
predictions={
'pred_label':pred_label,
"max_prob":max_prob
},
export_outputs={
"output":tf.estimator.export.PredictOutput(
{
'pred_label':pred_label,
"max_prob":max_prob
}
)
}
)
return estimator_spec
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss,
logits,
label_ids):
"""Computes the loss and accuracy of the model."""
sentence_log_probs = tf.reshape(
logits, [-1, logits.shape[-1]])
sentence_predictions = tf.argmax(
logits, axis=-1, output_type=tf.int32)
sentence_labels = tf.reshape(label_ids, [-1])
sentence_accuracy = tf.metrics.accuracy(
labels=label_ids, predictions=sentence_predictions)
sentence_mean_loss = tf.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 = tf.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":tf.reduce_mean(per_example_loss)
}
}
elif output_type == "estimator":
return estimator_spec
else:
raise NotImplementedError()
return model_fn
| [
"tensorflow.metrics.accuracy",
"tensorflow.control_dependencies",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.get_collection",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.argmax",
"tensorflow.nn.l2_normalize",
"tensorflow.metrics.mean",
"tensorflow.zeros_like",
"tensorflow.reduce_max",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.log",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
] | t2t_bert/distributed_single_sentence_classification/model_mdd_distillation.py | [(23, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['x', '(-1)'], {}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['y', '(-1)'], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['x'], {}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['((x - y) ** 2)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (21, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(-1)', 'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (22, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y'], {'axis': '(-1)', 'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(x * y)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(x_prob * y)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x'], {'axis': '(-1)', 'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['y'], {'axis': '(-1)', 'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (62, 'model_interface.model_zoo', 'model_zoo', (['model_config'], {}), False, 'from model_interface import model_zoo\n'), (147, 'model_io.model_io.ModelIO', 'model_io.ModelIO', (['model_io_config'], {}), False, 'from model_io import model_io\n'), (79, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {'reuse': 'model_reuse'}), True, 'import tensorflow as tf\n'), (92, 'task_module.classifier.classifier', 'classifier.classifier', (['model_config', "features['distillation_feature']", 'num_labels', 'label_ids', 'dropout_prob'], {}), False, 'from task_module import classifier\n'), (159, 'optimizer.distributed_optimizer.Optimizer', 'optimizer.Optimizer', (['opt_config'], {}), True, 'from optimizer import distributed_optimizer as optimizer\n'), (162, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(x_prob * y)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.reduce_sum', 'tf.reduce_sum', (["(per_example_loss * features['label_ratio'])"], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.log', 'tf.log', (["(features['label_probs'] + 1e-10)"], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.ones_like', 'tf.ones_like', (['label_ids'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.zeros_like', 'tf.zeros_like', (['label_ids'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['update_ops'], {}), True, 'import tensorflow as tf\n'), (185, 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'train_op': 'train_op', 'training_hooks': 'training_hooks'}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.reduce_max', 'tf.reduce_max', (['prob'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.reduce_sum', 'tf.reduce_sum', (["features['label_ratio']"], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (100, 'bunch.Bunch', 'Bunch', (["{'logits_ratio_decay': 'constant', 'logits_ratio': 0.5, 'logits_decay_rate':\n 0.999, 'distillation': ['mdd'], 'feature_ratio': 0.5,\n 'feature_ratio_decay': 'constant', 'feature_decay_rate': 0.999,\n 'kd_type': 'kd', 'scope': scope}"], {}), False, 'from bunch import Bunch\n'), (293, 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'loss', 'eval_metric_ops': 'eval_metric_ops'}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.argmax', 'tf.argmax', (["distillation_loss['st_logits']"], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (198, 'tensorflow.argmax', 'tf.argmax', (["distillation_loss['te_logits']"], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.reduce_mean', 'tf.reduce_mean', (["distillation_loss['src_f1_prob']"], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.reduce_mean', 'tf.reduce_mean', (["distillation_loss['tgt_f1_prob']"], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1, logits.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.reshape', 'tf.reshape', (['label_ids', '[-1]'], {}), True, 'import tensorflow as tf\n'), (272, 'tensorflow.metrics.accuracy', 'tf.metrics.accuracy', ([], {'labels': 'label_ids', 'predictions': 'sentence_predictions'}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.metrics.mean', 'tf.metrics.mean', ([], {'values': 'per_example_loss'}), True, 'import tensorflow as tf\n'), (276, 'metric.tf_metrics.f1', 'tf_metrics.f1', (['label_ids', 'sentence_predictions', 'num_labels', 'label_lst'], {'average': '"""macro"""'}), False, 'from metric import tf_metrics\n'), (194, 'tensorflow.cast', 'tf.cast', (['pred_label', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.cast', 'tf.cast', (['correct', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.cast', 'tf.cast', (['pred_label', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.cast', 'tf.cast', (['correct', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.reduce_sum', 'tf.reduce_sum', (["features['distillation_ratio']"], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.reduce_sum', 'tf.reduce_sum', (["features['label_ratio']"], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.estimator.export.PredictOutput', 'tf.estimator.export.PredictOutput', (["{'pred_label': pred_label, 'max_prob': max_prob}"], {}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.ones_like', 'tf.ones_like', (['label_ids'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.zeros_like', 'tf.zeros_like', (['label_ids'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['per_example_loss'], {}), True, 'import tensorflow as tf\n')] |
SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | # Copyright 2018 The TensorFlow 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 tensorflow as tf # pylint: disable=g-bad-import-order
import tensorflow.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 = tf.random_normal([batch_size, 784])
labels = tf.random_uniform([batch_size], minval=0, maxval=10, dtype=tf.int32)
return tf.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 = tf.train.GradientDescentOptimizer(learning_rate=0.01)
dataset = random_dataset()
with tf.device(device()):
mnist_eager.train(model, optimizer, dataset,
step_counter=tf.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 tf.device(device()):
mnist_eager.test(model, dataset)
class MNISTTest(tf.test.TestCase):
"""Run tests for MNIST eager loop."""
def setUp(self):
if not keras_utils.is_v2_0():
tf.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__":
tf.test.main()
| [
"tensorflow.data.Dataset.from_tensors",
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.test.main",
"tensorflow.train.get_or_create_global_step",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.contrib.eager.num_gpus",
"tensorflow.contrib.eager.defun",
"tensorflow.random_uniform",
"tensorflow.random_normal"
] | official/mnist/mnist_eager_test.py | [(37, 'tensorflow.random_normal', 'tf.random_normal', (['[batch_size, 784]'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.random_uniform', 'tf.random_uniform', (['[batch_size]'], {'minval': '(0)', 'maxval': '(10)', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.data.Dataset.from_tensors', 'tf.data.Dataset.from_tensors', (['(images, labels)'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.01)'}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (32, 'tensorflow.contrib.eager.num_gpus', 'tfe.num_gpus', ([], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (45, 'tensorflow.contrib.eager.defun', 'tfe.defun', (['model.call'], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (57, 'tensorflow.contrib.eager.defun', 'tfe.defun', (['model.call'], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (59, 'official.mnist.mnist_eager.test', 'mnist_eager.test', (['model', 'dataset'], {}), False, 'from official.mnist import mnist_eager\n'), (66, 'official.utils.misc.keras_utils.is_v2_0', 'keras_utils.is_v2_0', ([], {}), False, 'from official.utils.misc import keras_utils\n'), (67, 'tensorflow.compat.v1.enable_v2_behavior', 'tf.compat.v1.enable_v2_behavior', ([], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n')] |
SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | # Copyright 2017 The TensorFlow 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 TFGAN trained MNIST model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import data_provider
import networks
import tensorflow as tf
from absl import app
from absl import flags
import util
tfgan = tf.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 tf.name_scope('inputs'):
noise, one_hot_labels = _get_generator_inputs(
FLAGS.num_images_per_class, NUM_CLASSES, FLAGS.noise_dims)
# Generate images.
with tf.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)
tf.summary.image('generated_images', reshaped_img, max_outputs=1)
# Calculate evaluation metrics.
tf.summary.scalar('MNIST_Classifier_score',
util.mnist_score(images, FLAGS.classifier_filename))
tf.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 = tf.write_file(
'%s/%s'% (FLAGS.eval_dir, 'conditional_gan.png'),
tf.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
tf.contrib.training.evaluate_repeatedly(
FLAGS.checkpoint_dir,
hooks=[tf.contrib.training.SummaryAtEndHook(FLAGS.eval_dir),
tf.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 = tf.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 = tf.one_hot(tf.constant(labels), num_classes)
return noise, one_hot_labels
if __name__ == '__main__':
app.run(main)
| [
"tensorflow.constant",
"tensorflow.summary.image",
"tensorflow.contrib.training.SummaryAtEndHook",
"tensorflow.name_scope",
"tensorflow.variable_scope",
"tensorflow.contrib.training.StopAfterNEvalsHook",
"tensorflow.random_normal"
] | research/gan/mnist/conditional_eval.py | [(32, 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""checkpoint_dir"""', '"""/tmp/mnist/"""', '"""Directory where the model was written to."""'], {}), False, 'from absl import flags\n'), (35, 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""eval_dir"""', '"""/tmp/mnist/"""', '"""Directory where the results are saved to."""'], {}), False, 'from absl import flags\n'), (38, 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_images_per_class"""', '(10)', '"""Number of images to generate per class."""'], {}), False, 'from absl import flags\n'), (41, 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""noise_dims"""', '(64)', '"""Dimensions of the generator noise vector"""'], {}), False, 'from absl import flags\n'), (44, 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""classifier_filename"""', 'None', '"""Location of the pretrained classifier. If `None`, use default."""'], {}), False, 'from absl import flags\n'), (48, 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""max_number_of_evaluations"""', 'None', '"""Number of times to run evaluation. If `None`, run forever."""'], {}), False, 'from absl import flags\n'), (52, 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""write_to_disk"""', '(True)', '"""If `True`, run images to disk."""'], {}), False, 'from absl import flags\n'), (71, 'tensorflow.summary.image', 'tf.summary.image', (['"""generated_images"""', 'reshaped_img'], {'max_outputs': '(1)'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.random_normal', 'tf.random_normal', (['[num_images_generated, noise_dims]'], {}), True, 'import tensorflow as tf\n'), (110, 'absl.app.run', 'app.run', (['main'], {}), False, 'from absl import app\n'), (59, 'tensorflow.name_scope', 'tf.name_scope', (['"""inputs"""'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Generator"""'], {}), True, 'import tensorflow as tf\n'), (65, 'networks.conditional_generator', 'networks.conditional_generator', (['(noise, one_hot_labels)'], {'is_training': '(False)'}), False, 'import networks\n'), (75, 'util.mnist_score', 'util.mnist_score', (['images', 'FLAGS.classifier_filename'], {}), False, 'import util\n'), (77, 'util.mnist_cross_entropy', 'util.mnist_cross_entropy', (['images', 'one_hot_labels', 'FLAGS.classifier_filename'], {}), False, 'import util\n'), (105, 'tensorflow.constant', 'tf.constant', (['labels'], {}), True, 'import tensorflow as tf\n'), (85, 'data_provider.float_image_to_uint8', 'data_provider.float_image_to_uint8', (['reshaped_img[0]'], {}), False, 'import data_provider\n'), (92, 'tensorflow.contrib.training.SummaryAtEndHook', 'tf.contrib.training.SummaryAtEndHook', (['FLAGS.eval_dir'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.training.StopAfterNEvalsHook', 'tf.contrib.training.StopAfterNEvalsHook', (['(1)'], {}), True, 'import tensorflow as tf\n')] |
shfshf/seq2annotation | a824520d46f0b3d70268fae422976a5ce1b3f4ce | import tensorflow as tf
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 = tf.transpose(embeddings, perm=[1, 0, 2])
lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'])
lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size'])
lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw)
output_fw, _ = lstm_cell_fw(t, dtype=tf.float32,
sequence_length=nwords)
output_bw, _ = lstm_cell_bw(t, dtype=tf.float32,
sequence_length=nwords)
output = tf.concat([output_fw, output_bw], axis=-1)
# transpose it back
output = tf.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
| [
"tensorflow.concat",
"tensorflow.contrib.rnn.TimeReversedFusedRNN",
"tensorflow.contrib.rnn.LSTMBlockFusedCell",
"tensorflow.transpose"
] | seq2annotation/algorithms/Stacked_BiLSTM_CRF_model.py | [(15, 'tensorflow.transpose', 'tf.transpose', (['embeddings'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.contrib.rnn.LSTMBlockFusedCell', 'tf.contrib.rnn.LSTMBlockFusedCell', (["self.params['lstm_size']"], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.contrib.rnn.LSTMBlockFusedCell', 'tf.contrib.rnn.LSTMBlockFusedCell', (["self.params['lstm_size']"], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.contrib.rnn.TimeReversedFusedRNN', 'tf.contrib.rnn.TimeReversedFusedRNN', (['lstm_cell_bw'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.concat', 'tf.concat', (['[output_fw, output_bw]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.transpose', 'tf.transpose', (['output'], {'perm': '[1, 0, 2]'}), True, 'import tensorflow as tf\n')] |
GaoX2015/intro_ds | 886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5 | # -*- coding: UTF-8 -*-
"""
此脚本用于随机生成线性模型数据、定义模型以及其他工具
"""
import numpy as np
import tensorflow as tf
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 = tf.placeholder(tf.float64, shape=[None, dimension], name='x')
## 将被预测值写成矩阵形式,会极大加快速度
y = tf.placeholder(tf.float64, shape=[None, 1], name="y")
# 定义参数估计值和预测值
betaPred = tf.Variable(np.random.random([dimension, 1]))
yPred = tf.matmul(x, betaPred, name="y_pred")
# 定义损失函数
loss = tf.reduce_mean(tf.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 tf.gfile.Exists(logPath):
tf.gfile.DeleteRecursively(logPath)
summaryWriter = tf.summary.FileWriter(logPath, graph=tf.get_default_graph())
return summaryWriter
| [
"tensorflow.matmul",
"numpy.random.random",
"tensorflow.gfile.DeleteRecursively",
"numpy.random.seed",
"tensorflow.gfile.Exists",
"tensorflow.placeholder",
"tensorflow.square",
"tensorflow.get_default_graph"
] | ch06-sgd/utils.py | [(27, 'numpy.random.seed', 'np.random.seed', (['(1024)'], {}), True, 'import numpy as np\n'), (29, 'numpy.random.random', 'np.random.random', (['(num, dimension)'], {}), True, 'import numpy as np\n'), (30, 'numpy.random.random', 'np.random.random', (['(num, 1)'], {}), True, 'import numpy as np\n'), (48, 'numpy.random.seed', 'np.random.seed', (['(1024)'], {}), True, 'import numpy as np\n'), (50, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float64'], {'shape': '[None, dimension]', 'name': '"""x"""'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float64'], {'shape': '[None, 1]', 'name': '"""y"""'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.matmul', 'tf.matmul', (['x', 'betaPred'], {'name': '"""y_pred"""'}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['logPath'], {}), True, 'import tensorflow as tf\n'), (54, 'numpy.random.random', 'np.random.random', (['[dimension, 1]'], {}), True, 'import numpy as np\n'), (57, 'tensorflow.square', 'tf.square', (['(yPred - y)'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.gfile.DeleteRecursively', 'tf.gfile.DeleteRecursively', (['logPath'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\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 tensorflow as tf
import tensorflow.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 tf.Graph().as_default() as graph, tf.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)
tf.summary.scalar('lr', lr)
optimizer = tf.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM)
r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs,
is_training=True)
with tf.name_scope('get_batch'):
if cfgs.IMAGE_PYRAMID:
shortside_len_list = tf.constant(cfgs.IMG_SHORT_SIDE_LEN)
shortside_len = tf.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 = tf.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 / tf.constant([cfgs.PIXEL_STD])
gtboxes_and_label_r = tf.py_func(backward_convert,
inp=[gtboxes_and_label_batch[i]],
Tout=tf.float32)
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
num_objects = num_objects_batch[i]
num_objects = tf.cast(tf.reshape(num_objects, [-1, ]), tf.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 = tf.no_regularizer
weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(num_gpu):
with tf.device('/gpu:%d' % i):
with tf.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=tf.constant_initializer(0.0)):
gtboxes_and_label_h, gtboxes_and_label_r = tf.py_func(self.get_gtboxes_and_label,
inp=[inputs_list[i][1],
inputs_list[i][2],
inputs_list[i][3]],
Tout=[tf.float32, tf.float32])
gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [-1, 5])
gtboxes_and_label_r = tf.reshape(gtboxes_and_label_r, [-1, 6])
img = inputs_list[i][0]
img_shape = inputs_list[i][-2:]
img = tf.image.crop_to_bounding_box(image=img,
offset_height=0,
offset_width=0,
target_height=tf.cast(img_shape[0], tf.int32),
target_width=tf.cast(img_shape[1], tf.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)
tf.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h)
tf.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)
tf.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 = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
# weight_decay_loss = tf.add_n(slim.losses.get_regularization_losses())
total_losses = total_losses + tf.add_n(regularization_losses)
tf.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() | [
"tensorflow.device",
"tensorflow.cast",
"tensorflow.random_shuffle",
"tensorflow.summary.scalar",
"tensorflow.add_n",
"tensorflow.py_func",
"tensorflow.Graph",
"tensorflow.contrib.slim.get_or_create_global_step",
"tensorflow.get_collection",
"tensorflow.summary.image",
"tensorflow.train.MomentumOptimizer",
"tensorflow.name_scope",
"tensorflow.contrib.slim.arg_scope",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.contrib.slim.learning.clip_gradient_norms",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.get_variable_scope"
] | tools/r3det_gwd/train.py | [(15, 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), False, 'import sys\n'), (33, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.contrib.slim.get_or_create_global_step', 'slim.get_or_create_global_step', ([], {}), True, 'import tensorflow.contrib.slim as slim\n'), (38, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""lr"""', 'lr'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['lr'], {'momentum': 'cfgs.MOMENTUM'}), True, 'import tensorflow as tf\n'), (41, 'libs.models.detectors.r3det_gwd.build_whole_network.DetectionNetworkR3DetGWD', 'build_whole_network.DetectionNetworkR3DetGWD', ([], {'cfgs': 'self.cfgs', 'is_training': '(True)'}), False, 'from libs.models.detectors.r3det_gwd import build_whole_network\n'), (84, 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['cfgs.WEIGHT_DECAY'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.name_scope', 'tf.name_scope', (['"""get_batch"""'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.expand_dims', 'tf.expand_dims', (['img_batch[i]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (62, 'dataloader.pretrained_weights.pretrain_zoo.PretrainModelZoo', 'PretrainModelZoo', ([], {}), False, 'from dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo\n'), (66, 'tensorflow.py_func', 'tf.py_func', (['backward_convert'], {'inp': '[gtboxes_and_label_batch[i]]', 'Tout': 'tf.float32'}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.reshape', 'tf.reshape', (['gtboxes_and_label_r', '[-1, 6]'], {}), True, 'import tensorflow as tf\n'), (71, 'libs.utils.coordinate_convert.get_horizen_minAreaRectangle', 'get_horizen_minAreaRectangle', (['gtboxes_and_label_batch[i]'], {}), False, 'from libs.utils.coordinate_convert import backward_convert, get_horizen_minAreaRectangle\n'), (72, 'tensorflow.reshape', 'tf.reshape', (['gtboxes_and_label_h', '[-1, 5]'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.constant', 'tf.constant', (['cfgs.IMG_SHORT_SIDE_LEN'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.reshape', 'tf.reshape', (['num_objects', '[-1]'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (35, 'libs.configs.cfgs.GPU_GROUP.strip', 'cfgs.GPU_GROUP.strip', ([], {}), False, 'from libs.configs import cfgs\n'), (47, 'tensorflow.random_shuffle', 'tf.random_shuffle', (['shortside_len_list'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.constant', 'tf.constant', (['[cfgs.PIXEL_STD]'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.device', 'tf.device', (["('/gpu:%d' % i)"], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.name_scope', 'tf.name_scope', (["('tower_%d' % i)"], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.model_variable, slim.variable]'], {'device': '"""/device:CPU:0"""'}), True, 'import tensorflow.contrib.slim as slim\n'), (156, 'tensorflow.contrib.slim.learning.clip_gradient_norms', 'slim.learning.clip_gradient_norms', (['grads', 'cfgs.GRADIENT_CLIPPING_BY_NORM'], {}), True, 'import tensorflow.contrib.slim as slim\n'), (100, 'tensorflow.py_func', 'tf.py_func', (['self.get_gtboxes_and_label'], {'inp': '[inputs_list[i][1], inputs_list[i][2], inputs_list[i][3]]', 'Tout': '[tf.float32, tf.float32]'}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.reshape', 'tf.reshape', (['gtboxes_and_label_h', '[-1, 5]'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.reshape', 'tf.reshape', (['gtboxes_and_label_r', '[-1, 6]'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.summary.image', 'tf.summary.image', (["('Compare/gtboxes_h_gpu:%d' % i)", 'gtboxes_in_img_h'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.summary.image', 'tf.summary.image', (["('Compare/gtboxes_r_gpu:%d' % i)", 'gtboxes_in_img_r'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.summary.image', 'tf.summary.image', (["('Compare/final_detection_gpu:%d' % i)", 'detections_in_img'], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.cast', 'tf.cast', (['img_shape[0]', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.cast', 'tf.cast', (['img_shape[1]', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.add_n', 'tf.add_n', (['regularization_losses'], {}), True, 'import tensorflow as tf\n')] |
bhbai/tensorflow | d4b5c606fc9fbd1a20b5b113b4bc831f31d889a3 | # Copyright 2016 The TensorFlow 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 tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.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 tf.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.python.framework.tensor_shape.scalar",
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.check_ops.assert_positive",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.ops.math_ops.digamma",
"tensorflow.python.ops.random_ops.random_gamma",
"tensorflow.python.ops.nn.softplus",
"tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring",
"tensorflow.python.ops.math_ops.igammac",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.math_ops.lgamma",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.framework.constant_op.constant"
] | tensorflow/contrib/distributions/python/ops/inverse_gamma.py | [(165, 'tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', (['"""This is defined to be\n\n ```\n entropy = alpha - log(beta) + log(Gamma(alpha))\n + (1-alpha)digamma(alpha)\n ```\n\n where digamma(alpha) is the digamma function."""'], {}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (180, 'tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', (['"""The mean of an inverse gamma distribution is `beta / (alpha - 1)`,\n when `alpha > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is\n `False`, an exception will be raised rather than returning `NaN`"""'], {}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (198, 'tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', (['"""Variance for inverse gamma is defined only for `alpha > 2`. If\n `self.allow_nan_stats` is `False`, an exception will be raised rather\n than returning `NaN`."""'], {}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (135, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[]'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import constant_op\n'), (138, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (163, 'tensorflow.python.ops.math_ops.igammac', 'math_ops.igammac', (['self.alpha', '(self.beta / x)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (93, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name'], {'values': '[alpha, beta]'}), False, 'from tensorflow.python.framework import ops\n'), (128, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['self.alpha'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (128, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['self.beta'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (142, 'tensorflow.python.ops.random_ops.random_gamma', 'random_ops.random_gamma', (['[n]', 'self.alpha'], {'beta': 'self.beta', 'dtype': 'self.dtype', 'seed': 'seed'}), False, 'from tensorflow.python.ops import random_ops\n'), (203, 'tensorflow.python.ops.math_ops.square', 'math_ops.square', (['self.beta'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (233, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name'], {'values': '[alpha, beta]'}), False, 'from tensorflow.python.framework import ops\n'), (98, 'tensorflow.python.ops.array_ops.identity', 'array_ops.identity', (['alpha'], {'name': '"""alpha"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (99, 'tensorflow.python.ops.array_ops.identity', 'array_ops.identity', (['beta'], {'name': '"""beta"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (177, 'tensorflow.python.ops.math_ops.lgamma', 'math_ops.lgamma', (['self.alpha'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (178, 'tensorflow.python.ops.math_ops.digamma', 'math_ops.digamma', (['self.alpha'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (204, 'tensorflow.python.ops.math_ops.square', 'math_ops.square', (['(self.alpha - 1.0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (146, 'tensorflow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', (['x'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (149, 'tensorflow.python.ops.math_ops.lgamma', 'math_ops.lgamma', (['self.alpha'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (150, 'tensorflow.python.ops.math_ops.log', 'math_ops.log', (['x'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (159, 'tensorflow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', (['x'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (176, 'tensorflow.python.ops.math_ops.log', 'math_ops.log', (['self.beta'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (235, 'tensorflow.python.ops.nn.softplus', 'nn.softplus', (['alpha'], {'name': '"""softplus_alpha"""'}), False, 'from tensorflow.python.ops import nn\n'), (236, 'tensorflow.python.ops.nn.softplus', 'nn.softplus', (['beta'], {'name': '"""softplus_gamma"""'}), False, 'from tensorflow.python.ops import nn\n'), (113, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['sample_shape'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import ops\n'), (148, 'tensorflow.python.ops.math_ops.log', 'math_ops.log', (['self.beta'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (194, 'tensorflow.python.ops.array_ops.ones', 'array_ops.ones', (['()', 'self.dtype'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (213, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['(2.0)'], {'dtype': 'self.dtype'}), False, 'from tensorflow.python.framework import constant_op\n'), (95, 'tensorflow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', (['alpha'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (96, 'tensorflow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', (['beta'], {}), False, 'from tensorflow.python.ops import check_ops\n')] |
vincentcheny/models | afb1a59fc1bc792ac72d1a3e22e2469020529788 | # Copyright 2018 The TensorFlow 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 tensorflow as tf
import layers
import networks
def _get_grad_norm(ys, xs):
"""Compute 2-norm of dys / dxs."""
return tf.sqrt(
tf.add_n([tf.reduce_sum(tf.square(g)) for g in tf.gradients(ys, xs)]))
def _num_filters_stub(block_id):
return networks.num_filters(block_id, 8, 1, 8)
class NetworksTest(tf.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 = tf.placeholder(tf.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, tf.constant(progress, tf.float32)))
for progress in [0, 0.2, 1, 1.2, 2, 2.2, 3]
]
alpha_fixed_progress = [
sess.run(
networks._generator_alpha(block_id, tf.constant(1.2, tf.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, tf.constant(
progress, tf.float32)))
for progress in [0, 0.2, 1, 1.2, 2, 2.2, 3]
]
alpha_fixed_progress = [
sess.run(
networks._discriminator_alpha(block_id,
tf.constant(1.2, tf.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 = tf.constant(x_np, tf.float32)
x_blend = networks.blend_images(
x,
progress=tf.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 = tf.constant(x_np, tf.float32)
x_blend = networks.blend_images(
x,
tf.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 = tf.placeholder(tf.int32, [])
progress = networks.compute_progress(
current_image_id_ph,
stable_stage_num_images,
transition_stage_num_images,
num_blocks=3)
z = tf.random_normal([2, 10], dtype=tf.float32)
x, _ = networks.generator(
z, progress, _num_filters_stub,
networks.ResolutionSchedule(
start_resolutions=(4, 4), scale_base=2, num_resolutions=3))
fake_loss = tf.reduce_sum(tf.square(x))
grad_norms = [
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_1/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_2/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_3/.*'))
]
grad_norms_output = None
with self.test_session(use_gpu=True) as sess:
sess.run(tf.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 = tf.placeholder(tf.int32, [])
progress = networks.compute_progress(
current_image_id_ph,
stable_stage_num_images,
transition_stage_num_images,
num_blocks=3)
x = tf.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 = tf.reduce_sum(tf.square(logits))
grad_norms = [
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_1/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_2/.*')),
_get_grad_norm(
fake_loss, tf.trainable_variables('.*/progressive_gan_block_3/.*'))
]
grad_norms_output = None
with self.test_session(use_gpu=True) as sess:
sess.run(tf.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__':
tf.test.main()
| [
"tensorflow.constant",
"tensorflow.gradients",
"tensorflow.placeholder",
"tensorflow.test.main",
"tensorflow.global_variables_initializer",
"numpy.random.normal",
"numpy.argmax",
"tensorflow.square",
"tensorflow.trainable_variables",
"tensorflow.random_normal"
] | research/gan/progressive_gan/networks_test.py | [(34, 'networks.num_filters', 'networks.num_filters', (['block_id', '(8)', '(1)', '(8)'], {}), False, 'import networks\n'), (248, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (40, 'networks.ResolutionSchedule', 'networks.ResolutionSchedule', ([], {'start_resolutions': '[5, 3]', 'scale_base': '(2)', 'num_resolutions': '(3)'}), False, 'import networks\n'), (61, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[]'], {}), True, 'import tensorflow as tf\n'), (62, 'networks.compute_progress', 'networks.compute_progress', (['current_image_id_ph'], {'stable_stage_num_images': '(7)', 'transition_stage_num_images': '(8)', 'num_blocks': '(2)'}), False, 'import networks\n'), (112, 'numpy.random.normal', 'np.random.normal', ([], {'size': '[2, 8, 8, 3]'}), True, 'import numpy as np\n'), (113, 'tensorflow.constant', 'tf.constant', (['x_np', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (126, 'numpy.random.normal', 'np.random.normal', ([], {'size': '[2, 8, 8, 3]'}), True, 'import numpy as np\n'), (127, 'tensorflow.constant', 'tf.constant', (['x_np', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[]'], {}), True, 'import tensorflow as tf\n'), (149, 'networks.compute_progress', 'networks.compute_progress', (['current_image_id_ph', 'stable_stage_num_images', 'transition_stage_num_images'], {'num_blocks': '(3)'}), False, 'import networks\n'), (154, 'tensorflow.random_normal', 'tf.random_normal', (['[2, 10]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[]'], {}), True, 'import tensorflow as tf\n'), (202, 'networks.compute_progress', 'networks.compute_progress', (['current_image_id_ph', 'stable_stage_num_images', 'transition_stage_num_images'], {'num_blocks': '(3)'}), False, 'import networks\n'), (207, 'tensorflow.random_normal', 'tf.random_normal', (['[2, 16, 16, 3]'], {}), True, 'import tensorflow as tf\n'), (55, 'networks.block_name', 'networks.block_name', (['(10)'], {}), False, 'import networks\n'), (58, 'networks.min_total_num_images', 'networks.min_total_num_images', (['(7)', '(8)', '(4)'], {}), False, 'import networks\n'), (130, 'tensorflow.constant', 'tf.constant', (['(0.2)'], {}), True, 'import tensorflow as tf\n'), (141, 'networks.num_filters', 'networks.num_filters', (['(1)', '(4096)', '(1)', '(256)'], {}), False, 'import networks\n'), (142, 'networks.num_filters', 'networks.num_filters', (['(5)', '(4096)', '(1)', '(256)'], {}), False, 'import networks\n'), (157, 'networks.ResolutionSchedule', 'networks.ResolutionSchedule', ([], {'start_resolutions': '(4, 4)', 'scale_base': '(2)', 'num_resolutions': '(3)'}), False, 'import networks\n'), (159, 'tensorflow.square', 'tf.square', (['x'], {}), True, 'import tensorflow as tf\n'), (183, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (0)] > 0)'], {}), True, 'import numpy as np\n'), (188, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (1)] > 0)'], {}), True, 'import numpy as np\n'), (193, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (2)] > 0)'], {}), True, 'import numpy as np\n'), (210, 'networks.ResolutionSchedule', 'networks.ResolutionSchedule', ([], {'start_resolutions': '(4, 4)', 'scale_base': '(2)', 'num_resolutions': '(3)'}), False, 'import networks\n'), (212, 'tensorflow.square', 'tf.square', (['logits'], {}), True, 'import tensorflow as tf\n'), (232, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (0)] > 0)'], {}), True, 'import numpy as np\n'), (237, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (1)] > 0)'], {}), True, 'import numpy as np\n'), (242, 'numpy.argmax', 'np.argmax', (['(grad_norms_output[:, (2)] > 0)'], {}), True, 'import numpy as np\n'), (116, 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (117, 'networks.ResolutionSchedule', 'networks.ResolutionSchedule', ([], {'scale_base': '(2)', 'num_resolutions': '(2)'}), False, 'import networks\n'), (131, 'networks.ResolutionSchedule', 'networks.ResolutionSchedule', ([], {'scale_base': '(2)', 'num_resolutions': '(2)'}), False, 'import networks\n'), (162, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_1/.*"""'], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_2/.*"""'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_3/.*"""'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_1/.*"""'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_2/.*"""'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['""".*/progressive_gan_block_3/.*"""'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.square', 'tf.square', (['g'], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.gradients', 'tf.gradients', (['ys', 'xs'], {}), True, 'import tensorflow as tf\n'), (122, 'layers.downscale', 'layers.downscale', (['x', '(2)'], {}), False, 'import layers\n'), (80, 'tensorflow.constant', 'tf.constant', (['progress', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.constant', 'tf.constant', (['(1.2)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.constant', 'tf.constant', (['progress', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.constant', 'tf.constant', (['(1.2)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (137, 'layers.downscale', 'layers.downscale', (['x', '(2)'], {}), False, 'import layers\n')] |
vincentcheny/models | afb1a59fc1bc792ac72d1a3e22e2469020529788 | # Copyright 2018 The TensorFlow 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 tensorflow 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 tf.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 tf.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
tf.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=tf.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(tf.to_float(inputs))
rnn_inputs = tf.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, tf.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 tf.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 tf.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
tf.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 tf.distributions.Normal distribution
conditioned on its inputs. If proposal_type is "prior" this argument is
ignored.
rev_rnn_cell: A subclass of tf.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 tf.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=tf.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 = tf.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 = tf.reverse_sequence(
targets_encoded, seq_lengths, seq_axis=0, batch_axis=1)
# Compute the reverse rnn over the targets.
reverse_rnn_out, _ = tf.nn.dynamic_rnn(self.rev_rnn_cell,
reverse_targets_encoded,
time_major=True,
dtype=tf.float32)
reverse_rnn_out = tf.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 tf.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 tf.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 = tf.reduce_sum(p_xt_given_zt.log_prob(targets), axis=-1)
log_p_zt = tf.reduce_sum(p_zt.log_prob(zt), axis=-1)
log_q_zt = tf.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 = tf.cond(
tf.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 = tf.cond(
tf.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 *= tf.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": tf.contrib.layers.xavier_initializer(),
"b": tf.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 = tf.nn.rnn_cell.LSTMCell(rnn_hidden_size,
initializer=initializers["w"])
rev_rnn_cell = tf.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)
| [
"tensorflow.reduce_max",
"tensorflow.nn.dynamic_rnn",
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.greater",
"tensorflow.nn.rnn_cell.LSTMCell",
"tensorflow.zeros_initializer",
"tensorflow.less",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.to_float",
"tensorflow.reverse_sequence"
] | research/fivo/fivo/models/vrnn.py | [(31, 'collections.namedtuple', 'namedtuple', (['"""VRNNState"""', '"""rnn_state latent_encoded"""'], {}), False, 'from collections import namedtuple\n'), (216, 'collections.namedtuple', 'namedtuple', (['"""TrainableVRNNState"""', "(VRNNState._fields + ('rnn_out',))"], {}), False, 'from collections import namedtuple\n'), (446, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (447, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (515, 'sonnet.nets.MLP', 'snt.nets.MLP', ([], {'output_sizes': '(fcnet_hidden_sizes + [encoded_data_size])', 'initializers': 'initializers', 'name': '"""data_encoder"""'}), True, 'import sonnet as snt\n'), (519, 'sonnet.nets.MLP', 'snt.nets.MLP', ([], {'output_sizes': '(fcnet_hidden_sizes + [encoded_latent_size])', 'initializers': 'initializers', 'name': '"""latent_encoder"""'}), True, 'import sonnet as snt\n'), (523, 'fivo.models.base.ConditionalNormalDistribution', '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"""'}), False, 'from fivo.models import base\n'), (565, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', (['rnn_hidden_size'], {'initializer': "initializers['w']"}), True, 'import tensorflow as tf\n'), (567, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', (['rnn_hidden_size'], {'initializer': "initializers['w']"}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.concat', 'tf.concat', (['[inputs_encoded, prev_latent_encoded]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.reduce_max', 'tf.reduce_max', (['seq_lengths'], {}), True, 'import tensorflow as tf\n'), (350, 'fivo.models.base.ta_for_tensor', 'base.ta_for_tensor', (['inputs'], {'clear_after_read': '(False)'}), False, 'from fivo.models import base\n'), (351, 'fivo.models.base.ta_for_tensor', 'base.ta_for_tensor', (['targets'], {'clear_after_read': '(False)'}), False, 'from fivo.models import base\n'), (352, 'fivo.models.base.encode_all', 'base.encode_all', (['targets', 'self.data_encoder'], {}), False, 'from fivo.models import base\n'), (353, 'fivo.models.base.ta_for_tensor', 'base.ta_for_tensor', (['targets_encoded'], {'clear_after_read': '(False)'}), False, 'from fivo.models import base\n'), (534, 'functools.partial', 'functools.partial', (['base.ConditionalBernoulliDistribution'], {'bias_init': 'emission_bias_init'}), False, 'import functools\n'), (545, 'fivo.models.base.NormalApproximatePosterior', '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"""'}), False, 'from fivo.models import base\n'), (154, 'tensorflow.to_float', 'tf.to_float', (['inputs'], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.to_float', 'tf.to_float', (['xt'], {}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['targets_encoded', 'seq_lengths'], {'seq_axis': '(0)', 'batch_axis': '(1)'}), True, 'import tensorflow as tf\n'), (359, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['self.rev_rnn_cell', 'reverse_targets_encoded'], {'time_major': '(True)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['reverse_rnn_out', 'seq_lengths'], {'seq_axis': '(0)', 'batch_axis': '(1)'}), True, 'import tensorflow as tf\n'), (365, 'fivo.models.base.ta_for_tensor', 'base.ta_for_tensor', (['reverse_rnn_out'], {'clear_after_read': '(False)'}), False, 'from fivo.models import base\n'), (438, 'tensorflow.to_float', 'tf.to_float', (['(t < self.seq_lengths - 1)'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.zeros', 'tf.zeros', (['[batch_size, self.latent_encoder.output_size]'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (331, 'tensorflow.zeros', 'tf.zeros', (['[batch_size, self.rnn_cell.output_size]'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (430, 'tensorflow.greater', 'tf.greater', (['t', '(0)'], {}), True, 'import tensorflow as tf\n'), (434, 'tensorflow.less', 'tf.less', (['(t + 1)', 'self.max_seq_len'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
from tensorflow.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 = tf.reduce_mean(input_, axes)
res = tf.square(input_ - mean)
max_sqr = tf.reduce_max(res, axes)
res /= max_sqr
res = tf.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 = tf.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 tf.variable_scope(name) as scope:
weights = variable_on_cpu(
"weights",
filter_size + [dim_in, dim_out],
tf.random_uniform_initializer(
minval=-stddev, maxval=stddev))
# weight normalization
if weight_norm:
weights /= tf.sqrt(tf.reduce_sum(tf.square(weights), [0, 1, 2]))
if scale:
magnitude = variable_on_cpu(
"magnitude", [dim_out],
tf.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 = tf.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 = tf.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 = tf.concat(axis=1, values=[pad_1, res])
res = tf.concat(axis=2, values=[pad_2, res])
res = tf.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 = tf.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], tf.constant_initializer(0.))
res = tf.nn.bias_add(res, biases)
if nonlinearity is not None:
res = nonlinearity(res)
return res
def max_pool_2x2(input_):
"""Max pooling."""
return tf.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 = tf.reshape(input_, [batch_size, height, 1, width, 1, channels])
res = tf.concat(
axis=2, values=[res, tf.zeros([batch_size, height, stride - 1, width, 1, channels])])
res = tf.concat(axis=4, values=[
res, tf.zeros([batch_size, height, stride, width, stride - 1, channels])
])
res = tf.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 = tf.split(axis=0, num_or_size_splits=batch_size, value=input_)
res = [elem[0, :, :, :] for elem in res]
res = [tf.image.random_flip_left_right(elem) for elem in res]
res = [tf.reshape(elem, [1, height, width, channels]) for elem in res]
res = tf.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 = tf.range(n_elem)
indices = tf.cast(indices, tf.int64)
indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])])
indices_input = tf.reshape(indices_input, [2, -1])
indices_input = tf.transpose(indices_input)
res = tf.sparse_to_dense(
indices_input, [n_elem, n_indices], 1., 0., name="flat_one_hot")
res = tf.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 = tf.reshape(
input_,
[batch_size,
height // n_factor,
n_factor, width // n_factor,
n_factor, channels])
res = tf.transpose(res, [0, 1, 3, 5, 2, 4])
res = tf.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 = tf.reshape(input_, [batch_size, height, width, channels // 4, 2, 2])
res = tf.transpose(res, [0, 1, 4, 2, 5, 3])
res = tf.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 tf.variable_scope(name):
var = variable_on_cpu(
"var", [dim], tf.constant_initializer(1.), trainable=False)
mean = variable_on_cpu(
"mean", [dim], tf.constant_initializer(0.), trainable=False)
step = variable_on_cpu("step", [], tf.constant_initializer(0.), trainable=False)
if scale:
gamma = variable_on_cpu("gamma", [dim], tf.constant_initializer(1.))
beta = variable_on_cpu("beta", [dim], tf.constant_initializer(0.))
# choose the appropriate moments
if train:
used_mean, used_var = tf.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 - tf.stop_gradient(mean))
used_var -= (1 - bn_lag) * (used_var - tf.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) / tf.sqrt(used_var + epsilon)
# de-normalize
if scale:
res *= gamma
res += beta
# update variables
if train:
with tf.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]):
with ops.colocate_with(mean):
new_mean = tf.assign_sub(
mean,
tf.check_numerics(decay * (mean - cur_mean), "NaN in moving mean."))
with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]):
with ops.colocate_with(var):
new_var = tf.assign_sub(
var,
tf.check_numerics(decay * (var - cur_var),
"NaN in moving variance."))
with tf.name_scope(name, "IncrementTime", [step]):
with ops.colocate_with(step):
new_step = tf.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 tf.variable_scope(name) as scope:
if reuse:
scope.reuse_variables()
var = variable_on_cpu(
"var", [dim], tf.constant_initializer(1.), trainable=False)
mean = variable_on_cpu(
"mean", [dim], tf.constant_initializer(0.), trainable=False)
step = variable_on_cpu("step", [], tf.constant_initializer(0.), trainable=False)
# choose the appropriate moments
if train:
used_mean, used_var = tf.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 - tf.stop_gradient(mean))
used_mean /= (1. - bn_lag**(step + 1))
used_var -= (1 - bn_lag) * (used_var - tf.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 tf.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]):
with ops.colocate_with(mean):
new_mean = tf.assign_sub(
mean,
tf.check_numerics(
decay * (mean - cur_mean), "NaN in moving mean."))
with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]):
with ops.colocate_with(var):
new_var = tf.assign_sub(
var,
tf.check_numerics(decay * (var - cur_var),
"NaN in moving variance."))
with tf.name_scope(name, "IncrementTime", [step]):
with ops.colocate_with(step):
new_step = tf.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=tf.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 tf.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 == tf.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 * (tf.square(input_) + numpy.log(2. * numpy.pi))
return res
def standard_normal_sample(shape):
"""Samples from standard Gaussian distribution."""
return tf.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 = tf.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 = tf.nn.conv2d(
input=input_,
filter=weights,
strides=[1, 2, 2, 1],
padding="SAME",
name="squeeze_2x2")
return res
| [
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.conv2d_transpose",
"tensorflow.nn.conv2d",
"tensorflow.sparse_to_dense",
"tensorflow.image.random_flip_left_right",
"tensorflow.assign_add",
"tensorflow.random_uniform_initializer",
"tensorflow.nn.moments",
"tensorflow.check_numerics",
"tensorflow.stop_gradient",
"tensorflow.name_scope",
"tensorflow.square",
"numpy.zeros",
"numpy.log",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.split",
"numpy.array",
"tensorflow.nn.bias_add",
"tensorflow.reduce_max",
"tensorflow.transpose",
"tensorflow.range",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.constant_initializer",
"numpy.prod",
"tensorflow.variable_scope",
"tensorflow.sqrt",
"tensorflow.random_normal"
] | research/real_nvp/real_nvp_utils.py | [(428, 'numpy.array', 'numpy.array', (['[[[[1.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 1.0, 0.0]]], [[[0.0, 0.0, 0.0, 1.0]],\n [[0.0, 1.0, 0.0, 0.0]]]]'], {}), False, 'import numpy\n'), (33, 'tensorflow.square', 'tf.square', (['(input_ - mean)'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.reduce_max', 'tf.reduce_max', (['res', 'axes'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['res', 'axes'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.get_variable', 'tf.get_variable', (['name', 'shape'], {'initializer': 'initializer', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['input_'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.reshape', 'tf.reshape', (['input_', '[batch_size, height, 1, width, 1, channels]'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.reshape', 'tf.reshape', (['res', '[batch_size, stride * height, stride * width, channels]'], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.split', 'tf.split', ([], {'axis': '(0)', 'num_or_size_splits': 'batch_size', 'value': 'input_'}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(0)', 'values': 'res'}), True, 'import tensorflow as tf\n'), (176, 'numpy.prod', 'numpy.prod', (['shape'], {}), False, 'import numpy\n'), (177, 'tensorflow.range', 'tf.range', (['n_elem'], {}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.cast', 'tf.cast', (['indices', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (180, 'tensorflow.reshape', 'tf.reshape', (['indices_input', '[2, -1]'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.transpose', 'tf.transpose', (['indices_input'], {}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.sparse_to_dense', 'tf.sparse_to_dense', (['indices_input', '[n_elem, n_indices]', '(1.0)', '(0.0)'], {'name': '"""flat_one_hot"""'}), True, 'import tensorflow as tf\n'), (184, 'tensorflow.reshape', 'tf.reshape', (['res', '([elem for elem in shape] + [n_indices])'], {}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.reshape', 'tf.reshape', (['input_', '[batch_size, height // n_factor, n_factor, width // n_factor, n_factor,\n channels]'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.transpose', 'tf.transpose', (['res', '[0, 1, 3, 5, 2, 4]'], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.reshape', 'tf.reshape', (['res', '[batch_size, height // n_factor, width // n_factor, channels * n_factor *\n n_factor]'], {}), True, 'import tensorflow as tf\n'), (235, 'tensorflow.reshape', 'tf.reshape', (['input_', '[batch_size, height, width, channels // 4, 2, 2]'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.transpose', 'tf.transpose', (['res', '[0, 1, 4, 2, 5, 3]'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.reshape', 'tf.reshape', (['res', '[batch_size, 2 * height, 2 * width, channels // 4]'], {}), True, 'import tensorflow as tf\n'), (425, 'tensorflow.random_normal', 'tf.random_normal', (['shape'], {}), True, 'import tensorflow as tf\n'), (448, 'numpy.zeros', 'numpy.zeros', (['(2, 2, channels, 4 * channels)'], {}), False, 'import numpy\n'), (449, 'six.moves.xrange', 'xrange', (['channels'], {}), False, 'from six.moves import xrange\n'), (457, 'numpy.array', 'numpy.array', (['shuffle_channels'], {}), False, 'import numpy\n'), (32, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['input_', 'axes'], {}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', ([], {'input': 'res', 'filter': 'weights', 'strides': 'strides', 'padding': 'padding', 'name': 'scope.name'}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.image.random_flip_left_right', 'tf.image.random_flip_left_right', (['elem'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.reshape', 'tf.reshape', (['elem', '[1, height, width, channels]'], {}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.nn.moments', 'tf.nn.moments', (['input_', 'axes'], {'name': '"""batch_norm"""'}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.sqrt', 'tf.sqrt', (['(used_var + epsilon)'], {}), True, 'import tensorflow as tf\n'), (318, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.nn.moments', 'tf.nn.moments', (['input_', 'axes'], {'name': '"""batch_norm"""'}), True, 'import tensorflow as tf\n'), (379, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (460, 'tensorflow.nn.conv2d_transpose', 'tf.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"""'}), True, 'import tensorflow as tf\n'), (468, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', ([], {'input': 'input_', 'filter': 'weights', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""', 'name': '"""squeeze_2x2"""'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', ([], {'minval': '(-stddev)', 'maxval': 'stddev'}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['res', 'biases'], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""AssignMovingAvg"""', '[mean, cur_mean, decay]'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""AssignMovingAvg"""', '[var, cur_var, decay]'], {}), True, 'import tensorflow as tf\n'), (296, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""IncrementTime"""', '[step]'], {}), True, 'import tensorflow as tf\n'), (322, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (324, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (325, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""AssignMovingAvg"""', '[mean, cur_mean, decay]'], {}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""AssignMovingAvg"""', '[var, cur_var, decay]'], {}), True, 'import tensorflow as tf\n'), (355, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""IncrementTime"""', '[step]'], {}), True, 'import tensorflow as tf\n'), (418, 'tensorflow.square', 'tf.square', (['input_'], {}), True, 'import tensorflow as tf\n'), (418, 'numpy.log', 'numpy.log', (['(2.0 * numpy.pi)'], {}), False, 'import numpy\n'), (453, 'six.moves.xrange', 'xrange', (['channels'], {}), False, 'from six.moves import xrange\n'), (454, 'six.moves.xrange', 'xrange', (['channels'], {}), False, 'from six.moves import xrange\n'), (455, 'six.moves.xrange', 'xrange', (['channels'], {}), False, 'from six.moves import xrange\n'), (456, 'six.moves.xrange', 'xrange', (['channels'], {}), False, 'from six.moves import xrange\n'), (103, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': '[pad_1, res]'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(2)', 'values': '[pad_2, res]'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.zeros', 'tf.zeros', (['[batch_size, height, stride - 1, width, 1, channels]'], {}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.zeros', 'tf.zeros', (['[batch_size, height, stride, width, stride - 1, channels]'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.reshape', 'tf.reshape', (['input_', '[-1]'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['mean'], {}), False, 'from tensorflow.python.framework import ops\n'), (291, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['var'], {}), False, 'from tensorflow.python.framework import ops\n'), (297, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['step'], {}), False, 'from tensorflow.python.framework import ops\n'), (298, 'tensorflow.assign_add', 'tf.assign_add', (['step', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['mean'], {}), False, 'from tensorflow.python.framework import ops\n'), (350, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['var'], {}), False, 'from tensorflow.python.framework import ops\n'), (356, 'tensorflow.python.framework.ops.colocate_with', 'ops.colocate_with', (['step'], {}), False, 'from tensorflow.python.framework import ops\n'), (357, 'tensorflow.assign_add', 'tf.assign_add', (['step', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.square', 'tf.square', (['weights'], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['mean'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['var'], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.check_numerics', 'tf.check_numerics', (['(decay * (mean - cur_mean))', '"""NaN in moving mean."""'], {}), True, 'import tensorflow as tf\n'), (294, 'tensorflow.check_numerics', 'tf.check_numerics', (['(decay * (var - cur_var))', '"""NaN in moving variance."""'], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['mean'], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['var'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.check_numerics', 'tf.check_numerics', (['(decay * (mean - cur_mean))', '"""NaN in moving mean."""'], {}), True, 'import tensorflow as tf\n'), (353, 'tensorflow.check_numerics', 'tf.check_numerics', (['(decay * (var - cur_var))', '"""NaN in moving variance."""'], {}), True, 'import tensorflow as tf\n'), (85, 'numpy.prod', 'numpy.prod', (['filter_size'], {}), False, 'import numpy\n')] |
vincentcheny/models | afb1a59fc1bc792ac72d1a3e22e2469020529788 | # Copyright 2017 The TensorFlow 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 tensorflow 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 = tf.flags.FLAGS
def _get_configs_for_model(model_name):
"""Returns configurations for model."""
fname = os.path.join(tf.resource_loader.get_data_files_path(),
'samples/configs/' + model_name + '.config')
label_map_path = os.path.join(tf.resource_loader.get_data_files_path(),
'data/pet_label_map.pbtxt')
data_path = os.path.join(tf.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 `tf.data.Dataset` object.
Returns:
A `tf.data.Iterator`.
"""
iterator = dataset.make_initializable_iterator()
tf.add_to_collection(tf.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(tf.float32, features[fields.InputDataFields.image].dtype)
self.assertAllEqual([1],
features[inputs.HASH_KEY].shape.as_list())
self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
self.assertAllEqual(
[1, 100, 4],
labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
self.assertEqual(tf.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(tf.float32,
labels[fields.InputDataFields.groundtruth_classes].dtype)
self.assertAllEqual(
[1, 100],
labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
self.assertEqual(tf.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(
tf.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(tf.float32, features[fields.InputDataFields.image].dtype)
self.assertAllEqual([1],
features[inputs.HASH_KEY].shape.as_list())
self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
self.assertAllEqual(
[1, 100, 4],
labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
self.assertEqual(tf.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(tf.float32,
labels[fields.InputDataFields.groundtruth_classes].dtype)
self.assertAllEqual(
[1, 100],
labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
self.assertEqual(tf.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(
tf.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(tf.float32, features[fields.InputDataFields.image].dtype)
self.assertAllEqual(
[eval_batch_size, None, None, 3],
features[fields.InputDataFields.original_image].shape.as_list())
self.assertEqual(tf.uint8,
features[fields.InputDataFields.original_image].dtype)
self.assertAllEqual([eval_batch_size],
features[inputs.HASH_KEY].shape.as_list())
self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
self.assertAllEqual(
[eval_batch_size, 100, 4],
labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
self.assertEqual(tf.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(tf.float32,
labels[fields.InputDataFields.groundtruth_classes].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_weights].shape.as_list())
self.assertEqual(
tf.float32,
labels[fields.InputDataFields.groundtruth_weights].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_area].shape.as_list())
self.assertEqual(tf.float32,
labels[fields.InputDataFields.groundtruth_area].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())
self.assertEqual(
tf.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())
self.assertEqual(
tf.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(tf.float32, features[fields.InputDataFields.image].dtype)
self.assertAllEqual([batch_size],
features[inputs.HASH_KEY].shape.as_list())
self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
self.assertAllEqual(
[batch_size],
labels[fields.InputDataFields.num_groundtruth_boxes].shape.as_list())
self.assertEqual(tf.int32,
labels[fields.InputDataFields.num_groundtruth_boxes].dtype)
self.assertAllEqual(
[batch_size, 100, 4],
labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
self.assertEqual(tf.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(tf.float32,
labels[fields.InputDataFields.groundtruth_classes].dtype)
self.assertAllEqual(
[batch_size, 100],
labels[
fields.InputDataFields.groundtruth_weights].shape.as_list())
self.assertEqual(
tf.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(tf.float32, features[fields.InputDataFields.image].dtype)
self.assertAllEqual(
[eval_batch_size, 300, 300, 3],
features[fields.InputDataFields.original_image].shape.as_list())
self.assertEqual(tf.uint8,
features[fields.InputDataFields.original_image].dtype)
self.assertAllEqual([eval_batch_size],
features[inputs.HASH_KEY].shape.as_list())
self.assertEqual(tf.int32, features[inputs.HASH_KEY].dtype)
self.assertAllEqual(
[eval_batch_size, 100, 4],
labels[fields.InputDataFields.groundtruth_boxes].shape.as_list())
self.assertEqual(tf.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(tf.float32,
labels[fields.InputDataFields.groundtruth_classes].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[
fields.InputDataFields.groundtruth_weights].shape.as_list())
self.assertEqual(
tf.float32,
labels[fields.InputDataFields.groundtruth_weights].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_area].shape.as_list())
self.assertEqual(tf.float32,
labels[fields.InputDataFields.groundtruth_area].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list())
self.assertEqual(
tf.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype)
self.assertAllEqual(
[eval_batch_size, 100],
labels[fields.InputDataFields.groundtruth_difficult].shape.as_list())
self.assertEqual(
tf.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(tf.float32, image.dtype)
self.assertEqual(tf.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(tf.float32, image.dtype)
self.assertEqual(tf.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 = tf.placeholder(tf.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 = tf.placeholder(tf.string, shape=[])
replaced_string = inputs._replace_empty_string_with_random_number(
string_placeholder)
empty_string = ''
feed_dict = {string_placeholder: empty_string}
tf.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': tf.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:
tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.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': tf.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:
tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[.5, .5, 1., 1.]], np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([1.0], np.float32)),
fields.InputDataFields.groundtruth_weights:
tf.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': tf.image.ResizeMethod.NEAREST_NEIGHBOR
})
]
data_augmentation_fn = functools.partial(
inputs.augment_input_data,
data_augmentation_options=data_augmentation_options)
tensor_dict = {
fields.InputDataFields.image:
tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_instance_masks:
tf.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': tf.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:
tf.constant(np.random.rand(10, 10, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[.5, .5, 1., 1.]], np.float32)),
fields.InputDataFields.groundtruth_keypoints:
tf.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, tf.expand_dims(tf.shape(image)[1:], axis=0))
def _fake_image_resizer_fn(image, mask):
return (image, mask, tf.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:
tf.constant(image),
fields.InputDataFields.image_additional_channels:
tf.constant(additional_channels),
fields.InputDataFields.groundtruth_classes:
tf.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,
tf.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:
tf.constant(image),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)),
fields.InputDataFields.multiclass_scores:
tf.constant(np.array([0.2, 0.3, 0.5, 0.1, 0.6, 0.3], np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.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:
tf.constant(image),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)),
fields.InputDataFields.multiclass_scores:
tf.placeholder(tf.float32),
fields.InputDataFields.groundtruth_classes:
tf.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:
tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.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:
tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(
np.array([[0, 0, 1, 1], [.2, .2, 4, 4], [.5, .5, 1, 1]],
np.float32)),
fields.InputDataFields.groundtruth_area:
tf.constant(np.array([.5, .4, .3])),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, -1, 1], np.int32)),
fields.InputDataFields.groundtruth_keypoints:
tf.constant(
np.array([[[.1, .1]], [[.2, .2]], [[.5, .5]]],
np.float32)),
fields.InputDataFields.groundtruth_keypoint_visibilities:
tf.constant([True, False, True]),
fields.InputDataFields.groundtruth_instance_masks:
tf.constant(np.random.rand(3, 4, 4).astype(np.float32)),
fields.InputDataFields.groundtruth_is_crowd:
tf.constant([False, True, False]),
fields.InputDataFields.groundtruth_difficult:
tf.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:
tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.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:
tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_boxes:
tf.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32)),
fields.InputDataFields.groundtruth_confidences:
tf.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:
tf.constant(np.random.rand(4, 4, 3).astype(np.float32)),
fields.InputDataFields.groundtruth_instance_masks:
tf.constant(np.random.rand(2, 4, 4).astype(np.float32)),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32)),
fields.InputDataFields.original_image_spatial_shape:
tf.constant(np.array([4, 4], np.int32))
}
def fake_image_resizer_fn(image, masks=None):
resized_image = tf.image.resize_images(image, [8, 8])
results = [resized_image]
if masks is not None:
resized_masks = tf.transpose(
tf.image.resize_images(tf.transpose(masks, [1, 2, 0]), [8, 8]),
[2, 0, 1])
results.append(resized_masks)
results.append(tf.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, tf.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:
tf.constant(np_image),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32))
}
def fake_model_preprocessor_fn(image):
return (image / 255., tf.expand_dims(tf.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:
tf.constant(np_image),
fields.InputDataFields.groundtruth_classes:
tf.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:
tf.constant(np_image),
fields.InputDataFields.groundtruth_classes:
tf.constant(np.array([3, 1], np.int32))
}
def mul_two_model_preprocessor_fn(image):
return (image * 2, tf.expand_dims(tf.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:
tf.placeholder(tf.float32, [None, None, 3]),
fields.InputDataFields.groundtruth_boxes:
tf.placeholder(tf.float32, [None, 4]),
fields.InputDataFields.groundtruth_classes:
tf.placeholder(tf.int32, [None, 3]),
fields.InputDataFields.true_image_shape:
tf.placeholder(tf.int32, [3]),
fields.InputDataFields.original_image_spatial_shape:
tf.placeholder(tf.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:
tf.placeholder(tf.float32, [None, 4]),
fields.InputDataFields.groundtruth_classes:
tf.placeholder(tf.int32, [None, 3]),
fields.InputDataFields.num_groundtruth_boxes:
tf.placeholder(tf.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:
tf.placeholder(tf.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:
tf.placeholder(tf.float32, [None, None, 5]),
fields.InputDataFields.image_additional_channels:
tf.placeholder(tf.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:
tf.placeholder(tf.float32, [None, None, 3]),
fields.InputDataFields.image_additional_channels:
tf.placeholder(tf.float32, [None, None, 2]),
fields.InputDataFields.original_image:
tf.placeholder(tf.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:
tf.placeholder(tf.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:
tf.placeholder(tf.float32, [None, None, 3]),
fields.InputDataFields.image_additional_channels:
tf.placeholder(tf.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:
tf.placeholder(tf.float32, [None, 16, 4]),
fields.InputDataFields.groundtruth_keypoint_visibilities:
tf.placeholder(tf.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__':
tf.test.main()
| [
"tensorflow.constant",
"tensorflow.resource_loader.get_data_files_path",
"tensorflow.transpose",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.test.main",
"tensorflow.placeholder",
"numpy.concatenate",
"numpy.random.rand",
"tensorflow.set_random_seed",
"numpy.array",
"tensorflow.add_to_collection",
"numpy.zeros",
"numpy.random.randint"
] | research/object_detection/inputs_test.py | [(45, 'object_detection.utils.config_util.get_configs_from_pipeline_file', 'config_util.get_configs_from_pipeline_file', (['fname'], {}), False, 'from object_detection.utils import config_util\n'), (51, 'object_detection.utils.config_util.merge_external_params_with_configs', 'config_util.merge_external_params_with_configs', (['configs'], {'kwargs_dict': 'override_dict'}), False, 'from object_detection.utils import config_util\n'), (65, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.TABLE_INITIALIZERS', 'iterator.initializer'], {}), True, 'import tensorflow as tf\n'), (150, 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["{'eval_batch_size': 1}", "{'eval_batch_size': 8}"], {}), False, 'from absl.testing import parameterized\n'), (246, 'absl.testing.parameterized.parameters', 'parameterized.parameters', (["{'eval_batch_size': 1}", "{'eval_batch_size': 8}"], {}), False, 'from absl.testing import parameterized\n'), (1147, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.resource_loader.get_data_files_path', 'tf.resource_loader.get_data_files_path', ([], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.resource_loader.get_data_files_path', 'tf.resource_loader.get_data_files_path', ([], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.resource_loader.get_data_files_path', 'tf.resource_loader.get_data_files_path', ([], {}), True, 'import tensorflow as tf\n'), (76, 'object_detection.inputs.create_train_input_fn', 'inputs.create_train_input_fn', (["configs['train_config']", "configs['train_input_config']", 'model_config'], {}), False, 'from object_detection import inputs\n'), (115, 'object_detection.inputs.create_train_input_fn', 'inputs.create_train_input_fn', (["configs['train_config']", "configs['train_input_config']", 'model_config'], {}), False, 'from object_detection import inputs\n'), (161, 'object_detection.inputs.create_eval_input_fn', 'inputs.create_eval_input_fn', (['eval_config', "configs['eval_input_configs'][0]", 'model_config'], {}), False, 'from object_detection import inputs\n'), (213, 'object_detection.inputs.create_train_input_fn', 'inputs.create_train_input_fn', (["configs['train_config']", "configs['train_input_config']", 'model_config'], {}), False, 'from object_detection import inputs\n'), (257, 'object_detection.inputs.create_eval_input_fn', 'inputs.create_eval_input_fn', (['eval_config', "configs['eval_input_configs'][0]", 'model_config'], {}), False, 'from object_detection import inputs\n'), (307, 'object_detection.inputs.create_predict_input_fn', 'inputs.create_predict_input_fn', ([], {'model_config': "configs['model']", 'predict_input_config': "configs['eval_input_configs'][0]"}), False, 'from object_detection import inputs\n'), (323, 'object_detection.inputs.create_predict_input_fn', 'inputs.create_predict_input_fn', ([], {'model_config': "configs['model']", 'predict_input_config': "configs['eval_input_configs'][0]"}), False, 'from object_detection import inputs\n'), (340, 'object_detection.inputs.create_train_input_fn', 'inputs.create_train_input_fn', ([], {'train_config': "configs['eval_config']", 'train_input_config': "configs['train_input_config']", 'model_config': "configs['model']"}), False, 'from object_detection import inputs\n'), (351, 'object_detection.inputs.create_train_input_fn', 'inputs.create_train_input_fn', ([], {'train_config': "configs['train_config']", 'train_input_config': "configs['model']", 'model_config': "configs['model']"}), False, 'from object_detection import inputs\n'), (362, 'object_detection.inputs.create_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']"}), False, 'from object_detection import inputs\n'), (373, 'object_detection.inputs.create_eval_input_fn', 'inputs.create_eval_input_fn', ([], {'eval_config': "configs['train_config']", 'eval_input_config': "configs['eval_input_configs'][0]", 'model_config': "configs['model']"}), False, 'from object_detection import inputs\n'), (384, 'object_detection.inputs.create_eval_input_fn', 'inputs.create_eval_input_fn', ([], {'eval_config': "configs['eval_config']", 'eval_input_config': "configs['model']", 'model_config': "configs['model']"}), False, 'from object_detection import inputs\n'), (395, 'object_detection.inputs.create_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']"}), False, 'from object_detection import inputs\n'), (403, 'tensorflow.placeholder', 'tf.placeholder', (['tf.string'], {'shape': '[]'}), True, 'import tensorflow as tf\n'), (404, 'object_detection.inputs._replace_empty_string_with_random_number', 'inputs._replace_empty_string_with_random_number', (['string_placeholder'], {}), False, 'from object_detection import inputs\n'), (417, 'tensorflow.placeholder', 'tf.placeholder', (['tf.string'], {'shape': '[]'}), True, 'import tensorflow as tf\n'), (418, 'object_detection.inputs._replace_empty_string_with_random_number', 'inputs._replace_empty_string_with_random_number', (['string_placeholder'], {}), False, 'from object_detection import inputs\n'), (424, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(0)'], {}), True, 'import tensorflow as tf\n'), (446, 'functools.partial', 'functools.partial', (['inputs.augment_input_data'], {'data_augmentation_options': 'data_augmentation_options'}), False, 'import functools\n'), (477, 'functools.partial', 'functools.partial', (['inputs.augment_input_data'], {'data_augmentation_options': 'data_augmentation_options'}), False, 'import functools\n'), (520, 'functools.partial', 'functools.partial', (['inputs.augment_input_data'], {'data_augmentation_options': 'data_augmentation_options'}), False, 'import functools\n'), (548, 'functools.partial', 'functools.partial', (['inputs.augment_input_data'], {'data_augmentation_options': 'data_augmentation_options'}), False, 'import functools\n'), (582, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (599, 'functools.partial', 'functools.partial', (['inputs.transform_input_data'], {'model_preprocess_fn': '_fake_model_preprocessor_fn', 'image_resizer_fn': '_fake_image_resizer_fn', 'num_classes': '(1)'}), False, 'import functools\n'), (627, 'functools.partial', '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)'}), False, 'import functools\n'), (653, 'functools.partial', '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)'}), False, 'import functools\n'), (680, 'functools.partial', 'functools.partial', (['inputs.transform_input_data'], {'model_preprocess_fn': '_fake_model_preprocessor_fn', 'image_resizer_fn': '_fake_image_resizer_fn', 'num_classes': 'num_classes'}), False, 'import functools\n'), (723, 'functools.partial', 'functools.partial', (['inputs.transform_input_data'], {'model_preprocess_fn': '_fake_model_preprocessor_fn', 'image_resizer_fn': '_fake_image_resizer_fn', 'num_classes': 'num_classes'}), False, 'import functools\n'), (773, 'functools.partial', '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)'}), False, 'import functools\n'), (808, 'functools.partial', 'functools.partial', (['inputs.transform_input_data'], {'model_preprocess_fn': '_fake_model_preprocessor_fn', 'image_resizer_fn': '_fake_image_resizer_fn', 'num_classes': 'num_classes'}), False, 'import functools\n'), (848, 'functools.partial', '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)'}), False, 'import functools\n'), (867, 'numpy.random.randint', 'np.random.randint', (['(256)'], {'size': '(4, 4, 3)'}), True, 'import numpy as np\n'), (879, 'functools.partial', 'functools.partial', (['inputs.transform_input_data'], {'model_preprocess_fn': 'fake_model_preprocessor_fn', 'image_resizer_fn': '_fake_image_resizer_fn', 'num_classes': 'num_classes'}), False, 'import functools\n'), (895, 'numpy.random.randint', 'np.random.randint', (['(256)'], {'size': '(4, 4, 3)'}), True, 'import numpy as np\n'), (907, 'functools.partial', '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'}), False, 'import functools\n'), (924, 'numpy.random.randint', 'np.random.randint', (['(256)'], {'size': '(4, 4, 3)'}), True, 'import numpy as np\n'), (940, 'functools.partial', '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'}), False, 'import functools\n'), (969, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1000, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1039, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[None, None]'}), False, 'from object_detection import inputs\n'), (1056, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1092, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1111, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1131, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (592, 'tensorflow.constant', 'tf.constant', (['image'], {}), True, 'import tensorflow as tf\n'), (594, 'tensorflow.constant', 'tf.constant', (['additional_channels'], {}), True, 'import tensorflow as tf\n'), (612, 'numpy.concatenate', 'np.concatenate', (['(image, additional_channels)'], {'axis': '(2)'}), True, 'import numpy as np\n'), (618, 'tensorflow.constant', 'tf.constant', (['image'], {}), True, 'import tensorflow as tf\n'), (637, 'numpy.array', 'np.array', (['[[0.2, 0.3, 0.5], [0.1, 0.6, 0.3]]', 'np.float32'], {}), True, 'import numpy as np\n'), (644, 'tensorflow.constant', 'tf.constant', (['image'], {}), True, 'import tensorflow as tf\n'), (648, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (667, 'numpy.array', 'np.array', (['[[0, 1, 0], [0, 0, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (713, 'tensorflow.constant', 'tf.constant', (['[True, False, True]'], {}), True, 'import tensorflow as tf\n'), (717, 'tensorflow.constant', 'tf.constant', (['[False, True, False]'], {}), True, 'import tensorflow as tf\n'), (837, 'tensorflow.image.resize_images', 'tf.image.resize_images', (['image', '[8, 8]'], {}), True, 'import tensorflow as tf\n'), (870, 'tensorflow.constant', 'tf.constant', (['np_image'], {}), True, 'import tensorflow as tf\n'), (898, 'tensorflow.constant', 'tf.constant', (['np_image'], {}), True, 'import tensorflow as tf\n'), (927, 'tensorflow.constant', 'tf.constant', (['np_image'], {}), True, 'import tensorflow as tf\n'), (959, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (961, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 4]'], {}), True, 'import tensorflow as tf\n'), (963, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, 3]'], {}), True, 'import tensorflow as tf\n'), (965, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[3]'], {}), True, 'import tensorflow as tf\n'), (967, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[2]'], {}), True, 'import tensorflow as tf\n'), (994, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 4]'], {}), True, 'import tensorflow as tf\n'), (996, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, 3]'], {}), True, 'import tensorflow as tf\n'), (998, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[]'], {}), True, 'import tensorflow as tf\n'), (1037, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (1052, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 5]'], {}), True, 'import tensorflow as tf\n'), (1054, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 2]'], {}), True, 'import tensorflow as tf\n'), (1074, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (1076, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 2]'], {}), True, 'import tensorflow as tf\n'), (1078, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (1081, 'object_detection.inputs.pad_input_data_to_static_shapes', 'inputs.pad_input_data_to_static_shapes', ([], {'tensor_dict': 'input_tensor_dict', 'max_num_boxes': '(3)', 'num_classes': '(3)', 'spatial_image_shape': '[5, 6]'}), False, 'from object_detection import inputs\n'), (1090, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 1]'], {}), True, 'import tensorflow as tf\n'), (1105, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 3]'], {}), True, 'import tensorflow as tf\n'), (1107, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, None, 2]'], {}), True, 'import tensorflow as tf\n'), (1127, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 16, 4]'], {}), True, 'import tensorflow as tf\n'), (1129, 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool', '[None, 16]'], {}), True, 'import tensorflow as tf\n'), (453, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1.0, 1.0]]', 'np.float32'], {}), True, 'import numpy as np\n'), (484, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1.0, 1.0]]', 'np.float32'], {}), True, 'import numpy as np\n'), (486, 'numpy.array', 'np.array', (['[1.0]', 'np.float32'], {}), True, 'import numpy as np\n'), (488, 'numpy.array', 'np.array', (['[0.8]', 'np.float32'], {}), True, 'import numpy as np\n'), (527, 'numpy.zeros', 'np.zeros', (['[2, 10, 10]', 'np.uint8'], {}), True, 'import numpy as np\n'), (555, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1.0, 1.0]]', 'np.float32'], {}), True, 'import numpy as np\n'), (557, 'numpy.array', 'np.array', (['[[[0.5, 1.0], [0.5, 0.5]]]', 'np.float32'], {}), True, 'import numpy as np\n'), (578, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (588, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (589, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(2)'], {}), True, 'import numpy as np\n'), (596, 'numpy.array', 'np.array', (['[1, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (615, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (620, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1, 1], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (622, 'numpy.array', 'np.array', (['[0.2, 0.3, 0.5, 0.1, 0.6, 0.3]', 'np.float32'], {}), True, 'import numpy as np\n'), (624, 'numpy.array', 'np.array', (['[1, 2]', 'np.int32'], {}), True, 'import numpy as np\n'), (641, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (646, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1, 1], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (650, 'numpy.array', 'np.array', (['[1, 2]', 'np.int32'], {}), True, 'import numpy as np\n'), (675, 'numpy.array', 'np.array', (['[[0, 0, 1, 1], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (677, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (702, 'numpy.array', 'np.array', (['[[0, 0, 1, 1], [0.2, 0.2, 4, 4], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (705, 'numpy.array', 'np.array', (['[0.5, 0.4, 0.3]'], {}), True, 'import numpy as np\n'), (707, 'numpy.array', 'np.array', (['[3, -1, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (710, 'numpy.array', 'np.array', (['[[[0.1, 0.1]], [[0.2, 0.2]], [[0.5, 0.5]]]', 'np.float32'], {}), True, 'import numpy as np\n'), (719, 'numpy.array', 'np.array', (['[0, 0, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (767, 'numpy.array', 'np.array', (['[[0.5, 0.5, 1, 1], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (769, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (801, 'numpy.array', 'np.array', (['[[0, 0, 1, 1], [0.5, 0.5, 1, 1]]', 'np.float32'], {}), True, 'import numpy as np\n'), (803, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (805, 'numpy.array', 'np.array', (['[1.0, -1.0]', 'np.float32'], {}), True, 'import numpy as np\n'), (831, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (833, 'numpy.array', 'np.array', (['[4, 4]', 'np.int32'], {}), True, 'import numpy as np\n'), (844, 'tensorflow.shape', 'tf.shape', (['resized_image'], {}), True, 'import tensorflow as tf\n'), (872, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (900, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (929, 'numpy.array', 'np.array', (['[3, 1]', 'np.int32'], {}), True, 'import numpy as np\n'), (451, 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), True, 'import numpy as np\n'), (482, 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), True, 'import numpy as np\n'), (525, 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), True, 'import numpy as np\n'), (553, 'numpy.random.rand', 'np.random.rand', (['(10)', '(10)', '(3)'], {}), True, 'import numpy as np\n'), (663, 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (673, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (699, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (715, 'numpy.random.rand', 'np.random.rand', (['(3)', '(4)', '(4)'], {}), True, 'import numpy as np\n'), (765, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (799, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (827, 'numpy.random.rand', 'np.random.rand', (['(4)', '(4)', '(3)'], {}), True, 'import numpy as np\n'), (829, 'numpy.random.rand', 'np.random.rand', (['(2)', '(4)', '(4)'], {}), True, 'import numpy as np\n'), (841, 'tensorflow.transpose', 'tf.transpose', (['masks', '[1, 2, 0]'], {}), True, 'import tensorflow as tf\n'), (876, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (933, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (1018, 'numpy.random.rand', 'np.random.rand', (['(5)', '(4)'], {}), True, 'import numpy as np\n'), (1020, 'numpy.random.rand', 'np.random.rand', (['(2)', '(3)'], {}), True, 'import numpy as np\n')] |
vincentcheny/models | afb1a59fc1bc792ac72d1a3e22e2469020529788 | # Copyright 2017 The TensorFlow 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 tensorflow 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 = tf.random_uniform([32, 32, 3], dtype=tf.float32)
key = tf.constant('image_000000')
class_label = tf.random_uniform(
[1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=tf.int32)
box_label = tf.random_uniform(
[1, 4], minval=0.4, maxval=0.6, dtype=tf.float32)
multiclass_scores = tf.random_uniform(
[1, NUMBER_OF_CLASSES], minval=0.4, maxval=0.6, dtype=tf.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 tf.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 = tf.contrib.layers.flatten(preprocessed_inputs)
class_prediction = tf.contrib.layers.fully_connected(
flattened_inputs, self._num_classes)
box_prediction = tf.contrib.layers.fully_connected(flattened_inputs, 4)
return {
'class_predictions_with_background': tf.reshape(
class_prediction, [-1, 1, self._num_classes]),
'box_encodings': tf.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 = tf.stack(
self.groundtruth_lists(fields.BoxListFields.boxes))
batch_cls_targets = tf.stack(
self.groundtruth_lists(fields.BoxListFields.classes))
weights = tf.constant(
1.0, dtype=tf.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': tf.reduce_sum(location_losses),
'classification_loss': tf.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 tf.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(tf.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__':
tf.test.main()
| [
"tensorflow.constant",
"tensorflow.image.resize_images",
"tensorflow.reduce_sum",
"tensorflow.reshape",
"tensorflow.global_variables",
"tensorflow.test.main",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.contrib.layers.flatten",
"tensorflow.random_uniform"
] | research/object_detection/legacy/trainer_test.py | [(34, 'tensorflow.random_uniform', 'tf.random_uniform', (['[32, 32, 3]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.constant', 'tf.constant', (['"""image_000000"""'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.random_uniform', 'tf.random_uniform', (['[1]'], {'minval': '(0)', 'maxval': 'NUMBER_OF_CLASSES', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, 4]'], {'minval': '(0.4)', 'maxval': '(0.6)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.random_uniform', 'tf.random_uniform', (['[1, NUMBER_OF_CLASSES]'], {'minval': '(0.4)', 'maxval': '(0.6)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (57, 'object_detection.core.losses.WeightedSigmoidClassificationLoss', 'losses.WeightedSigmoidClassificationLoss', ([], {}), False, 'from object_detection.core import losses\n'), (58, 'object_detection.core.losses.WeightedSmoothL1LocalizationLoss', 'losses.WeightedSmoothL1LocalizationLoss', ([], {}), False, 'from object_detection.core import losses\n'), (92, 'tensorflow.contrib.layers.flatten', 'tf.contrib.layers.flatten', (['preprocessed_inputs'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', (['flattened_inputs', 'self._num_classes'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.contrib.layers.fully_connected', 'tf.contrib.layers.fully_connected', (['flattened_inputs', '(4)'], {}), True, 'import tensorflow as tf\n'), (227, 'object_detection.protos.train_pb2.TrainConfig', 'train_pb2.TrainConfig', ([], {}), False, 'from object_detection.protos import train_pb2\n'), (228, 'google.protobuf.text_format.Merge', 'text_format.Merge', (['train_config_text_proto', 'train_config'], {}), False, 'from google.protobuf import text_format\n'), (232, 'object_detection.legacy.trainer.train', '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'}), False, 'from object_detection.legacy import trainer\n'), (271, 'object_detection.protos.train_pb2.TrainConfig', 'train_pb2.TrainConfig', ([], {}), False, 'from object_detection.protos import train_pb2\n'), (272, 'google.protobuf.text_format.Merge', 'text_format.Merge', (['train_config_text_proto', 'train_config'], {}), False, 'from google.protobuf import text_format\n'), (276, 'object_detection.legacy.trainer.train', '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'}), False, 'from object_detection.legacy import trainer\n'), (76, 'tensorflow.image.resize_images', 'tf.image.resize_images', (['inputs', '[28, 28]'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.reshape', 'tf.reshape', (['class_prediction', '[-1, 1, self._num_classes]'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.reshape', 'tf.reshape', (['box_prediction', '[-1, 1, 4]'], {}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['location_losses'], {}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['cls_losses'], {}), True, 'import tensorflow as tf\n'), (186, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n')] |
mkulariya1/tefla | 8de25c1b67dcf025535f5e8c40539de59acd7fb8 | # -------------------------------------------------------------------#
# Written by Mrinal Haloi
# Contact: mrinal.haloi11@gmail.com
# Copyright 2016, Mrinal Haloi
# -------------------------------------------------------------------#
import numpy as np
import tensorflow as tf
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 = tf.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 tf.name_scope(name):
predictions = tf.to_float(predictions)
labels = tf.to_float(labels)
predictions = tf.clip_by_value(predictions, eps, 1 - eps)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
loss = -tf.reduce_mean(labels * tf.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 tf.name_scope(name):
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
predictions = tf.to_float(predictions)
labels = tf.to_float(labels)
losses = -tf.multiply(labels, tf.log(predictions + eps)) - tf.multiply(
(1 - labels), tf.log(1 - predictions + eps))
return tf.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 tf.name_scope(name):
labels = tf.to_float(labels)
repeat_op = tf.to_float(
tf.tile(tf.reshape(tf.range(0, num_ratings), [num_ratings, 1]), [1, num_ratings]))
repeat_op_sq = tf.square((repeat_op - tf.transpose(repeat_op)))
weights = repeat_op_sq / tf.to_float((num_ratings - 1)**2)
pred_ = predictions**y_pow
try:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [-1, 1]))
except Exception:
pred_norm = pred_ / \
(eps + tf.reshape(tf.reduce_sum(pred_, 1), [batch_size, 1]))
hist_rater_a = tf.reduce_sum(pred_norm, 0)
hist_rater_b = tf.reduce_sum(labels, 0)
conf_mat = tf.matmul(tf.transpose(pred_norm), labels)
nom = tf.reduce_sum(weights * conf_mat)
denom = tf.reduce_sum(weights * tf.matmul(
tf.reshape(hist_rater_a, [num_ratings, 1]), tf.reshape(hist_rater_b, [1, num_ratings])) /
tf.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 tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.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 tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.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 * tf.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 tf.name_scope(name):
num_classes = labels.get_shape()[-1].value
labels = tf.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 = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels, name='xentropy')
weight = tf.convert_to_tensor(weight, dtype=logits.dtype.base_dtype, name='loss_weight')
loss = tf.multiply(weight, tf.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 tf.name_scope(name):
weight_l1_t = tf.convert_to_tensor(weight_l1, dtype=var.dtype.base_dtype, name='weight_l1')
weight_l2_t = tf.convert_to_tensor(weight_l2, dtype=var.dtype.base_dtype, name='weight_l2')
reg_l1 = tf.multiply(weight_l1_t, tf.reduce_sum(tf.abs(var)), name='value_l1')
reg_l2 = tf.multiply(weight_l2_t, tf.nn.l2_loss(var), name='value_l2')
return tf.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 tf.name_scope(name):
my_scale = tf.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale')
return tf.multiply(my_scale, tf.reduce_sum(tf.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 tf.name_scope(name):
my_scale = tf.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale')
return tf.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 tf.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 = tf.reshape(predictions[:, :, :, nr_mix:], inputs_shape + [nr_mix * 3])
means = predictions[:, :, :, :, :nr_mix]
log_scales = tf.maximum(predictions[:, :, :, :, nr_mix:2 * nr_mix], -7.)
coeffs = tf.nn.tanh(predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix])
inputs = tf.reshape(inputs, inputs_shape + [1]) + tf.zeros(inputs_shape + [nr_mix])
m2 = tf.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :] * inputs[:, :, :, 0, :],
[inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix])
m3 = tf.reshape(
means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * inputs[:, :, :, 0, :] +
coeffs[:, :, :, 2, :] * inputs[:, :, :, 1, :],
[inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix])
means = tf.concat([
tf.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 = tf.exp(-log_scales)
plus_in = inv_stdv * (centered_inputs + 1. / 255.)
cdf_plus = tf.nn.sigmoid(plus_in)
min_in = inv_stdv * (centered_inputs - 1. / 255.)
cdf_min = tf.nn.sigmoid(min_in)
log_cdf_plus = plus_in - tf.nn.softplus(plus_in)
log_one_minus_cdf_min = -tf.nn.softplus(min_in)
cdf_delta = cdf_plus - cdf_min
mid_in = inv_stdv * centered_inputs
log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in)
log_probs = tf.select(
inputs < -0.999, log_cdf_plus,
tf.select(
inputs > 0.999, log_one_minus_cdf_min,
tf.select(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)),
log_pdf_mid - np.log(127.5))))
log_probs = tf.reduce_sum(log_probs, 3) + \
log_prob_from_logits(logit_probs)
if sum_all:
return -tf.reduce_sum(log_sum_exp(log_probs))
else:
return -tf.reduce_sum(log_sum_exp(log_probs), [1, 2])
def mse_loss(pred, labels):
try:
batch_size = tf.cast(pred.shape[0], tf.float32)
except Exception as e:
print('Pred is a tf tensor %s' % str(e.message))
batch_size = tf.cast(tf.shape(pred)[0], tf.float32)
loss_val = tf.sqrt(2 * tf.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 tf.name_scope(name):
norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
normalized_embeddings = embeddings / norm
similarity = tf.matmul(normalized_embeddings, normalized_embeddings, transpose_b=True)
batch_size = tf.cast(tf.shape(embeddings)[0], tf.float32)
pt_loss = (tf.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 = tf.reduce_max(x, axis)
m2 = tf.reduce_max(x, axis, keep_dims=True)
return m + tf.log(tf.reduce_sum(tf.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 = tf.reduce_max(x, axis, keep_dims=True)
return x - m - tf.log(tf.reduce_sum(tf.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 tf.name_scope('segment_loss'):
# logits = tf.reshape(logits, (-1, num_classes))
epsilon = tf.constant(value=1e-7)
labels = tf.to_float(labels)
# labels = tf.to_float(tf.reshape(labels, (-1, num_classes)))
softmax = tf.nn.softmax(logits) + epsilon
if head is not None:
cross_entropy = -tf.reduce_sum(tf.mul(labels * tf.log(softmax), head), axis=[1])
else:
cross_entropy = -tf.reduce_sum(labels * tf.log(softmax), axis=[1])
cross_entropy_mean = tf.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 tf.name_scope(name):
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
loss = tf.reduce_mean(tf.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 tf.name_scope(name):
x = tf.reshape(xs, [int(xs.get_shape()[0]), -1])
m = tf.reduce_mean(x, 0, True)
z = tf.expand_dims(x - m, 2)
corr = tf.reduce_mean(tf.matmul(z, tf.transpose(z, perm=[0, 2, 1])), 0)
corr_frob_sqr = tf.reduce_sum(tf.square(corr))
corr_diag_sqr = tf.reduce_sum(tf.square(tf.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 tf.variable_scope(name):
num_features = features.get_shape()[1]
centers = tf.get_variable(
'centers', [num_classes, num_features],
dtype=tf.float32,
initializer=tf.constant_initializer(0),
trainable=False)
label = tf.reshape(label, [-1])
centers_batch = tf.gather(centers, label)
diff = (1 - alpha) * (centers_batch - features)
centers = tf.scatter_sub(centers, label, diff)
loss = tf.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 tf.name_scope(name):
source_samples -= tf.reduce_mean(source_samples, 0)
target_samples -= tf.reduce_mean(target_samples, 0)
source_samples = tf.nn.l2_normalize(source_samples, 1)
target_samples = tf.nn.l2_normalize(target_samples, 1)
source_cov = tf.matmul(tf.transpose(source_samples), source_samples)
target_cov = tf.matmul(tf.transpose(target_samples), target_samples)
corr_loss = tf.reduce_mean(tf.square(source_cov - target_cov)) * weight
assert_op = tf.Assert(tf.is_finite(corr_loss), [corr_loss])
with tf.control_dependencies([assert_op]):
tag = 'Correlation Loss'
barrier = tf.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 tf.name_scope(name):
# \E{ K(x, x) } + \E{ K(y, y) } - 2 \E{ K(x, y) }
cost = tf.reduce_mean(kernel(x, x))
cost += tf.reduce_mean(kernel(y, y))
cost -= 2 * tf.reduce_mean(kernel(x, y))
# We do not allow the loss to become negative.
cost = tf.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 tf.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=tf.constant(sigmas))
loss_value = maximum_mean_discrepancy(source_samples, target_samples, kernel=gaussian_kernel)
loss_value = tf.maximum(1e-4, loss_value) * weight
assert_op = tf.Assert(tf.is_finite(loss_value), [loss_value])
with tf.control_dependencies([assert_op]):
tag = 'MMD_Loss'
barrier = tf.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 tf.variable_scope(name):
batch_size = tf.shape(source_samples)[0]
samples = tf.concat(values=[source_samples, target_samples], axis=0)
samples = flatten(samples)
domain_selection_mask = tf.concat(
values=[tf.zeros((batch_size, 1)), tf.ones((batch_size, 1))], axis=0)
grl = gradient_reverse(samples)
grl = tf.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 = tf.sigmoid(logits)
domain_loss = tf.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight)
domain_accuracy = util.accuracy_tf(domain_selection_mask, tf.round(domain_predictions))
assert_op = tf.Assert(tf.is_finite(domain_loss), [domain_loss])
with tf.control_dependencies([assert_op]):
tag_loss = 'losses/domain_loss'
barrier = tf.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 tf.name_scope(name):
private_samples -= tf.reduce_mean(private_samples, 0)
shared_samples -= tf.reduce_mean(shared_samples, 0)
private_samples = tf.nn.l2_normalize(private_samples, 1)
shared_samples = tf.nn.l2_normalize(shared_samples, 1)
correlation_matrix = tf.matmul(private_samples, shared_samples, transpose_a=True)
cost = tf.reduce_mean(tf.square(correlation_matrix)) * weight
cost = tf.where(cost > 0, cost, 0, name='value')
assert_op = tf.Assert(tf.is_finite(cost), [cost])
with tf.control_dependencies([assert_op]):
barrier = tf.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(
tf.Assert(
tf.reduce_all(tf.less(tf.abs(tf.reduce_sum(tf.square(predictions), [1]) - 1), 1e-4)),
['The l2 norm of each prediction quaternion vector should be 1.']))
assertions.append(
tf.Assert(
tf.reduce_all(tf.less(tf.abs(tf.reduce_sum(tf.square(labels), [1]) - 1), 1e-4)),
['The l2 norm of each label quaternion vector should be 1.']))
with tf.name_scope(name):
with tf.control_dependencies(assertions):
product = tf.multiply(predictions, labels)
internal_dot_products = tf.reduce_sum(product, [1])
logcost = tf.log(1e-4 + 1 - tf.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 tf.name_scope(name):
logcost = log_quaternion_loss_batch(predictions, labels)
logcost = tf.reduce_sum(logcost, [0])
logcost = tf.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 = tf.random_normal(shape=tf.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, = tf.gradients(
loss, embedded, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
grad = tf.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 = tf.stop_gradient(logits)
weights = _end_of_seq_mask(labels, vocab_size)
d = _mask_by_length(tf.random_normal(shape=tf.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, = tf.gradients(kl, d, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
d = tf.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 = [tf.random_normal(shape=tf.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 = tf.gradients(
loss, embedded, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
adv_exs = [
emb + _scale_l2(tf.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 = tf.stop_gradient(logits)
weights = _end_of_seq_mask(labels, vocab_size)
perturbs = [_mask_by_length(tf.random_normal(shape=tf.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 = tf.gradients(
kl, perturbs, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N)
perturbs = [tf.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 = tf.sequence_mask(length, maxlen=maxlen)
mask = tf.expand_dims(tf.cast(mask, tf.float32), -1)
return t * mask
def _scale_l2(x, norm_length):
alpha = tf.reduce_max(tf.abs(x), (1, 2), keep_dims=True) + 1e-12
l2_norm = alpha * tf.sqrt(tf.reduce_sum(tf.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 tf.cast(tf.equal(tokens, eos_id), tf.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 = tf.nn.sigmoid(q_logits)
p = tf.nn.sigmoid(p_logits)
kl = (-tf.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 = tf.nn.softmax(q_logits)
p = tf.nn.softmax(p_logits)
kl = tf.reduce_sum(q * (tf.log(q) - tf.log(p)), 1)
num_labels = tf.reduce_sum(weights)
num_labels = tf.where(tf.equal(num_labels, 0.), 1., num_labels)
kl.get_shape().assert_has_rank(2)
weights.get_shape().assert_has_rank(1)
loss = tf.identity(tf.reduce_sum(tf.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 tf.name_scope("cross_entropy_sequence_loss"):
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets)
loss_mask = tf.sequence_mask(tf.to_int32(sequence_length), tf.to_int32(tf.shape(targets)[0]))
losses = losses * tf.transpose(tf.to_float(loss_mask), [1, 0])
return losses
def dice_loss(predictions, targets, weights=1., name='dice_loss'):
with tf.name_scope(name):
# predictions = tf.to_float(predictions)
targets = tf.to_float(targets)
intersection = 2 * tf.reduce_sum(predictions * targets) + weights
union = weights + tf.reduce_sum(predictions) + tf.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=tf.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 `tf.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 tf.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 = tf.contrib.framework.model_variable(
name='biases',
shape=[1, num_labels, num_anchors],
dtype=logits.dtype,
initializer=tf.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 = tf.reshape(label_priors, [1, num_labels, 1])
# Expand logits, labels, and weights to shape [batch_size, num_labels, 1].
logits = tf.expand_dims(logits, 2)
labels = tf.expand_dims(labels, 2)
weights = tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.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 * tf.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 = tf.div(
per_label_loss, precision_range[1] - precision_range[0] - delta, name='AUC_Normalize')
scaled_loss = tf.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 tf.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 = tf.expand_dims(logits, 0) - tf.expand_dims(logits, 1)
labels_difference = tf.expand_dims(labels, 0) - tf.expand_dims(labels, 1)
weights_product = tf.expand_dims(weights, 0) * tf.expand_dims(weights, 1)
signed_logits_difference = labels_difference * logits_difference
raw_loss = losses_utils.weighted_surrogate_loss(
labels=tf.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 = tf.reduce_mean(tf.abs(labels_difference) * weighted_loss, 0) * 0.5
loss = tf.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=tf.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 `tf.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 tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
lambda_term = lambdas * (1.0 - target_precision) * label_priors * maybe_log2
loss = tf.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=tf.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 `tf.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 tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
lambda_term = lambdas * label_priors * (target_recall - 1.0) * maybe_log2
loss = tf.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=tf.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 `tf.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=tf.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 `tf.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 tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
lambda_term = lambdas * target_rate * (1.0 - label_priors) * maybe_log2
loss = tf.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 = tf.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 = tf.reshape(labels, [-1, 1])
logits = tf.reshape(logits, [-1, 1])
if weights.get_shape().ndims == 1:
# Weights has shape [batch_size]. Reshape to [batch_size, 1].
weights = tf.reshape(weights, [-1, 1])
if weights.get_shape().ndims == 0:
# Weights is a scalar. Change shape of weights to match logits.
weights *= tf.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 = tf.get_variable_scope().partitioner
try:
tf.get_variable_scope().set_partitioner(None)
dual_variable = tf.contrib.framework.model_variable(
name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
collections=collections,
trainable=trainable)
finally:
tf.get_variable_scope().set_partitioner(partitioner)
# Using the absolute value enforces nonnegativity.
dual_value = tf.abs(dual_variable)
if trainable:
# To reverse the gradient on the dual variable, multiply the gradient by
# -dual_rate_factor
dual_value = (tf.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 tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype)
if logits.get_shape().ndims == 3 and labels.get_shape().ndims < 3:
labels = tf.expand_dims(labels, 2)
loss_on_positives = losses_utils.weighted_surrogate_loss(
labels, logits, surrogate_type, negative_weights=0.0) / maybe_log2
return tf.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 = tf.log(2.0) if surrogate_type == 'xent' else 1.0
maybe_log2 = tf.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 tf.reduce_sum(weights * loss_on_negatives, 0)
| [
"tensorflow.convert_to_tensor",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.concat",
"tensorflow.is_finite",
"tensorflow.control_dependencies",
"tensorflow.scatter_sub",
"tensorflow.reduce_sum",
"numpy.linspace",
"tensorflow.cast",
"tensorflow.equal",
"tensorflow.zeros",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.nn.l2_loss",
"tensorflow.where",
"tensorflow.losses.log_loss",
"tensorflow.to_int32",
"tensorflow.diag_part",
"tensorflow.gradients",
"tensorflow.squeeze",
"tensorflow.stop_gradient",
"tensorflow.losses.compute_weighted_loss",
"tensorflow.gather",
"tensorflow.div",
"tensorflow.subtract",
"tensorflow.add",
"tensorflow.name_scope",
"tensorflow.to_float",
"tensorflow.square",
"tensorflow.nn.softplus",
"tensorflow.nn.l2_normalize",
"tensorflow.matmul",
"numpy.log",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"tensorflow.pow",
"tensorflow.zeros_initializer",
"tensorflow.exp",
"tensorflow.nn.tanh",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.no_op",
"tensorflow.round",
"tensorflow.sequence_mask",
"tensorflow.clip_by_value",
"tensorflow.reduce_max",
"tensorflow.multiply",
"tensorflow.constant",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.range",
"tensorflow.maximum",
"tensorflow.reshape",
"tensorflow.sigmoid",
"tensorflow.expand_dims",
"tensorflow.ones_like",
"tensorflow.contrib.framework.model_variable",
"tensorflow.constant_initializer",
"tensorflow.ones",
"tensorflow.log",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope",
"tensorflow.abs"
] | tefla/core/losses.py | [(56, 'tensorflow.losses.compute_weighted_loss', 'tf.losses.compute_weighted_loss', (['losses', 'weights'], {}), True, 'import tensorflow as tf\n'), (396, 'tensorflow.reduce_max', 'tf.reduce_max', (['x', 'axis'], {}), True, 'import tensorflow as tf\n'), (397, 'tensorflow.reduce_max', 'tf.reduce_max', (['x', 'axis'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (404, 'tensorflow.reduce_max', 'tf.reduce_max', (['x', 'axis'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (632, 'tensorflow.losses.log_loss', 'tf.losses.log_loss', (['domain_selection_mask', 'domain_predictions'], {'weights': 'weight'}), True, 'import tensorflow as tf\n'), (751, 'tensorflow.gradients', 'tf.gradients', (['loss', 'embedded'], {'aggregation_method': 'tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N'}), True, 'import tensorflow as tf\n'), (753, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['grad'], {}), True, 'import tensorflow as tf\n'), (789, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['logits'], {}), True, 'import tensorflow as tf\n'), (840, 'tensorflow.gradients', 'tf.gradients', (['loss', 'embedded'], {'aggregation_method': 'tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N'}), True, 'import tensorflow as tf\n'), (881, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['logits'], {}), True, 'import tensorflow as tf\n'), (889, 'tensorflow.gradients', 'tf.gradients', (['kl', 'perturbs'], {'aggregation_method': 'tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N'}), True, 'import tensorflow as tf\n'), (900, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['length'], {'maxlen': 'maxlen'}), True, 'import tensorflow as tf\n'), (954, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['weights'], {}), True, 'import tensorflow as tf\n'), (1002, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (1195, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (1317, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (1429, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (1511, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (1642, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['logits'], {'name': '"""logits"""'}), True, 'import tensorflow as tf\n'), (1735, 'tensorflow.abs', 'tf.abs', (['dual_variable'], {}), True, 'import tensorflow as tf\n'), (1784, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1789, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(weights * (labels - loss_on_positives))', '(0)'], {}), True, 'import tensorflow as tf\n'), (1809, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1812, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(weights * loss_on_negatives)', '(0)'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.to_float', 'tf.to_float', (['predictions'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.to_float', 'tf.to_float', (['labels'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['predictions', 'eps', '(1 - eps)'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.to_float', 'tf.to_float', (['predictions'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.to_float', 'tf.to_float', (['labels'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.to_float', 'tf.to_float', (['labels'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['pred_norm', '(0)'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['labels', '(0)'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(weights * conf_mat)'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.cast', 'tf.cast', (['labels', 'predictions.dtype'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.cast', 'tf.cast', (['labels', 'predictions.dtype'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.cast', 'tf.cast', (['labels', 'logits.dtype'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'labels', 'name': '"""xentropy"""'}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['weight'], {'dtype': 'logits.dtype.base_dtype', 'name': '"""loss_weight"""'}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['weight_l1'], {'dtype': 'var.dtype.base_dtype', 'name': '"""weight_l1"""'}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['weight_l2'], {'dtype': 'var.dtype.base_dtype', 'name': '"""weight_l2"""'}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.add', 'tf.add', (['reg_l1', 'reg_l2'], {'name': '"""value"""'}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (322, 'tensorflow.reshape', 'tf.reshape', (['predictions[:, :, :, nr_mix:]', '(inputs_shape + [nr_mix * 3])'], {}), True, 'import tensorflow as tf\n'), (324, 'tensorflow.maximum', 'tf.maximum', (['predictions[:, :, :, :, nr_mix:2 * nr_mix]', '(-7.0)'], {}), True, 'import tensorflow as tf\n'), (325, 'tensorflow.nn.tanh', 'tf.nn.tanh', (['predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix]'], {}), True, 'import tensorflow as tf\n'), (327, 'tensorflow.reshape', 'tf.reshape', (['(means[:, :, :, (1), :] + coeffs[:, :, :, (0), :] * inputs[:, :, :, (0), :])', '[inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]'], {}), True, 'import tensorflow as tf\n'), (329, 'tensorflow.reshape', 'tf.reshape', (['(means[:, :, :, (2), :] + coeffs[:, :, :, (1), :] * inputs[:, :, :, (0), :] +\n coeffs[:, :, :, (2), :] * inputs[:, :, :, (1), :])', '[inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]'], {}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.exp', 'tf.exp', (['(-log_scales)'], {}), True, 'import tensorflow as tf\n'), (341, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['plus_in'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['min_in'], {}), True, 'import tensorflow as tf\n'), (366, 'tensorflow.cast', 'tf.cast', (['pred.shape[0]', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (383, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (386, 'tensorflow.matmul', 'tf.matmul', (['normalized_embeddings', 'normalized_embeddings'], {'transpose_b': '(True)'}), True, 'import tensorflow as tf\n'), (423, 'tensorflow.name_scope', 'tf.name_scope', (['"""segment_loss"""'], {}), True, 'import tensorflow as tf\n'), (425, 'tensorflow.constant', 'tf.constant', ([], {'value': '(1e-07)'}), True, 'import tensorflow as tf\n'), (426, 'tensorflow.to_float', 'tf.to_float', (['labels'], {}), True, 'import tensorflow as tf\n'), (436, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['cross_entropy'], {'name': '"""xentropy_mean"""'}), True, 'import tensorflow as tf\n'), (452, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (470, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (472, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x', '(0)', '(True)'], {}), True, 'import tensorflow as tf\n'), (473, 'tensorflow.expand_dims', 'tf.expand_dims', (['(x - m)', '(2)'], {}), True, 'import tensorflow as tf\n'), (494, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (501, 'tensorflow.reshape', 'tf.reshape', (['label', '[-1]'], {}), True, 'import tensorflow as tf\n'), (502, 'tensorflow.gather', 'tf.gather', (['centers', 'label'], {}), True, 'import tensorflow as tf\n'), (504, 'tensorflow.scatter_sub', 'tf.scatter_sub', (['centers', 'label', 'diff'], {}), True, 'import tensorflow as tf\n'), (505, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(features - centers_batch)'], {}), True, 'import tensorflow as tf\n'), (521, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (522, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['source_samples', '(0)'], {}), True, 'import tensorflow as tf\n'), (523, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['target_samples', '(0)'], {}), True, 'import tensorflow as tf\n'), (524, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['source_samples', '(1)'], {}), True, 'import tensorflow as tf\n'), (525, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['target_samples', '(1)'], {}), True, 'import tensorflow as tf\n'), (530, 'tensorflow.is_finite', 'tf.is_finite', (['corr_loss'], {}), True, 'import tensorflow as tf\n'), (531, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[assert_op]'], {}), True, 'import tensorflow as tf\n'), (533, 'tensorflow.no_op', 'tf.no_op', (['tag'], {}), True, 'import tensorflow as tf\n'), (563, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (570, 'tensorflow.where', 'tf.where', (['(cost > 0)', 'cost', '(0)'], {'name': '"""value"""'}), True, 'import tensorflow as tf\n'), (589, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (597, 'tensorflow.is_finite', 'tf.is_finite', (['loss_value'], {}), True, 'import tensorflow as tf\n'), (598, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[assert_op]'], {}), True, 'import tensorflow as tf\n'), (600, 'tensorflow.no_op', 'tf.no_op', (['tag'], {}), True, 'import tensorflow as tf\n'), (616, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (618, 'tensorflow.concat', 'tf.concat', ([], {'values': '[source_samples, target_samples]', 'axis': '(0)'}), True, 'import tensorflow as tf\n'), (630, 'tensorflow.sigmoid', 'tf.sigmoid', (['logits'], {}), True, 'import tensorflow as tf\n'), (634, 'tensorflow.round', 'tf.round', (['domain_predictions'], {}), True, 'import tensorflow as tf\n'), (636, 'tensorflow.is_finite', 'tf.is_finite', (['domain_loss'], {}), True, 'import tensorflow as tf\n'), (637, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[assert_op]'], {}), True, 'import tensorflow as tf\n'), (639, 'tensorflow.no_op', 'tf.no_op', (['tag_loss'], {}), True, 'import tensorflow as tf\n'), (653, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (654, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['private_samples', '(0)'], {}), True, 'import tensorflow as tf\n'), (655, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['shared_samples', '(0)'], {}), True, 'import tensorflow as tf\n'), (657, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['private_samples', '(1)'], {}), True, 'import tensorflow as tf\n'), (658, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['shared_samples', '(1)'], {}), True, 'import tensorflow as tf\n'), (660, 'tensorflow.matmul', 'tf.matmul', (['private_samples', 'shared_samples'], {'transpose_a': '(True)'}), True, 'import tensorflow as tf\n'), (663, 'tensorflow.where', 'tf.where', (['(cost > 0)', 'cost', '(0)'], {'name': '"""value"""'}), True, 'import tensorflow as tf\n'), (665, 'tensorflow.is_finite', 'tf.is_finite', (['cost'], {}), True, 'import tensorflow as tf\n'), (666, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[assert_op]'], {}), True, 'import tensorflow as tf\n'), (667, 'tensorflow.no_op', 'tf.no_op', (['name'], {}), True, 'import tensorflow as tf\n'), (691, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (694, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['product', '[1]'], {}), True, 'import tensorflow as tf\n'), (713, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (715, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['logcost', '[0]'], {}), True, 'import tensorflow as tf\n'), (716, 'tensorflow.multiply', 'tf.multiply', (['logcost', '(1.0 / batch_size)'], {'name': '"""log_quaternion_loss"""'}), True, 'import tensorflow as tf\n'), (798, 'tensorflow.gradients', 'tf.gradients', (['kl', 'd'], {'aggregation_method': 'tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N'}), True, 'import tensorflow as tf\n'), (799, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['d'], {}), True, 'import tensorflow as tf\n'), (891, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['d'], {}), True, 'import tensorflow as tf\n'), (901, 'tensorflow.cast', 'tf.cast', (['mask', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (925, 'tensorflow.equal', 'tf.equal', (['tokens', 'eos_id'], {}), True, 'import tensorflow as tf\n'), (944, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['q_logits'], {}), True, 'import tensorflow as tf\n'), (945, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['p_logits'], {}), True, 'import tensorflow as tf\n'), (950, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['q_logits'], {}), True, 'import tensorflow as tf\n'), (951, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['p_logits'], {}), True, 'import tensorflow as tf\n'), (955, 'tensorflow.equal', 'tf.equal', (['num_labels', '(0.0)'], {}), True, 'import tensorflow as tf\n'), (976, 'tensorflow.name_scope', 'tf.name_scope', (['"""cross_entropy_sequence_loss"""'], {}), True, 'import tensorflow as tf\n'), (977, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'targets'}), True, 'import tensorflow as tf\n'), (985, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (987, 'tensorflow.to_float', 'tf.to_float', (['targets'], {}), True, 'import tensorflow as tf\n'), (1065, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""precision_recall_auc"""', '[labels, logits, label_priors]'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (1094, 'tensorflow.reshape', 'tf.reshape', (['label_priors', '[1, num_labels, 1]'], {}), True, 'import tensorflow as tf\n'), (1097, 'tensorflow.expand_dims', 'tf.expand_dims', (['logits', '(2)'], {}), True, 'import tensorflow as tf\n'), (1098, 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(2)'], {}), True, 'import tensorflow as tf\n'), (1099, 'tensorflow.expand_dims', 'tf.expand_dims', (['weights', '(2)'], {}), True, 'import tensorflow as tf\n'), (1110, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1119, 'tensorflow.div', 'tf.div', (['per_label_loss', '(precision_range[1] - precision_range[0] - delta)'], {'name': '"""AUC_Normalize"""'}), True, 'import tensorflow as tf\n'), (1121, 'tensorflow.reshape', 'tf.reshape', (['scaled_loss', 'original_shape'], {}), True, 'import tensorflow as tf\n'), (1163, 'tensorflow.name_scope', 'tf.name_scope', (['scope', '"""roc_auc"""', '[labels, logits, weights]'], {}), True, 'import tensorflow as tf\n'), (1184, 'tensorflow.reshape', 'tf.reshape', (['loss', 'original_shape'], {}), True, 'import tensorflow as tf\n'), (1262, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""recall_at_precision"""', '[logits, labels, label_priors]'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (1293, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1295, 'tensorflow.reshape', 'tf.reshape', (['(weighted_loss - lambda_term)', 'original_shape'], {}), True, 'import tensorflow as tf\n'), (1379, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""precision_at_recall"""', '[logits, labels, label_priors]'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (1405, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1407, 'tensorflow.reshape', 'tf.reshape', (['(weighted_loss + lambda_term)', 'original_shape'], {}), True, 'import tensorflow as tf\n'), (1576, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""tpr_at_fpr"""', '[labels, logits, label_priors]'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (1606, 'tensorflow.cast', 'tf.cast', (['maybe_log2', 'logits.dtype.base_dtype'], {}), True, 'import tensorflow as tf\n'), (1608, 'tensorflow.reshape', 'tf.reshape', (['(weighted_loss - lambda_term)', 'original_shape'], {}), True, 'import tensorflow as tf\n'), (1656, 'tensorflow.reshape', 'tf.reshape', (['labels', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (1657, 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (1661, 'tensorflow.reshape', 'tf.reshape', (['weights', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (1664, 'tensorflow.ones_like', 'tf.ones_like', (['logits'], {}), True, 'import tensorflow as tf\n'), (1690, 'numpy.linspace', 'np.linspace', ([], {'start': 'precision_range[0]', 'stop': 'precision_range[1]', 'num': '(num_anchors + 2)'}), True, 'import numpy as np\n'), (1722, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (1725, 'tensorflow.contrib.framework.model_variable', 'tf.contrib.framework.model_variable', ([], {'name': 'name', 'shape': 'shape', 'dtype': 'dtype', 'initializer': 'initializer', 'collections': 'collections', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (1760, 'tensorflow.squeeze', 'tf.squeeze', (['label_priors'], {}), True, 'import tensorflow as tf\n'), (1783, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (1786, 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(2)'], {}), True, 'import tensorflow as tf\n'), (1808, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.to_float', 'tf.to_float', (['((num_ratings - 1) ** 2)'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.transpose', 'tf.transpose', (['pred_norm'], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['cross_entropy'], {}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['var'], {}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['scale'], {'dtype': 'weights.dtype.base_dtype', 'name': '"""scale"""'}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['scale'], {'dtype': 'weights.dtype.base_dtype', 'name': '"""scale"""'}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.reshape', 'tf.reshape', (['inputs', '(inputs_shape + [1])'], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.zeros', 'tf.zeros', (['(inputs_shape + [nr_mix])'], {}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.nn.softplus', 'tf.nn.softplus', (['plus_in'], {}), True, 'import tensorflow as tf\n'), (345, 'tensorflow.nn.softplus', 'tf.nn.softplus', (['min_in'], {}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['log_probs', '(3)'], {}), True, 'import tensorflow as tf\n'), (429, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), True, 'import tensorflow as tf\n'), (455, 'tensorflow.subtract', 'tf.subtract', (['pos_dist', 'neg_dist'], {}), True, 'import tensorflow as tf\n'), (456, 'tensorflow.maximum', 'tf.maximum', (['basic_loss', '(0.0)'], {}), True, 'import tensorflow as tf\n'), (475, 'tensorflow.square', 'tf.square', (['corr'], {}), True, 'import tensorflow as tf\n'), (526, 'tensorflow.transpose', 'tf.transpose', (['source_samples'], {}), True, 'import tensorflow as tf\n'), (527, 'tensorflow.transpose', 'tf.transpose', (['target_samples'], {}), True, 'import tensorflow as tf\n'), (596, 'tensorflow.maximum', 'tf.maximum', (['(0.0001)', 'loss_value'], {}), True, 'import tensorflow as tf\n'), (617, 'tensorflow.shape', 'tf.shape', (['source_samples'], {}), True, 'import tensorflow as tf\n'), (692, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['assertions'], {}), True, 'import tensorflow as tf\n'), (693, 'tensorflow.multiply', 'tf.multiply', (['predictions', 'labels'], {}), True, 'import tensorflow as tf\n'), (733, 'tensorflow.shape', 'tf.shape', (['embedded'], {}), True, 'import tensorflow as tf\n'), (906, 'tensorflow.abs', 'tf.abs', (['x'], {}), True, 'import tensorflow as tf\n'), (978, 'tensorflow.to_int32', 'tf.to_int32', (['sequence_length'], {}), True, 'import tensorflow as tf\n'), (989, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['targets'], {}), True, 'import tensorflow as tf\n'), (1109, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (1113, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['per_anchor_loss', '(2)'], {}), True, 'import tensorflow as tf\n'), (1170, 'tensorflow.expand_dims', 'tf.expand_dims', (['logits', '(0)'], {}), True, 'import tensorflow as tf\n'), (1170, 'tensorflow.expand_dims', 'tf.expand_dims', (['logits', '(1)'], {}), True, 'import tensorflow as tf\n'), (1171, 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(0)'], {}), True, 'import tensorflow as tf\n'), (1171, 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (1172, 'tensorflow.expand_dims', 'tf.expand_dims', (['weights', '(0)'], {}), True, 'import tensorflow as tf\n'), (1172, 'tensorflow.expand_dims', 'tf.expand_dims', (['weights', '(1)'], {}), True, 'import tensorflow as tf\n'), (1292, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (1404, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (1605, 'tensorflow.log', 'tf.log', (['(2.0)'], {}), True, 'import tensorflow as tf\n'), (1740, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['((1.0 + dual_rate_factor) * dual_value)'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.log', 'tf.log', (['(1 - predictions + eps)'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.transpose', 'tf.transpose', (['repeat_op'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.to_float', 'tf.to_float', (['batch_size'], {}), True, 'import tensorflow as tf\n'), (184, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['log_loss_res', 'log_cutoff', '(10 ** 3)'], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.abs', 'tf.abs', (['var'], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.reshape', 'tf.reshape', (['means[:, :, :, (0), :]', '[inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]'], {}), True, 'import tensorflow as tf\n'), (348, 'tensorflow.nn.softplus', 'tf.nn.softplus', (['mid_in'], {}), True, 'import tensorflow as tf\n'), (370, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(pred - labels)'], {}), True, 'import tensorflow as tf\n'), (384, 'tensorflow.square', 'tf.square', (['embeddings'], {}), True, 'import tensorflow as tf\n'), (387, 'tensorflow.shape', 'tf.shape', (['embeddings'], {}), True, 'import tensorflow as tf\n'), (388, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['similarity'], {}), True, 'import tensorflow as tf\n'), (398, 'tensorflow.exp', 'tf.exp', (['(x - m2)'], {}), True, 'import tensorflow as tf\n'), (405, 'tensorflow.exp', 'tf.exp', (['(x - m)'], {}), True, 'import tensorflow as tf\n'), (453, 'tensorflow.subtract', 'tf.subtract', (['anchor', 'positive'], {}), True, 'import tensorflow as tf\n'), (454, 'tensorflow.subtract', 'tf.subtract', (['anchor', 'negative'], {}), True, 'import tensorflow as tf\n'), (474, 'tensorflow.transpose', 'tf.transpose', (['z'], {'perm': '[0, 2, 1]'}), True, 'import tensorflow as tf\n'), (476, 'tensorflow.diag_part', 'tf.diag_part', (['corr'], {}), True, 'import tensorflow as tf\n'), (499, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), True, 'import tensorflow as tf\n'), (528, 'tensorflow.square', 'tf.square', (['(source_cov - target_cov)'], {}), True, 'import tensorflow as tf\n'), (593, 'tensorflow.constant', 'tf.constant', (['sigmas'], {}), True, 'import tensorflow as tf\n'), (662, 'tensorflow.square', 'tf.square', (['correlation_matrix'], {}), True, 'import tensorflow as tf\n'), (695, 'tensorflow.abs', 'tf.abs', (['internal_dot_products'], {}), True, 'import tensorflow as tf\n'), (792, 'tensorflow.shape', 'tf.shape', (['embedded'], {}), True, 'import tensorflow as tf\n'), (820, 'tensorflow.shape', 'tf.shape', (['emb'], {}), True, 'import tensorflow as tf\n'), (843, 'tensorflow.stop_gradient', 'tf.stop_gradient', (['g'], {}), True, 'import tensorflow as tf\n'), (946, 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'logits': 'q_logits', 'labels': 'q'}), True, 'import tensorflow as tf\n'), (979, 'tensorflow.to_float', 'tf.to_float', (['loss_mask'], {}), True, 'import tensorflow as tf\n'), (988, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(predictions * targets)'], {}), True, 'import tensorflow as tf\n'), (989, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['predictions'], {}), True, 'import tensorflow as tf\n'), (1089, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (1176, 'tensorflow.ones_like', 'tf.ones_like', (['signed_logits_difference'], {}), True, 'import tensorflow as tf\n'), (1724, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (1733, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.log', 'tf.log', (['predictions'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.log', 'tf.log', (['(predictions + eps)'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.range', 'tf.range', (['(0)', 'num_ratings'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.abs', 'tf.abs', (['weights'], {}), True, 'import tensorflow as tf\n'), (369, 'tensorflow.shape', 'tf.shape', (['pred'], {}), True, 'import tensorflow as tf\n'), (622, 'tensorflow.zeros', 'tf.zeros', (['(batch_size, 1)'], {}), True, 'import tensorflow as tf\n'), (622, 'tensorflow.ones', 'tf.ones', (['(batch_size, 1)'], {}), True, 'import tensorflow as tf\n'), (884, 'tensorflow.shape', 'tf.shape', (['emb'], {}), True, 'import tensorflow as tf\n'), (907, 'tensorflow.pow', 'tf.pow', (['(x / alpha)', '(2)'], {}), True, 'import tensorflow as tf\n'), (952, 'tensorflow.log', 'tf.log', (['q'], {}), True, 'import tensorflow as tf\n'), (952, 'tensorflow.log', 'tf.log', (['p'], {}), True, 'import tensorflow as tf\n'), (959, 'tensorflow.expand_dims', 'tf.expand_dims', (['weights', '(-1)'], {}), True, 'import tensorflow as tf\n'), (978, 'tensorflow.shape', 'tf.shape', (['targets'], {}), True, 'import tensorflow as tf\n'), (1183, 'tensorflow.abs', 'tf.abs', (['labels_difference'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['pred_', '(1)'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.reshape', 'tf.reshape', (['hist_rater_a', '[num_ratings, 1]'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.reshape', 'tf.reshape', (['hist_rater_b', '[1, num_ratings]'], {}), True, 'import tensorflow as tf\n'), (353, 'tensorflow.maximum', 'tf.maximum', (['cdf_delta', '(1e-12)'], {}), True, 'import tensorflow as tf\n'), (354, 'numpy.log', 'np.log', (['(127.5)'], {}), True, 'import numpy as np\n'), (434, 'tensorflow.log', 'tf.log', (['softmax'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['pred_', '(1)'], {}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.log', 'tf.log', (['softmax'], {}), True, 'import tensorflow as tf\n'), (685, 'tensorflow.square', 'tf.square', (['predictions'], {}), True, 'import tensorflow as tf\n'), (689, 'tensorflow.square', 'tf.square', (['labels'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
from . import text_encoder
from .texttfrecords import TextTFRecord
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 = TextTFRecord()
@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": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.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 = tf.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
| [
"tensorflow.gfile.Glob",
"tensorflow.VarLenFeature"
] | tefla/dataset/textdataset.py | [(16, 'six.add_metaclass', 'six.add_metaclass', (['abc.ABCMeta'], {}), False, 'import six\n'), (160, 'os.path.join', 'os.path.join', (['self._data_dir', 'self._dataset_name'], {}), False, 'import os\n'), (95, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (135, 'os.path.join', 'os.path.join', (['output_dir', 'fname'], {}), False, 'import os\n'), (115, 'os.path.join', 'os.path.join', (['self._data_dir', 'self.vocab_file'], {}), False, 'import os\n'), (118, 'os.path.join', 'os.path.join', (['self._data_dir', 'self.vocab_file'], {}), False, 'import os\n'), (189, 'tensorflow.gfile.Glob', 'tf.gfile.Glob', (['data_sources'], {}), True, 'import tensorflow as tf\n')] |
Monnoroch/tensorflow | 1d76583411038767f673a0c96174c80eaf9ff42f | """## Arithmetic Operators
TensorFlow provides several operations that you can use to add basic arithmetic
operators to your graph.
@@add
@@sub
@@mul
@@div
@@mod
## Basic Math Functions
TensorFlow 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
TensorFlow 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
TensorFlow provides several operations that you can use to add complex number
functions to your graph.
@@complex
@@complex_abs
@@conj
@@imag
@@real
## Reduction
TensorFlow 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
TensorFlow 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 = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.segment_sum(c, tf.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
TensorFlow 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 tensorflow.python.platform
import numpy as np
import six.moves
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework import types
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import common_shapes
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import gen_state_ops
# pylint: disable=wildcard-import,undefined-variable
from tensorflow.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 [`tf.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]]
tf.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]
tf.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]
tf.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=tf.float
tf.cast(a, tf.int32) ==> [1, 2] # dtype=tf.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 `tf.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 `tf.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 `tf.div(x,y)`, but uses `tf.floor(tf.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
tf.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]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
tf.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.]]
tf.reduce_mean(x) ==> 1.5
tf.reduce_mean(x, 0) ==> [1.5, 1.5]
tf.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]]
tf.reduce_all(x) ==> False
tf.reduce_all(x, 0) ==> [False, False]
tf.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]]
tf.reduce_any(x) ==> True
tf.reduce_any(x, 0) ==> [True, True]
tf.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 = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.]
[4. 5. 6.]]
# 2-D tensor `b`
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.]
[9. 10.]
[11. 12.]]
c = tf.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]]
tf.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]]
# Explicitly pass shape and type
tf.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=tf.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.framework.tensor_shape.scalar",
"tensorflow.python.ops.gen_math_ops._range",
"tensorflow.python.ops.gen_math_ops._abs",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.framework.ops.op_scope",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.ops.gen_math_ops._sigmoid",
"tensorflow.python.ops.gen_math_ops._complex",
"tensorflow.python.framework.ops.convert_n_to_tensor_or_indexed_slices",
"tensorflow.python.ops.gen_math_ops._tanh",
"tensorflow.python.ops.array_ops.rank",
"tensorflow.python.ops.gen_state_ops._temporary_variable",
"tensorflow.python.ops.gen_state_ops._destroy_temporary_variable",
"numpy.ravel",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.framework.ops.SparseTensor",
"tensorflow.python.ops.gen_math_ops._mat_mul",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.framework.ops.RegisterShape",
"tensorflow.python.framework.ops.Tensor._override_operator",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.gen_math_ops.complex_abs",
"tensorflow.python.framework.tensor_util.ConstantValue",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.python.ops.gen_math_ops._pow",
"tensorflow.python.ops.gen_math_ops.cast",
"tensorflow.python.framework.tensor_shape.Dimension",
"tensorflow.python.framework.tensor_shape.vector",
"tensorflow.python.framework.tensor_shape.as_shape"
] | tensorflow/python/ops/math_ops.py | [(386, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__neg__"""', 'neg'], {}), False, 'from tensorflow.python.framework import ops\n'), (387, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__abs__"""', 'abs'], {}), False, 'from tensorflow.python.framework import ops\n'), (391, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__invert__"""', 'logical_not'], {}), False, 'from tensorflow.python.framework import ops\n'), (533, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__lt__"""', 'less'], {}), False, 'from tensorflow.python.framework import ops\n'), (534, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__le__"""', 'less_equal'], {}), False, 'from tensorflow.python.framework import ops\n'), (535, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__gt__"""', 'greater'], {}), False, 'from tensorflow.python.framework import ops\n'), (536, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (['"""__ge__"""', 'greater_equal'], {}), False, 'from tensorflow.python.framework import ops\n'), (568, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Range"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1015, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BatchMatMul"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1095, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Add"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1096, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Complex"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1097, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Div"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1098, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Equal"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1099, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Greater"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1100, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""GreaterEqual"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1101, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Less"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1102, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LessEqual"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1103, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LogicalAnd"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1104, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LogicalOr"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1105, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Maximum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1106, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Minimum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1107, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Mod"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1108, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Mul"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1109, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""NotEqual"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1110, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Pow"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1111, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sub"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1157, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""AddN"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1165, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Select"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1173, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""ArgMax"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1174, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""ArgMin"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1201, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""All"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1202, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Any"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1203, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Max"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1204, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Mean"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1205, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Min"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1206, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Prod"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1207, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1241, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SegmentMax"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1242, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SegmentMean"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1243, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SegmentMin"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1244, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SegmentProd"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1245, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SegmentSum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1254, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SparseSegmentMean"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1255, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SparseSegmentSum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1267, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SparseSegmentMeanGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1283, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""UnsortedSegmentSum"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1297, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LinSpace"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (259, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (408, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (["('__%s__' % op_name)", 'binary_op_wrapper'], {}), False, 'from tensorflow.python.framework import ops\n'), (417, 'tensorflow.python.framework.ops.Tensor._override_operator', 'ops.Tensor._override_operator', (["('__r%s__' % op_name)", 'r_binary_op_wrapper'], {}), False, 'from tensorflow.python.framework import ops\n'), (565, 'tensorflow.python.ops.gen_math_ops._range', 'gen_math_ops._range', (['start', 'limit', 'delta'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (570, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[0]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (571, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (572, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[2]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (884, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""MatMul"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (885, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SparseMatMul"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (907, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['x'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1069, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Abs"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1070, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Ceil"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1071, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Conj"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1072, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Cos"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1073, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Exp"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1074, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Floor"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1075, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Imag"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1076, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Inv"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1077, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""IsFinite"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1078, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""IsInf"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1079, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""IsNan"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1080, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Log"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1081, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LogicalNot"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1082, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Neg"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1083, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Real"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1084, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Rsqrt"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1085, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sign"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1086, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sin"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1087, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sqrt"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1088, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Square"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1089, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Sigmoid"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1090, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Tanh"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1091, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Cast"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1092, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""ComplexAbs"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1159, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1185, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (1211, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (1220, 'numpy.ravel', 'np.ravel', (['reduction_indices'], {}), True, 'import numpy as np\n'), (1275, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[3]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (1299, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[2]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (180, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""Abs"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (181, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (184, 'tensorflow.python.ops.gen_math_ops._abs', 'gen_math_ops._abs', (['x'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (208, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""Pow"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (209, 'tensorflow.python.ops.gen_math_ops._pow', 'gen_math_ops._pow', (['x', 'y'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (238, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[real, imag]', 'name', '"""Complex"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (239, 'tensorflow.python.ops.gen_math_ops._complex', 'gen_math_ops._complex', (['real', 'imag'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (290, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""Cast"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (459, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, y]', 'name', '"""truediv"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (460, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (461, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['y'], {'name': '"""y"""'}), False, 'from tensorflow.python.framework import ops\n'), (503, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, y]', 'name', '"""floordiv"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (504, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (865, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[a, b]', 'name', '"""MatMul"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (866, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['a'], {'name': '"""a"""'}), False, 'from tensorflow.python.framework import ops\n'), (867, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['b'], {'name': '"""b"""'}), False, 'from tensorflow.python.framework import ops\n'), (979, 'tensorflow.python.framework.ops.convert_n_to_tensor_or_indexed_slices', 'ops.convert_n_to_tensor_or_indexed_slices', (['inputs'], {}), False, 'from tensorflow.python.framework import ops\n'), (988, 'tensorflow.python.framework.tensor_shape.as_shape', 'tensor_shape.as_shape', (['shape'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (990, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1001, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['inputs', 'name', '"""AccumulateN"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1002, 'tensorflow.python.ops.gen_state_ops._temporary_variable', 'gen_state_ops._temporary_variable', ([], {'shape': 'shape', 'dtype': 'tensor_dtype'}), False, 'from tensorflow.python.ops import gen_state_ops\n'), (1047, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""Sigmoid"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1048, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (1049, 'tensorflow.python.ops.gen_math_ops._sigmoid', 'gen_math_ops._sigmoid', (['x'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (1064, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""Tanh"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (1065, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (1066, 'tensorflow.python.ops.gen_math_ops._tanh', 'gen_math_ops._tanh', (['x'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (1154, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['return_dims'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1178, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1238, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['returned_dims'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1274, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1292, 'tensorflow.python.framework.tensor_util.ConstantValue', 'tensor_util.ConstantValue', (['op.inputs[2]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (1300, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['num'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (183, 'tensorflow.python.ops.gen_math_ops.complex_abs', 'gen_math_ops.complex_abs', (['x'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (293, 'tensorflow.python.framework.ops.SparseTensor', 'ops.SparseTensor', (['x.indices', 'values_cast', 'x.shape'], {}), False, 'from tensorflow.python.framework import ops\n'), (300, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (303, 'tensorflow.python.ops.gen_math_ops.cast', 'gen_math_ops.cast', (['x', 'dtype'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (403, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, y]', 'None', 'op_name'], {}), False, 'from tensorflow.python.framework import ops\n'), (405, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['y'], {'dtype': 'x.dtype.base_dtype', 'name': '"""y"""'}), False, 'from tensorflow.python.framework import ops\n'), (412, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, y]', 'None', 'op_name'], {}), False, 'from tensorflow.python.framework import ops\n'), (414, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'dtype': 'y.dtype.base_dtype', 'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (574, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['None'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (576, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['((limit_value - start_value + delta_value - 1) // delta_value)'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (586, 'tensorflow.python.ops.array_ops.rank', 'array_ops.rank', (['x'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (876, 'tensorflow.python.ops.gen_math_ops._mat_mul', 'gen_math_ops._mat_mul', (['a', 'b'], {'transpose_a': 'transpose_a', 'transpose_b': 'transpose_b', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_math_ops\n'), (1004, 'tensorflow.python.ops.array_ops.zeros_like', 'array_ops.zeros_like', (['inputs[0]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1007, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['var', 'input_tensor'], {'use_locking': '(True)'}), False, 'from tensorflow.python.ops import state_ops\n'), (1009, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['update_ops'], {}), False, 'from tensorflow.python.framework import ops\n'), (1010, 'tensorflow.python.ops.gen_state_ops._destroy_temporary_variable', 'gen_state_ops._destroy_temporary_variable', (['var'], {'var_name': 'var_name', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_state_ops\n'), (1023, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1117, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1181, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1187, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(input_shape.ndims - 1)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1290, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1183, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1193, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['returned_shape'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1215, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': 'input_shape.ndims'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1217, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1251, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['[None]'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1264, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['[None]'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1280, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['[dim0]'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1124, 'tensorflow.python.framework.tensor_shape.Dimension', 'tensor_shape.Dimension', (['(1)'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (1293, 'tensorflow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', (['[num_segments]'], {}), False, 'from tensorflow.python.framework import tensor_shape\n')] |
intel-isl/MetaLearningTradeoffs | bb1b849742a959310f3b9b630bb76ae3509a5d4a | import tensorflow as tf
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 (tf.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 = tf.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 tf.global_variables() if not sess.run(tf.is_variable_initialized(var))]
sess.run(tf.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 = tf.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)
| [
"tensorflow.global_variables",
"tensorflow.variables_initializer",
"tensorflow.is_variable_initialized",
"tensorflow.Session",
"numpy.sum"
] | maml_zoo/meta_trainer.py | [(141, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Training finished"""'], {}), False, 'from maml_zoo.logger import logger\n'), (45, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (66, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (64, 'tensorflow.variables_initializer', 'tf.variables_initializer', (['uninit_vars'], {}), True, 'import tensorflow as tf\n'), (68, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (69, 'maml_zoo.logger.logger.log', 'logger.log', (['("""\n ---------------- Iteration %d ----------------""" % itr)'], {}), False, 'from maml_zoo.logger import logger\n'), (70, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Sampling set of tasks/goals for this meta-batch..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (77, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (110, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (113, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Optimizing policy..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (115, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (119, 'maml_zoo.logger.logger.logkv', 'logger.logkv', (['"""Itr"""', 'itr'], {}), False, 'from maml_zoo.logger import logger\n'), (120, 'maml_zoo.logger.logger.logkv', 'logger.logkv', (['"""n_timesteps"""', 'self.sampler.total_timesteps_sampled'], {}), False, 'from maml_zoo.logger import logger\n'), (123, 'maml_zoo.logger.logger.logkv', 'logger.logkv', (['"""Time-TotalInner"""', 'total_inner_time'], {}), False, 'from maml_zoo.logger import logger\n'), (132, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Saving snapshot..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (134, 'maml_zoo.logger.logger.save_itr_params', 'logger.save_itr_params', (['itr', 'params'], {}), False, 'from maml_zoo.logger import logger\n'), (135, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Saved"""'], {}), False, 'from maml_zoo.logger import logger\n'), (137, 'maml_zoo.logger.logger.dumpkvs', 'logger.dumpkvs', ([], {}), False, 'from maml_zoo.logger import logger\n'), (63, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (83, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Obtaining samples..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (84, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (91, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Processing samples..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (92, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (101, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (108, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (124, 'numpy.sum', 'np.sum', (['list_inner_step_time'], {}), True, 'import numpy as np\n'), (125, 'numpy.sum', 'np.sum', (['list_proc_samples_time'], {}), True, 'import numpy as np\n'), (126, 'numpy.sum', 'np.sum', (['list_sampling_time'], {}), True, 'import numpy as np\n'), (103, 'maml_zoo.logger.logger.log', 'logger.log', (['"""Computing inner policy updates..."""'], {}), False, 'from maml_zoo.logger import logger\n'), (122, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (128, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (129, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (130, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (63, 'tensorflow.is_variable_initialized', 'tf.is_variable_initialized', (['var'], {}), True, 'import tensorflow as tf\n'), (86, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (95, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (107, 'time.time', 'time.time', ([], {}), False, 'import time\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 tensorflow as tf
import tensorflow.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 = tf.reduce_max(n_vars_per_sample)
output = tf.split(
value=output,
num_or_size_splits=n_vars_per_sample,
axis=1,
)
output = tf.concat([
tf.pad(
x,
paddings=[[0, 0], [0, n_vars_max - tf.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, tf.reduce_sum(n_cs, keepdims=True), tf.reduce_sum(n_vs, keepdims=True)), tf.convert_to_tensor(False))
# filter candidate variables
pred_scores = tf.expand_dims(tf.gather(tf.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 TF
pred_scores = tf.convert_to_tensor(pred_scores.reshape((1, -1)), dtype=tf.float32)
# padding
pred_scores = padding(pred_scores, n_cands)
true_scores = padding(tf.reshape(cand_scores, (1, -1)), n_cands)
true_bestscore = tf.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 = tf.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 = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.enable_eager_execution(config)
tf.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)
tf.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'] = [tf.float32, tf.int32, tf.float32,
tf.float32, tf.int32, tf.int32, tf.int32, tf.int32, tf.int32, tf.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'] = [tf.float32, tf.int32, tf.int32, tf.float32]
policy['batch_fun'] = lambda x: load_batch_flat(x, feat_specs['type'], feat_specs['augment'], feat_specs['qbnorm'])
test_data = tf.data.Dataset.from_tensor_slices(test_files)
test_data = test_data.batch(test_batch_size)
test_data = test_data.map(lambda x: tf.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()
| [
"tensorflow.convert_to_tensor",
"tensorflow.reduce_max",
"tensorflow.enable_eager_execution",
"tensorflow.executing_eagerly",
"tensorflow.shape",
"numpy.asarray",
"tensorflow.reduce_sum",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.reshape",
"tensorflow.squeeze",
"tensorflow.ConfigProto",
"numpy.concatenate",
"tensorflow.nn.top_k",
"numpy.iinfo",
"tensorflow.contrib.eager.defun",
"tensorflow.split",
"numpy.random.RandomState",
"tensorflow.py_func"
] | 04_test.py | [(45, 'tensorflow.reduce_max', 'tf.reduce_max', (['n_vars_per_sample'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.split', 'tf.split', ([], {'value': 'output', 'num_or_size_splits': 'n_vars_per_sample', 'axis': '(1)'}), True, 'import tensorflow as tf\n'), (117, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (134, 'os.makedirs', 'os.makedirs', (['"""results"""'], {'exist_ok': '(True)'}), False, 'import os\n'), (156, 'os.makedirs', 'os.makedirs', (['"""results"""'], {'exist_ok': '(True)'}), False, 'import os\n'), (163, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', (['config'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), True, 'import tensorflow as tf\n'), (28, 'utilities.load_flat_samples', 'utilities.load_flat_samples', (['filename', 'feats_type', '"""scores"""', 'augment_feats', 'normalize_feats'], {}), False, 'import utilities\n'), (96, 'tensorflow.reduce_max', 'tf.reduce_max', (['true_scores'], {'axis': '(-1)', 'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (105, 'numpy.asarray', 'np.asarray', (['kacc'], {}), True, 'import numpy as np\n'), (183, 'csv.DictWriter', 'csv.DictWriter', (['csvfile'], {'fieldnames': 'fieldnames'}), False, 'import csv\n'), (36, 'numpy.concatenate', 'np.concatenate', (['cand_features'], {'axis': '(0)'}), True, 'import numpy as np\n'), (37, 'numpy.asarray', 'np.asarray', (['cand_choices'], {}), True, 'import numpy as np\n'), (38, 'numpy.concatenate', 'np.concatenate', (['cand_scoress'], {'axis': '(0)'}), True, 'import numpy as np\n'), (39, 'numpy.asarray', 'np.asarray', (['n_cands_per_sample'], {}), True, 'import numpy as np\n'), (95, 'tensorflow.reshape', 'tf.reshape', (['cand_scores', '(1, -1)'], {}), True, 'import tensorflow as tf\n'), (135, 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), False, 'import time\n'), (153, 'time.strftime', 'time.strftime', (['"""%Y%m%d-%H%M%S"""'], {}), False, 'import time\n'), (73, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['(False)'], {}), True, 'import tensorflow as tf\n'), (168, 'pathlib.Path', 'pathlib.Path', (['f"""data/samples/{problem_folder}/test"""'], {}), False, 'import pathlib\n'), (188, 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), True, 'import numpy as np\n'), (229, 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['test_files'], {}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['n_cs'], {'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['n_vs'], {'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.squeeze', 'tf.squeeze', (['pred_scores', '(0)'], {}), True, 'import tensorflow as tf\n'), (199, 'importlib.reload', 'importlib.reload', (['model'], {}), False, 'import importlib\n'), (201, 'model.GCNPolicy', 'model.GCNPolicy', ([], {}), False, 'import model\n'), (203, 'tensorflow.contrib.eager.defun', 'tfe.defun', (["policy['model'].call"], {'input_signature': "policy['model'].input_signature"}), True, 'import tensorflow.contrib.eager as tfe\n'), (102, 'tensorflow.nn.top_k', 'tf.nn.top_k', (['pred_scores'], {'k': 'k'}), True, 'import tensorflow as tf\n'), (197, 'os.path.abspath', 'os.path.abspath', (['f"""models/{policy[\'name\']}"""'], {}), False, 'import os\n'), (224, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (231, 'tensorflow.py_func', 'tf.py_func', (["policy['batch_fun']", '[x]', "policy['batch_datatypes']"], {}), True, 'import tensorflow as tf\n'), (189, 'numpy.iinfo', 'np.iinfo', (['int'], {}), True, 'import numpy as np\n'), (211, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (220, 'pickle.load', 'pickle.load', (['f'], {}), False, 'import pickle\n'), (217, 'svmrank.Model', 'svmrank.Model', ([], {}), False, 'import svmrank\n'), (55, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\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 tensorflow as tf
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": tf.VarLenFeature(tf.int64)}
if self.has_inputs:
data_fields["inputs"] = tf.VarLenFeature(tf.int64)
if self.packed_length:
if self.has_inputs:
data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["inputs_position"] = tf.VarLenFeature(tf.int64)
data_fields["targets_segmentation"] = tf.VarLenFeature(tf.int64)
data_fields["targets_position"] = tf.VarLenFeature(tf.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"] = tf.VarLenFeature(tf.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": tf.VarLenFeature(tf.int64),
"targets": tf.FixedLenFeature([1], tf.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 tf.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 = tf.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
tf.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.
"""
tf.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]
| [
"tensorflow.logging.info",
"tensorflow.FixedLenFeature",
"tensorflow.gfile.Open",
"tensorflow.VarLenFeature"
] | tensor2tensor/data_generators/text_problems.py | [(236, 'tensor2tensor.data_generators.generator_utils.pack_examples', 'generator_utils.pack_examples', (['generator', 'self.has_inputs', 'self.packed_length'], {'chop_long_sequences': '(not self.has_inputs)'}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (290, 'tensor2tensor.data_generators.generator_utils.shuffle_dataset', 'generator_utils.shuffle_dataset', (['all_paths'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (392, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (503, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['txt_path'], {}), True, 'import tensorflow as tf\n'), (691, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['filepath'], {}), True, 'import tensorflow as tf\n'), (799, 'tensorflow.logging.info', 'tf.logging.info', (["('generate_data task_id=%s' % task_id)"], {}), True, 'import tensorflow as tf\n'), (811, 'tensor2tensor.data_generators.generator_utils.shuffle_dataset', 'generator_utils.shuffle_dataset', (['[out_file]'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (212, 'tensor2tensor.data_generators.text_encoder.ByteTextEncoder', 'text_encoder.ByteTextEncoder', ([], {}), False, 'from tensor2tensor.data_generators import text_encoder\n'), (315, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (323, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (324, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (494, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (495, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[1]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (608, 'os.path.join', 'os.path.join', (['tmp_dir', 'f'], {}), False, 'import os\n'), (693, 'tensor2tensor.data_generators.text_encoder.to_unicode_ignore_errors', 'text_encoder.to_unicode_ignore_errors', (['b'], {}), False, 'from tensor2tensor.data_generators import text_encoder\n'), (719, 'tensorflow.logging.info', 'tf.logging.info', (["('reading file %s' % fname)"], {}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (322, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (215, 'os.path.join', 'os.path.join', (['data_dir', 'self.vocab_filename'], {}), False, 'import os\n'), (216, 'tensor2tensor.data_generators.text_encoder.SubwordTextEncoder', 'text_encoder.SubwordTextEncoder', (['vocab_filepath'], {}), False, 'from tensor2tensor.data_generators import text_encoder\n'), (225, 'os.path.join', 'os.path.join', (['data_dir', 'self.vocab_filename'], {}), False, 'import os\n'), (226, 'tensor2tensor.data_generators.text_encoder.TokenTextEncoder', 'text_encoder.TokenTextEncoder', (['vocab_filename'], {'replace_oov': 'self.oov_token'}), False, 'from tensor2tensor.data_generators import text_encoder\n')] |
aditya2592/PoseCNN | da9eaae850eed7521a2a48a4d27474d655caab42 | import tensorflow as tf
from tensorflow.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]
| [
"tensorflow.python.framework.ops.RegisterShape",
"tensorflow.python.framework.ops.RegisterGradient"
] | lib/hard_label_layer/hard_label_op_grad.py | [(5, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Hardlabel"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (11, 'tensorflow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', (['"""Hardlabel"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (19, 'hard_label_op.hard_label_grad', 'hard_label_op.hard_label_grad', (['bottom_prob', 'bottom_gt', 'grad', 'threshold'], {}), False, 'import hard_label_op\n')] |
kadeng/tensorflow_project_workspace | dee284fb2d1796329895130a075cd57a62ea873f | # Copyright 2016 The TensorFlow 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 tensorflow.contrib import layers
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework import deprecated_arg_values
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.layers.python.layers import optimizers
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.learn.python.learn import monitors as monitor_lib
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.python.ops import nn
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.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 `tf.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 TensorFlow 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=tf.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 `tf.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 `tf.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
`tf.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 TensorFlow 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=tf.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 `tf.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 `tf.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
`tf.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.layers.parse_feature_columns_from_examples",
"tensorflow.contrib.learn.python.learn.estimators.head._multi_class_head",
"tensorflow.contrib.framework.python.ops.variables.get_global_step",
"tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined._extract_embedding_lr_multipliers",
"tensorflow.contrib.layers.input_from_feature_columns",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.python.summary.summary.histogram",
"tensorflow.contrib.layers.dropout",
"tensorflow.contrib.learn.python.learn.estimators.head._regression_head",
"tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner",
"tensorflow.contrib.framework.deprecated_arg_values",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.nn.zero_fraction",
"tensorflow.contrib.learn.python.learn.monitors.replace_monitors_with_hooks",
"tensorflow.contrib.framework.deprecated"
] | tensorflow/contrib/learn/python/learn/estimators/dnn.py | [(66, 'tensorflow.python.summary.summary.histogram', 'summary.histogram', (["('%s_activation' % tag)", 'value'], {}), False, 'from tensorflow.python.summary import summary\n'), (116, 'tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner', 'partitioned_variables.min_max_variable_partitioner', ([], {'max_partitions': 'num_ps_replicas', 'min_slice_size': '(64 << 20)'}), False, 'from tensorflow.python.ops import partitioned_variables\n'), (130, 'tensorflow.python.ops.partitioned_variables.min_max_variable_partitioner', 'partitioned_variables.min_max_variable_partitioner', ([], {'max_partitions': 'num_ps_replicas'}), False, 'from tensorflow.python.ops import partitioned_variables\n'), (365, 'tensorflow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', (['estimator.AS_ITERABLE_DATE', 'estimator.AS_ITERABLE_INSTRUCTIONS'], {'as_iterable': '(False)'}), False, 'from tensorflow.contrib.framework import deprecated_arg_values\n'), (397, 'tensorflow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', (['estimator.AS_ITERABLE_DATE', 'estimator.AS_ITERABLE_INSTRUCTIONS'], {'as_iterable': '(False)'}), False, 'from tensorflow.contrib.framework import deprecated_arg_values\n'), (503, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-10-30"""', '"""This method will be removed after the deprecation date. To inspect variables, use get_variable_names() and get_variable_value()."""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (516, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-10-30"""', '"""This method will be removed after the deprecation date. To inspect variables, use get_variable_names() and get_variable_value()."""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (727, 'tensorflow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', (['estimator.AS_ITERABLE_DATE', 'estimator.AS_ITERABLE_INSTRUCTIONS'], {'as_iterable': '(False)'}), False, 'from tensorflow.contrib.framework import deprecated_arg_values\n'), (65, 'tensorflow.python.ops.nn.zero_fraction', 'nn.zero_fraction', (['value'], {}), False, 'from tensorflow.python.ops import nn\n'), (123, 'tensorflow.contrib.layers.input_from_feature_columns', 'layers.input_from_feature_columns', ([], {'columns_to_tensors': 'features', 'feature_columns': 'feature_columns', 'weight_collections': '[parent_scope]', 'scope': 'scope'}), False, 'from tensorflow.contrib import layers\n'), (147, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (["(parent_scope + '/logits')"], {'values': '[net]', 'partitioner': 'hidden_layer_partitioner'}), False, 'from tensorflow.python.ops import variable_scope\n'), (151, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['net', 'head.logits_dimension'], {'activation_fn': 'None', 'variables_collections': '[parent_scope]', 'scope': 'scope'}), False, 'from tensorflow.contrib import layers\n'), (331, 'tensorflow.contrib.learn.python.learn.monitors.replace_monitors_with_hooks', 'monitor_lib.replace_monitors_with_hooks', (['monitors', 'self'], {}), True, 'from tensorflow.contrib.learn.python.learn import monitors as monitor_lib\n'), (683, 'tensorflow.contrib.learn.python.learn.monitors.replace_monitors_with_hooks', 'monitor_lib.replace_monitors_with_hooks', (['monitors', 'self'], {}), True, 'from tensorflow.contrib.learn.python.learn import monitors as monitor_lib\n'), (133, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (["(parent_scope + '/hiddenlayer_%d' % layer_id)"], {'values': '[net]', 'partitioner': 'hidden_layer_partitioner'}), False, 'from tensorflow.python.ops import variable_scope\n'), (137, 'tensorflow.contrib.layers.fully_connected', 'layers.fully_connected', (['net', 'num_hidden_units'], {'activation_fn': 'activation_fn', 'variables_collections': '[parent_scope]', 'scope': 'scope'}), False, 'from tensorflow.contrib import layers\n'), (468, 'tensorflow.contrib.layers.parse_feature_columns_from_examples', 'layers.parse_feature_columns_from_examples', (['examples', 'self._feature_columns'], {}), False, 'from tensorflow.contrib import layers\n'), (708, 'six.iteritems', 'six.iteritems', (['metrics'], {}), False, 'import six\n'), (795, 'tensorflow.contrib.layers.parse_feature_columns_from_examples', 'layers.parse_feature_columns_from_examples', (['examples', 'self._feature_columns'], {}), False, 'from tensorflow.contrib import layers\n'), (144, 'tensorflow.contrib.layers.dropout', 'layers.dropout', (['net'], {'keep_prob': '(1.0 - dropout)'}), False, 'from tensorflow.contrib import layers\n'), (163, 'tensorflow.contrib.framework.python.ops.variables.get_global_step', 'contrib_variables.get_global_step', ([], {}), True, 'from tensorflow.contrib.framework.python.ops import variables as contrib_variables\n'), (167, 'tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined._extract_embedding_lr_multipliers', 'dnn_linear_combined._extract_embedding_lr_multipliers', (['embedding_lr_multipliers', 'parent_scope', 'input_layer_scope'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined\n'), (121, 'six.itervalues', 'six.itervalues', (['features'], {}), False, 'import six\n'), (300, 'tensorflow.contrib.learn.python.learn.estimators.head._multi_class_head', 'head_lib._multi_class_head', (['n_classes'], {'weight_column_name': 'weight_column_name', 'enable_centered_bias': 'enable_centered_bias'}), True, 'from tensorflow.contrib.learn.python.learn.estimators import head as head_lib\n'), (652, 'tensorflow.contrib.learn.python.learn.estimators.head._regression_head', 'head_lib._regression_head', ([], {'label_dimension': 'label_dimension', 'weight_column_name': 'weight_column_name', 'enable_centered_bias': 'enable_centered_bias'}), True, 'from tensorflow.contrib.learn.python.learn.estimators import head as head_lib\n')] |
873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a |
# Copyright 2018 The TensorFlow 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 tensorflow as tf
import cv2
gfile = tf.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 TensorFlow 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 = tf.trainable_variables()
# Add batchnorm variables.
bn_vars = [v for v in tf.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 = tf.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 = tf.contrib.framework.list_variables(imagenet_ckpt)
ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names]
model_vars = tf.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 tf.gfile.Open(filepath, 'r') as f:
lines = f.readlines()
lines = [l.rstrip() for l in lines]
return lines
| [
"numpy.clip",
"tensorflow.gfile.Open",
"matplotlib.use",
"tensorflow.global_variables",
"matplotlib.pyplot.get_cmap",
"numpy.percentile",
"numpy.delete",
"tensorflow.trainable_variables",
"numpy.array",
"tensorflow.contrib.framework.list_variables"
] | research/struct2depth/util.py | [(28, 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), False, 'import matplotlib\n'), (51, 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['cmap'], {}), True, 'import matplotlib.pyplot as plt\n'), (61, 'cv2.imdecode', 'cv2.imdecode', (['im_data', 'cv2.IMREAD_COLOR'], {}), False, 'import cv2\n'), (62, 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), False, 'import cv2\n'), (88, 'numpy.clip', 'np.clip', (['disp', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (168, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.contrib.framework.list_variables', 'tf.contrib.framework.list_variables', (['imagenet_ckpt'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (236, 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '"""en_US"""'], {}), False, 'import locale\n'), (237, 'locale.format', 'locale.format', (['"""%d"""', 'n'], {'grouping': '(True)'}), False, 'import locale\n'), (46, 'cv2.resize', 'cv2.resize', (['im', 'resize'], {}), False, 'import cv2\n'), (54, 'numpy.delete', 'np.delete', (['result_img', '(3)', '(2)'], {}), True, 'import numpy as np\n'), (65, 'cv2.resize', 'cv2.resize', (['im', 'resize'], {'interpolation': 'ip'}), False, 'import cv2\n'), (66, 'numpy.array', 'np.array', (['im'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (73, 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_RGB2BGR'], {}), False, 'import cv2\n'), (74, 'cv2.imencode', 'cv2.imencode', (["('.%s' % file_extension)", 'im'], {}), False, 'import cv2\n'), (146, 'absl.logging.info', 'logging.info', (['"""Model Parameters:"""'], {}), False, 'from absl import logging\n'), (178, 'tensorflow.contrib.framework.list_variables', 'tf.contrib.framework.list_variables', (['ckpt'], {}), True, 'import tensorflow as tf\n'), (249, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['filepath', '"""r"""'], {}), True, 'import tensorflow as tf\n'), (87, 'numpy.percentile', 'np.percentile', (['disp', 'pc'], {}), True, 'import numpy as np\n'), (170, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (206, 'absl.logging.warn', 'logging.warn', (['"""The following variables in the checkpoint were not loaded:"""'], {}), False, 'from absl import logging\n'), (229, 'absl.logging.info', 'logging.info', (['"""The following variable will not be restored from pretrained ImageNet-checkpoint: %s"""', 'mvname_noprefix'], {}), False, 'from absl import logging\n'), (245, 're.split', 're.split', (['"""(\\\\d+)"""', 'text'], {}), False, 'import re\n'), (208, 'absl.logging.info', 'logging.info', (['"""%s"""', 'varname_not_loaded'], {}), False, 'from absl import logging\n'), (196, 'os.path.basename', 'os.path.basename', (['ckpt'], {}), False, 'import os\n'), (204, 'absl.logging.warn', 'logging.warn', (['"""Shape mismatch, will not restore %s."""', 'v.op.name'], {}), False, 'from absl import logging\n'), (194, 'absl.logging.warn', 'logging.warn', (['"""Shape mismatch, will not restore %s."""', 'v.op.name'], {}), False, 'from absl import logging\n')] |
873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | # Copyright 2017 The TensorFlow 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 TF:
github.com/tensorflow/models/tree/master/research/transformer
"""
import tensorflow as tf
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 (tf.float32).
theta: A tensor of size [num_batch, 16].
It is the inverse camera transformation matrix (tf.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 (tf.float32).
"""
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(
tf.expand_dims(tf.ones(shape=tf.stack([
n_repeats,
])), 1), [1, 0])
rep = tf.to_int32(rep)
x = tf.matmul(tf.reshape(x, (-1, 1)), rep)
return tf.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 (tf.float32).
x: A tensor of size [num_batch, out_depth, out_height, out_width]
representing the inverse coordinate mapping for x (tf.float32).
y: A tensor of size [num_batch, out_depth, out_height, out_width]
representing the inverse coordinate mapping for y (tf.float32).
z: A tensor of size [num_batch, out_depth, out_height, out_width]
representing the inverse coordinate mapping for z (tf.float32).
out_size: A tuple representing the output size of transformation layer
(float).
Returns:
A transformed tensor (tf.float32).
"""
with tf.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 = tf.to_float(x)
y = tf.to_float(y)
z = tf.to_float(z)
depth_f = tf.to_float(depth)
height_f = tf.to_float(height)
width_f = tf.to_float(width)
# Number of disparity interpolated.
out_depth = out_size[0]
out_height = out_size[1]
out_width = out_size[2]
zero = tf.zeros([], dtype='int32')
# 0 <= z < depth, 0 <= y < height & 0 <= x < width.
max_z = tf.to_int32(tf.shape(im)[1] - 1)
max_y = tf.to_int32(tf.shape(im)[2] - 1)
max_x = tf.to_int32(tf.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 = tf.to_int32(tf.floor(x))
x1 = x0 + 1
y0 = tf.to_int32(tf.floor(y))
y1 = y0 + 1
z0 = tf.to_int32(tf.floor(z))
z1 = z0 + 1
x0_clip = tf.clip_by_value(x0, zero, max_x)
x1_clip = tf.clip_by_value(x1, zero, max_x)
y0_clip = tf.clip_by_value(y0, zero, max_y)
y1_clip = tf.clip_by_value(y1, zero, max_y)
z0_clip = tf.clip_by_value(z0, zero, max_z)
z1_clip = tf.clip_by_value(z1, zero, max_z)
dim3 = width
dim2 = width * height
dim1 = width * height * depth
base = _repeat(
tf.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 = tf.reshape(im, tf.stack([-1, channels]))
im_flat = tf.to_float(im_flat)
i_z0_y0_x0 = tf.gather(im_flat, idx_z0_y0_x0)
i_z0_y0_x1 = tf.gather(im_flat, idx_z0_y0_x1)
i_z0_y1_x0 = tf.gather(im_flat, idx_z0_y1_x0)
i_z0_y1_x1 = tf.gather(im_flat, idx_z0_y1_x1)
i_z1_y0_x0 = tf.gather(im_flat, idx_z1_y0_x0)
i_z1_y0_x1 = tf.gather(im_flat, idx_z1_y0_x1)
i_z1_y1_x0 = tf.gather(im_flat, idx_z1_y1_x0)
i_z1_y1_x1 = tf.gather(im_flat, idx_z1_y1_x1)
# Finally calculate interpolated values.
x0_f = tf.to_float(x0)
x1_f = tf.to_float(x1)
y0_f = tf.to_float(y0)
y1_f = tf.to_float(y1)
z0_f = tf.to_float(z0)
z1_f = tf.to_float(z1)
# Check the out-of-boundary case.
x0_valid = tf.to_float(
tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0))
x1_valid = tf.to_float(
tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0))
y0_valid = tf.to_float(
tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0))
y1_valid = tf.to_float(
tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0))
z0_valid = tf.to_float(
tf.less_equal(z0, max_z) & tf.greater_equal(z0, 0))
z1_valid = tf.to_float(
tf.less_equal(z1, max_z) & tf.greater_equal(z1, 0))
w_z0_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) *
(z1_f - z) * x1_valid * y1_valid * z1_valid),
1)
w_z0_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) *
(z1_f - z) * x0_valid * y1_valid * z1_valid),
1)
w_z0_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) *
(z1_f - z) * x1_valid * y0_valid * z1_valid),
1)
w_z0_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) *
(z1_f - z) * x0_valid * y0_valid * z1_valid),
1)
w_z1_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) *
(z - z0_f) * x1_valid * y1_valid * z0_valid),
1)
w_z1_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) *
(z - z0_f) * x0_valid * y1_valid * z0_valid),
1)
w_z1_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) *
(z - z0_f) * x1_valid * y0_valid * z0_valid),
1)
w_z1_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) *
(z - z0_f) * x0_valid * y0_valid * z0_valid),
1)
output = tf.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 tf.variable_scope('_meshgrid'):
x_t = tf.reshape(
tf.tile(tf.linspace(-1.0, 1.0, width), [height * depth]),
[depth, height, width])
y_t = tf.reshape(
tf.tile(tf.linspace(-1.0, 1.0, height), [width * depth]),
[depth, width, height])
y_t = tf.transpose(y_t, [0, 2, 1])
sample_grid = tf.tile(
tf.linspace(float(z_near), float(z_far), depth), [width * height])
z_t = tf.reshape(sample_grid, [height, width, depth])
z_t = tf.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 = tf.reshape(x_t, (1, -1))
y_t_flat = tf.reshape(y_t, (1, -1))
d_t_flat = tf.reshape(d_t, (1, -1))
ones = tf.ones_like(x_t_flat)
grid = tf.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 tf.variable_scope('_transform'):
num_batch = input_dim.get_shape().as_list()[0]
num_channels = input_dim.get_shape().as_list()[4]
theta = tf.reshape(theta, (-1, 4, 4))
theta = tf.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 = tf.expand_dims(grid, 0)
grid = tf.reshape(grid, [-1])
grid = tf.tile(grid, tf.stack([num_batch]))
grid = tf.reshape(grid, tf.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 = tf.matmul(theta, grid)
z_s = tf.slice(t_g, [0, 0, 0], [-1, 1, -1])
y_s = tf.slice(t_g, [0, 1, 0], [-1, 1, -1])
x_s = tf.slice(t_g, [0, 2, 0], [-1, 1, -1])
z_s_flat = tf.reshape(z_s, [-1])
y_s_flat = tf.reshape(y_s, [-1])
x_s_flat = tf.reshape(x_s, [-1])
input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, z_s_flat,
out_size)
output = tf.reshape(
input_transformed,
tf.stack([num_batch, out_depth, out_height, out_width, num_channels]))
return output
with tf.variable_scope(name):
output = _transform(theta, voxels, out_size, z_near, z_far)
return output
| [
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.to_int32",
"tensorflow.linspace",
"tensorflow.add_n",
"tensorflow.floor",
"tensorflow.gather",
"tensorflow.to_float",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.less_equal",
"tensorflow.clip_by_value",
"tensorflow.transpose",
"tensorflow.range",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"tensorflow.variable_scope",
"tensorflow.greater_equal"
] | research/ptn/nets/perspective_transform.py | [(276, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""_repeat"""'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.to_int32', 'tf.to_int32', (['rep'], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.reshape', 'tf.reshape', (['x', '[-1]'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""_interpolate"""'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.to_float', 'tf.to_float', (['x'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.to_float', 'tf.to_float', (['y'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.to_float', 'tf.to_float', (['z'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.to_float', 'tf.to_float', (['depth'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.to_float', 'tf.to_float', (['height'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.to_float', 'tf.to_float', (['width'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.zeros', 'tf.zeros', (['[]'], {'dtype': '"""int32"""'}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['x0', 'zero', 'max_x'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['x1', 'zero', 'max_x'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['y0', 'zero', 'max_y'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['y1', 'zero', 'max_y'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['z0', 'zero', 'max_z'], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['z1', 'zero', 'max_z'], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.to_float', 'tf.to_float', (['im_flat'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z0_y0_x0'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z0_y0_x1'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z0_y1_x0'], {}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z0_y1_x1'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z1_y0_x0'], {}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z1_y0_x1'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z1_y1_x0'], {}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.gather', 'tf.gather', (['im_flat', 'idx_z1_y1_x1'], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.to_float', 'tf.to_float', (['x0'], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.to_float', 'tf.to_float', (['x1'], {}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.to_float', 'tf.to_float', (['y0'], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.to_float', 'tf.to_float', (['y1'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.to_float', 'tf.to_float', (['z0'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.to_float', 'tf.to_float', (['z1'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x1_f - x) * (y1_f - y) * (z1_f - z) * x1_valid * y1_valid * z1_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (184, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x - x0_f) * (y1_f - y) * (z1_f - z) * x0_valid * y1_valid * z1_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (187, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x1_f - x) * (y - y0_f) * (z1_f - z) * x1_valid * y0_valid * z1_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (190, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x - x0_f) * (y - y0_f) * (z1_f - z) * x0_valid * y0_valid * z1_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x1_f - x) * (y1_f - y) * (z - z0_f) * x1_valid * y1_valid * z0_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x - x0_f) * (y1_f - y) * (z - z0_f) * x0_valid * y1_valid * z0_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x1_f - x) * (y - y0_f) * (z - z0_f) * x1_valid * y0_valid * z0_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.expand_dims', 'tf.expand_dims', (['((x - x0_f) * (y - y0_f) * (z - z0_f) * x0_valid * y0_valid * z0_valid)', '(1)'], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.add_n', 'tf.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,\n w_z0_y1_x1 * i_z0_y1_x1, w_z1_y0_x0 * i_z1_y0_x0, w_z1_y0_x1 *\n i_z1_y0_x1, w_z1_y1_x0 * i_z1_y1_x0, w_z1_y1_x1 * i_z1_y1_x1]'], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""_meshgrid"""'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.transpose', 'tf.transpose', (['y_t', '[0, 2, 1]'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.reshape', 'tf.reshape', (['sample_grid', '[height, width, depth]'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.transpose', 'tf.transpose', (['z_t', '[2, 0, 1]'], {}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.reshape', 'tf.reshape', (['x_t', '(1, -1)'], {}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.reshape', 'tf.reshape', (['y_t', '(1, -1)'], {}), True, 'import tensorflow as tf\n'), (235, 'tensorflow.reshape', 'tf.reshape', (['d_t', '(1, -1)'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.ones_like', 'tf.ones_like', (['x_t_flat'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.concat', 'tf.concat', (['[d_t_flat, y_t_flat, x_t_flat, ones]', '(0)'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""_transform"""'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.reshape', 'tf.reshape', (['theta', '(-1, 4, 4)'], {}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.cast', 'tf.cast', (['theta', '"""float32"""'], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.expand_dims', 'tf.expand_dims', (['grid', '(0)'], {}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.reshape', 'tf.reshape', (['grid', '[-1]'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.matmul', 'tf.matmul', (['theta', 'grid'], {}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.slice', 'tf.slice', (['t_g', '[0, 0, 0]', '[-1, 1, -1]'], {}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.slice', 'tf.slice', (['t_g', '[0, 1, 0]', '[-1, 1, -1]'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.slice', 'tf.slice', (['t_g', '[0, 2, 0]', '[-1, 1, -1]'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.reshape', 'tf.reshape', (['z_s', '[-1]'], {}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.reshape', 'tf.reshape', (['y_s', '[-1]'], {}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.reshape', 'tf.reshape', (['x_s', '[-1]'], {}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.reshape', 'tf.reshape', (['x', '(-1, 1)'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.floor', 'tf.floor', (['x'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.floor', 'tf.floor', (['y'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.floor', 'tf.floor', (['z'], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.stack', 'tf.stack', (['[-1, channels]'], {}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.stack', 'tf.stack', (['[num_batch]'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.stack', 'tf.stack', (['[num_batch, 4, -1]'], {}), True, 'import tensorflow as tf\n'), (272, 'tensorflow.stack', 'tf.stack', (['[num_batch, out_depth, out_height, out_width, num_channels]'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.range', 'tf.range', (['num_batch'], {}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.less_equal', 'tf.less_equal', (['x0', 'max_x'], {}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.greater_equal', 'tf.greater_equal', (['x0', '(0)'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.less_equal', 'tf.less_equal', (['x1', 'max_x'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.greater_equal', 'tf.greater_equal', (['x1', '(0)'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.less_equal', 'tf.less_equal', (['y0', 'max_y'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.greater_equal', 'tf.greater_equal', (['y0', '(0)'], {}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.less_equal', 'tf.less_equal', (['y1', 'max_y'], {}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.greater_equal', 'tf.greater_equal', (['y1', '(0)'], {}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.less_equal', 'tf.less_equal', (['z0', 'max_z'], {}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.greater_equal', 'tf.greater_equal', (['z0', '(0)'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.less_equal', 'tf.less_equal', (['z1', 'max_z'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.greater_equal', 'tf.greater_equal', (['z1', '(0)'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.linspace', 'tf.linspace', (['(-1.0)', '(1.0)', 'width'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.linspace', 'tf.linspace', (['(-1.0)', '(1.0)', 'height'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.shape', 'tf.shape', (['im'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.shape', 'tf.shape', (['im'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.shape', 'tf.shape', (['im'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.stack', 'tf.stack', (['[n_repeats]'], {}), True, 'import tensorflow as tf\n')] |
BreastGAN/augmentation | 0e1bcb7175e2b2a45cd8084bb14521e26b68caea | # Copyright 2019 Lukas Jendele and Ondrej Skopek.
# Adapted from The TensorFlow 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/tensorflow/tensorflow/blob/r1.11/tensorflow/contrib/layers/python/layers/layers.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework.python.ops import add_arg_scope
# from tensorflow.contrib.framework.python.ops import variables
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.contrib.layers.python.layers import utils
# from tensorflow.python.eager import context
# from tensorflow.python.framework import constant_op
# from tensorflow.python.framework import dtypes
# from tensorflow.python.framework import function
from tensorflow.python.framework import ops
# from tensorflow.python.framework import sparse_tensor
from tensorflow.python.layers import convolutional as convolutional_layers
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import variable_scope
# My imports
from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections
from models.breast_cycle_gan.custom.conv.layers import MyConv2D
import tensorflow as tf
# This part is copied from:
# https://github.com/tensorflow/tensorflow/blob/r1.11/tensorflow/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 tf.variable_scope("self_attention"):
with tf.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 tf.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 tf.reshape(x, shape=[x.shape[0], -1, x.shape[-1]])
# N = h * w
s = tf.matmul(hw_flatten(g), hw_flatten(f), transpose_b=True) # # [bs, N, N]
beta = tf.nn.softmax(s, axis=-1) # attention map
o = tf.matmul(beta, hw_flatten(h)) # [bs, N, C]
gamma = tf.get_variable("gamma", [1], initializer=tf.constant_initializer(0.0))
o = tf.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 tf.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)
| [
"tensorflow.nn.softmax",
"tensorflow.contrib.layers.python.layers.initializers.xavier_initializer",
"tensorflow.reshape",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.constant_initializer",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.variable_scope",
"tensorflow.contrib.layers.python.layers.layers._build_variable_getter",
"tensorflow.contrib.layers.python.layers.layers._add_variable_to_collections",
"tensorflow.contrib.layers.python.layers.utils.collect_named_outputs"
] | models/breast_cycle_gan/custom/conv/contrib.py | [(56, 'tensorflow.contrib.layers.python.layers.initializers.xavier_initializer', 'initializers.xavier_initializer', ([], {}), False, 'from tensorflow.contrib.layers.python.layers import initializers\n'), (58, 'tensorflow.python.ops.init_ops.zeros_initializer', 'init_ops.zeros_initializer', ([], {}), False, 'from tensorflow.python.ops import init_ops\n'), (171, 'tensorflow.contrib.layers.python.layers.initializers.xavier_initializer', 'initializers.xavier_initializer', ([], {}), False, 'from tensorflow.contrib.layers.python.layers import initializers\n'), (173, 'tensorflow.python.ops.init_ops.zeros_initializer', 'init_ops.zeros_initializer', ([], {}), False, 'from tensorflow.python.ops import init_ops\n'), (252, 'tensorflow.contrib.layers.python.layers.layers._build_variable_getter', '_build_variable_getter', (["{'bias': 'biases', 'kernel': 'weights'}"], {}), False, 'from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections\n'), (93, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""self_attention"""'], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['s'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.reshape', 'tf.reshape', (['o'], {'shape': 'inputs.shape'}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['scope', '"""Conv"""', '[inputs]'], {'reuse': 'reuse', 'custom_getter': 'layer_variable_getter'}), False, 'from tensorflow.python.ops import variable_scope\n'), (255, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['inputs'], {}), False, 'from tensorflow.python.framework import ops\n'), (294, 'tensorflow.contrib.layers.python.layers.layers._add_variable_to_collections', '_add_variable_to_collections', (['layer.kernel', 'variables_collections', '"""weights"""'], {}), False, 'from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections\n'), (304, 'tensorflow.contrib.layers.python.layers.utils.collect_named_outputs', 'utils.collect_named_outputs', (['outputs_collections', 'sc.name', 'outputs'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (94, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""f"""'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""g"""'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.reshape', 'tf.reshape', (['x'], {'shape': '[x.shape[0], -1, x.shape[-1]]'}), True, 'import tensorflow as tf\n'), (296, 'tensorflow.contrib.layers.python.layers.layers._add_variable_to_collections', '_add_variable_to_collections', (['layer.bias', 'variables_collections', '"""biases"""'], {}), False, 'from tensorflow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections\n'), (152, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n')] |
LinZichuan/AdMRL | 50a22d4d480e99125cc91cc65dfcc0df4a883ac6 | import sys
sys.path = ['./rllab/'] + sys.path
print (sys.path)
import pickle
import os,time
from collections import deque
import tensorflow as tf
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 = tf.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 = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(normalizers_copy_parameters, normalizers_parameters)])
revert_normalizers = tf.group(*[tf.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 = tf.group(*[tf.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 = tf.group(*[tf.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 = tf.group(*[tf.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 = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(model.parameters(), lazy_model.parameters())])
sync_model_to_lazymodel = tf.group(*[tf.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)
tf.get_default_session().run(tf.global_variables_initializer())
print ("norm params:", normalizers_parameters)
print ("norm_copy params:", normalizers_copy_parameters)
norm_before = tf.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)')
tf.get_default_session().run(sync_model_to_lazymodel)
tf.get_default_session().run(copy_normalizers)
logger.info('Loaded normalizers:')
load_norm = tf.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)')
tf.get_default_session().run(sync_model_to_lazymodel)
tf.get_default_session().run(copy_normalizers)
logger.info('Loaded normalizers:')
load_norm = tf.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')
tf.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')
tf.get_default_session().run(sync_model_from_lazymodel)
tf.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 = tf.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters())])
tf.get_default_session().run(tf.variables_initializer(policy.parameters()))
pol_params_after = tf.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")
tf.get_default_session().run(tf.variables_initializer(vfn.parameters()))
tf.get_default_session().run(tf.variables_initializer(warmup_policy.parameters()))
tf.get_default_session().run(tf.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')
tf.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 = tf.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 = tf.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 = tf.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")
tf.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 tf.Session(config=get_tf_config()):
main()
| [
"tensorflow.get_default_session",
"numpy.allclose",
"numpy.isnan",
"tensorflow.assign",
"numpy.linalg.norm",
"numpy.concatenate",
"tensorflow.global_variables_initializer",
"numpy.std",
"numpy.mean",
"numpy.prod",
"numpy.load",
"numpy.array"
] | main.py | [(101, 'click.command', 'click.command', ([], {}), False, 'import click\n'), (102, 'click.option', 'click.option', (['"""--setting"""'], {'default': '"""default"""'}), False, 'import click\n'), (103, 'click.option', 'click.option', (['"""--adv"""'], {'default': '(1)'}), False, 'import click\n'), (104, 'click.option', 'click.option', (['"""--gpu"""'], {'default': '(0)'}), False, 'import click\n'), (105, 'click.option', 'click.option', (['"""--debug"""'], {'is_flag': '(True)', 'default': '(False)'}), False, 'import click\n'), (106, 'click.option', 'click.option', (['"""--taskname"""'], {'default': '"""Ant2D"""'}), False, 'import click\n'), (107, 'click.option', 'click.option', (['"""--verbose"""'], {'is_flag': '(True)', 'default': '(False)'}), False, 'import click\n'), (108, 'click.option', 'click.option', (['"""--test"""'], {'is_flag': '(True)', 'default': '(False)'}), False, 'import click\n'), (109, 'click.option', 'click.option', (['"""--warmupent"""'], {'default': '(0.005)'}), False, 'import click\n'), (110, 'click.option', 'click.option', (['"""--alpha"""'], {'default': '(1.0)'}), False, 'import click\n'), (111, 'click.option', 'click.option', (['"""--beta"""'], {'default': '(1.0)'}), False, 'import click\n'), (112, 'click.option', 'click.option', (['"""--snapshot"""'], {'default': '(1)'}), False, 'import click\n'), (113, 'click.option', 'click.option', (['"""--testadv"""'], {'default': '(0)'}), False, 'import click\n'), (114, 'click.option', 'click.option', (['"""--seed"""'], {'default': '(1)'}), False, 'import click\n'), (115, 'click.option', 'click.option', (['"""--nsample"""'], {'default': '(10000)'}), False, 'import click\n'), (116, 'click.option', 'click.option', (['"""--fixedvel"""'], {'default': 'None'}), False, 'import click\n'), (117, 'click.option', 'click.option', (['"""--initnslbo"""'], {'default': '(20)'}), False, 'import click\n'), (118, 'click.option', 'click.option', (['"""--nslbo"""'], {'default': '(3)'}), False, 'import click\n'), (119, 'click.option', 'click.option', (['"""--warmniter"""'], {'default': '(40)'}), False, 'import click\n'), (120, 'click.option', 'click.option', (['"""--slboniter"""'], {'default': '(20)'}), False, 'import click\n'), (121, 'click.option', 'click.option', (['"""--piter"""'], {'default': '(20)'}), False, 'import click\n'), (122, 'click.option', 'click.option', (['"""--miter"""'], {'default': '(100)'}), False, 'import click\n'), (123, 'click.option', 'click.option', (['"""--atype"""'], {'default': '"""gae"""'}), False, 'import click\n'), (124, 'click.option', 'click.option', (['"""--video"""'], {'is_flag': '(True)', 'default': '(False)'}), False, 'import click\n'), (125, 'click.option', 'click.option', (['"""--maxstep"""'], {'default': '(1)'}), False, 'import click\n'), (126, 'click.option', 'click.option', (['"""--genadvstrategy"""'], {'default': 'None'}), False, 'import click\n'), (127, 'click.option', 'click.option', (['"""--inittask"""'], {'default': '"""none"""'}), False, 'import click\n'), (128, 'click.option', 'click.option', (['"""--decay"""'], {'default': '"""joint"""'}), False, 'import click\n'), (129, 'click.option', 'click.option', (['"""--testgiven"""'], {'default': 'None'}), False, 'import click\n'), (130, 'click.option', 'click.option', (['"""--testnum"""'], {'default': '(1)'}), False, 'import click\n'), (131, 'click.option', 'click.option', (['"""--testparam"""'], {'default': '""""""'}), False, 'import click\n'), (33, 'lunzi.Logger.logger.info', 'logger.info', (['"""start render video..."""'], {}), False, 'from lunzi.Logger import logger\n'), (53, 'lunzi.Logger.logger.info', 'logger.info', (['f"""render {cnt_} steps, return = {return_:.6f}"""'], {}), False, 'from lunzi.Logger import logger\n'), (58, 'lunzi.Logger.logger.info', 'logger.info', (['des'], {}), False, 'from lunzi.Logger import logger\n'), (71, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (135, 'os.path.join', 'os.path.join', (['"""./data/"""', 'setting'], {}), False, 'import os, time\n'), (177, 'slbo.utils.flags.FLAGS.set_seed', 'FLAGS.set_seed', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (178, 'slbo.utils.flags.FLAGS.freeze', 'FLAGS.freeze', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (186, 'slbo.partial_envs.make_task', 'make_task', (['FLAGS.env.id'], {}), False, 'from slbo.partial_envs import make_env, make_task\n'), (187, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (193, 'slbo.utils.normalizer.Normalizers', 'Normalizers', ([], {'dim_action': 'dim_action', 'dim_state': 'dim_state'}), False, 'from slbo.utils.normalizer import Normalizers\n'), (194, 'slbo.utils.normalizer.Normalizers', 'Normalizers', ([], {'dim_action': 'dim_action', 'dim_state': 'dim_state'}), False, 'from slbo.utils.normalizer import Normalizers\n'), (200, 'slbo.utils.dataset.gen_dtype', 'gen_dtype', (['env', '"""state action next_state reward done timeout"""'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (201, 'slbo.utils.dataset.Dataset', 'Dataset', (['dtype', 'FLAGS.rollout.max_buf_size'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (202, 'slbo.utils.dataset.Dataset', 'Dataset', (['dtype', 'FLAGS.rollout.max_buf_size'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (213, 'slbo.utils.OU_noise.OUNoise', 'OUNoise', (['env.action_space'], {'theta': 'FLAGS.OUNoise.theta', 'sigma': 'FLAGS.OUNoise.sigma', 'shape': '(1, dim_action)'}), False, 'from slbo.utils.OU_noise import OUNoise\n'), (214, 'slbo.v_function.mlp_v_function.MLPVFunction', 'MLPVFunction', (['dim_state', '[64, 64]', 'normalizers.state'], {}), False, 'from slbo.v_function.mlp_v_function import MLPVFunction\n'), (215, 'slbo.v_function.mlp_v_function.MLPVFunction', 'MLPVFunction', (['dim_state', '[64, 64]', 'normalizers.state'], {}), False, 'from slbo.v_function.mlp_v_function import MLPVFunction\n'), (218, 'slbo.dynamics_model.DynamicsModel', 'DynamicsModel', (['dim_state', 'dim_action', 'normalizers', 'FLAGS.model.hidden_sizes'], {}), False, 'from slbo.dynamics_model import DynamicsModel\n'), (219, 'slbo.dynamics_model.DynamicsModel', 'DynamicsModel', (['dim_state', 'dim_action', 'normalizers', 'FLAGS.model.hidden_sizes'], {}), False, 'from slbo.dynamics_model import DynamicsModel\n'), (220, 'slbo.dynamics_model.DynamicsModel', 'DynamicsModel', (['dim_state', 'dim_action', 'normalizers', 'FLAGS.model.hidden_sizes'], {}), False, 'from slbo.dynamics_model import DynamicsModel\n'), (238, 'lunzi.Logger.logger.info', 'logger.info', (["('FLAGS.plan.n_envs=%d' % FLAGS.plan.n_envs)"], {}), False, 'from lunzi.Logger import logger\n'), (248, 'slbo.loss.multi_step_loss.MultiStepLoss', 'MultiStepLoss', (['model', 'normalizers', 'dim_state', 'dim_action', 'criterion', 'FLAGS.model.multi_step'], {}), False, 'from slbo.loss.multi_step_loss import MultiStepLoss\n'), (254, 'slbo.algos.ADVTASK.ADVTASK', 'ADVTASK', (['dim_state', 'dim_action', 'policy', 'vfn', 'warmup_policy', 'warmup_vfn', 'task'], {'alpha': 'alpha', 'beta': 'beta', 'nsample': 'nsample', 'atype': 'atype'}), False, 'from slbo.algos.ADVTASK import ADVTASK\n'), (282, 'lunzi.nn.ModuleDict', 'nn.ModuleDict', (["{'policy': policy, 'model': model, 'vfn': vfn, 'normalizers': normalizers}"], {}), True, 'import lunzi.nn as nn\n'), (316, 'lunzi.Logger.logger.info', 'logger.info', (['f"""inittask:{inittask}"""'], {}), False, 'from lunzi.Logger import logger\n'), (63, 'numpy.mean', 'np.mean', (['data.state'], {}), True, 'import numpy as np\n'), (64, 'numpy.mean', 'np.mean', (['data.action'], {}), True, 'import numpy as np\n'), (79, 'numpy.array', 'np.array', (["[ep_info['return'] for ep_info in ep_infos]"], {}), True, 'import numpy as np\n'), (80, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (159, 'os.path.isdir', 'os.path.isdir', (['setting'], {}), False, 'import os, time\n'), (160, 'os.makedirs', 'os.makedirs', (['setting'], {}), False, 'import os, time\n'), (169, 'lunzi.Logger.logger.info', 'logger.info', (['f"""fixedvel={fixedvel}"""'], {}), False, 'from lunzi.Logger import logger\n'), (188, 'numpy.prod', 'np.prod', (['env.observation_space.shape'], {}), True, 'import numpy as np\n'), (189, 'numpy.prod', 'np.prod', (['env.action_space.shape'], {}), True, 'import numpy as np\n'), (203, 'slbo.utils.dataset.Dataset', 'Dataset', (['dtype', 'FLAGS.rollout.max_buf_size'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (204, 'slbo.utils.dataset.Dataset', 'Dataset', (['dtype', 'FLAGS.rollout.max_buf_size'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (222, 'slbo.dynamics_model.DynamicsModel', 'DynamicsModel', (['dim_state', 'dim_action', 'normalizers', 'FLAGS.model.hidden_sizes'], {}), False, 'from slbo.dynamics_model import DynamicsModel\n'), (226, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (228, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (235, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (243, 'lunzi.nn.L1Loss', 'nn.L1Loss', ([], {}), True, 'import lunzi.nn as nn\n'), (244, 'lunzi.nn.L2Loss', 'nn.L2Loss', ([], {}), True, 'import lunzi.nn as nn\n'), (245, 'lunzi.nn.MSELoss', 'nn.MSELoss', ([], {}), True, 'import lunzi.nn as nn\n'), (250, 'slbo.loss.multi_step_loss.MultiStepLoss', 'MultiStepLoss', (['shadow_model', 'normalizers', 'dim_state', 'dim_action', 'criterion', 'FLAGS.model.multi_step'], {}), False, 'from slbo.loss.multi_step_loss import MultiStepLoss\n'), (255, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (375, 'lunzi.Logger.logger.info', 'logger.info', (['"""Testing mode!"""'], {}), False, 'from lunzi.Logger import logger\n'), (378, 'lunzi.Logger.logger.info', 'logger.info', (['f"""train_tasknum = {train_tasknum}, test_tasknum = {test_tasknum}"""'], {}), False, 'from lunzi.Logger import logger\n'), (433, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Load the task{snapshot} saver!"""'], {}), False, 'from lunzi.Logger import logger\n'), (436, 'lunzi.Logger.logger.info', 'logger.info', (['"""Update all copies! (lazymodel, normalizers_copy)"""'], {}), False, 'from lunzi.Logger import logger\n'), (439, 'lunzi.Logger.logger.info', 'logger.info', (['"""Loaded normalizers:"""'], {}), False, 'from lunzi.Logger import logger\n'), (441, 'lunzi.Logger.logger.info', 'logger.info', (['load_norm'], {}), False, 'from lunzi.Logger import logger\n'), (474, 'lunzi.Logger.logger.info', 'logger.info', (['"""Sync model from lazymodel"""'], {}), False, 'from lunzi.Logger import logger\n'), (486, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (490, 'collections.deque', 'deque', ([], {'maxlen': '(warmup_n_model_iters // FLAGS.model.validation_freq)'}), False, 'from collections import deque\n'), (491, 'collections.deque', 'deque', ([], {'maxlen': '(slbo_n_model_iters // FLAGS.model.validation_freq)'}), False, 'from collections import deque\n'), (492, 'collections.deque', 'deque', ([], {'maxlen': '(warmup_n_model_iters // FLAGS.model.validation_freq)'}), False, 'from collections import deque\n'), (493, 'collections.deque', 'deque', ([], {'maxlen': '(slbo_n_model_iters // FLAGS.model.validation_freq)'}), False, 'from collections import deque\n'), (571, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (574, 'lunzi.Logger.logger.info', 'logger.info', (["('----------------------------- Warmup for %d iterations ------------------------'\n % warmup_n_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (685, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (694, 'lunzi.Logger.logger.info', 'logger.info', (['"""Sync warmup policy and vfn and model"""'], {}), False, 'from lunzi.Logger import logger\n'), (713, 'lunzi.Logger.logger.info', 'logger.info', (["('--------------------------------------------- SLBO for %d outer stages -----------------------------------------'\n % slbo_n_stages)"], {}), False, 'from lunzi.Logger import logger\n'), (914, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (917, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Warmup time = {warmup_time}, SLBO time = {slbo_time}"""'], {}), False, 'from lunzi.Logger import logger\n'), (961, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (62, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (82, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (82, 'numpy.std', 'np.std', (['returns'], {}), True, 'import numpy as np\n'), (97, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task_config'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (98, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (171, 'lunzi.Logger.logger.info', 'logger.info', (['"""Test with adversarial generated tasks!"""'], {}), False, 'from lunzi.Logger import logger\n'), (172, 'lunzi.Logger.logger.info', 'logger.info', (['f"""testadv=1, maxstep={maxstep}, using model revert!"""'], {}), False, 'from lunzi.Logger import logger\n'), (174, 'lunzi.Logger.logger.info', 'logger.info', (['"""We still do not consider this senario: test with random tasks"""'], {}), False, 'from lunzi.Logger import logger\n'), (207, 'slbo.utils.flags.FLAGS.policy.as_dict', 'FLAGS.policy.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (208, 'slbo.utils.flags.FLAGS.policy.as_dict', 'FLAGS.policy.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (239, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (253, 'slbo.utils.flags.FLAGS.TRPO.as_dict', 'FLAGS.TRPO.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (255, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (386, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Load all tasks from {f}!"""'], {}), False, 'from lunzi.Logger import logger\n'), (388, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Test on task"""'], {}), False, 'from lunzi.Logger import logger\n'), (389, 'lunzi.Logger.logger.info', 'logger.info', (['task.fixed_velocities'], {}), False, 'from lunzi.Logger import logger\n'), (394, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Load all adversarial task from {f}!"""'], {}), False, 'from lunzi.Logger import logger\n'), (396, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Test random method on task {train_tasknum}~{train_tasknum + test_tasknum}:"""'], {}), False, 'from lunzi.Logger import logger\n'), (397, 'lunzi.Logger.logger.info', 'logger.info', (['task.fixed_velocities'], {}), False, 'from lunzi.Logger import logger\n'), (418, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Load all task dataset from {setting}!"""'], {}), False, 'from lunzi.Logger import logger\n'), (499, 'lunzi.Logger.logger.info', 'logger.info', (['"""################################################## TESTING TASK %d ################################################"""', 'TEST_TASK_NUM'], {}), False, 'from lunzi.Logger import logger\n'), (500, 'lunzi.Logger.logger.info', 'logger.info', (['f"""TEST_TASK_NUM={TEST_TASK_NUM}, TASK_NUM={TASK_NUM}"""'], {}), False, 'from lunzi.Logger import logger\n'), (501, 'lunzi.Logger.logger.warning', 'logger.warning', (['"""Revert model and normalizers"""'], {}), False, 'from lunzi.Logger import logger\n'), (505, 'lunzi.Logger.logger.info', 'logger.info', (['"""################################################## TRAINING TASK %d ################################################"""', 'TASK_NUM'], {}), False, 'from lunzi.Logger import logger\n'), (527, 'lunzi.Logger.logger.info', 'logger.info', (['"""Task Sampled: %s"""', 'task.goal_velocity'], {}), False, 'from lunzi.Logger import logger\n'), (548, 'lunzi.Logger.logger.info', 'logger.info', (['"""Resetting Policy"""'], {}), False, 'from lunzi.Logger import logger\n'), (553, 'lunzi.Logger.logger.info', 'logger.info', (['"""Resetting Valuefunc"""'], {}), False, 'from lunzi.Logger import logger\n'), (576, 'lunzi.Logger.logger.info', 'logger.info', (['"""Joint train from a joint dataset"""'], {}), False, 'from lunzi.Logger import logger\n'), (591, 'collections.deque', 'deque', ([], {'maxlen': 'warmup_n_model_iters'}), False, 'from collections import deque\n'), (592, 'slbo.utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), False, 'from slbo.utils.average_meter import AverageMeter\n'), (601, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (646, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (703, 'numpy.linalg.norm', 'np.linalg.norm', (['pol_params'], {}), True, 'import numpy as np\n'), (703, 'numpy.linalg.norm', 'np.linalg.norm', (['warm_params'], {}), True, 'import numpy as np\n'), (705, 'numpy.linalg.norm', 'np.linalg.norm', (['mod'], {}), True, 'import numpy as np\n'), (705, 'numpy.linalg.norm', 'np.linalg.norm', (['warm_mod'], {}), True, 'import numpy as np\n'), (715, 'lunzi.Logger.logger.info', 'logger.info', (['"""-------- Starting Stage %d ---------"""', 'T'], {}), False, 'from lunzi.Logger import logger\n'), (728, 'lunzi.Logger.logger.info', 'logger.info', (['"""save setting dataset! trainset and devset!"""'], {}), False, 'from lunzi.Logger import logger\n'), (748, 'slbo.utils.dataset.Dataset', 'Dataset', (['dtype', 'FLAGS.rollout.max_buf_size'], {}), False, 'from slbo.utils.dataset import Dataset, gen_dtype\n'), (756, 'numpy.mean', 'np.mean', (['losses_new'], {}), True, 'import numpy as np\n'), (758, 'lunzi.Logger.logger.info', 'logger.info', (['f"""(surprisal) model loss on new collected data is {losses_new_mean}"""'], {}), False, 'from lunzi.Logger import logger\n'), (766, 'numpy.array', 'np.array', (["[ep_info['return'] for ep_info in ep_infos]"], {}), True, 'import numpy as np\n'), (786, 'lunzi.Logger.logger.info', 'logger.info', (["('SLBO for %d inner stages' % slbo_n_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (909, 'numpy.linalg.norm', 'np.linalg.norm', (['pol_params'], {}), True, 'import numpy as np\n'), (909, 'numpy.linalg.norm', 'np.linalg.norm', (['warm_params'], {}), True, 'import numpy as np\n'), (935, 'lunzi.Logger.logger.info', 'logger.info', (['f"""task_num={TASK_NUM}, sync_model_to_lazymodel"""'], {}), False, 'from lunzi.Logger import logger\n'), (197, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (198, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (221, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.assign', 'tf.assign', (['w_v', 'p_v'], {}), True, 'import tensorflow as tf\n'), (227, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (229, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (232, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (236, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (323, 'lunzi.Logger.logger.info', 'logger.info', (['"""Load the first task dataset!"""'], {}), False, 'from lunzi.Logger import logger\n'), (337, 'lunzi.Logger.logger.info', 'logger.info', (['"""Load the first task saver!"""'], {}), False, 'from lunzi.Logger import logger\n'), (340, 'lunzi.Logger.logger.info', 'logger.info', (['"""Update all copies! (lazymodel, normalizers_copy)"""'], {}), False, 'from lunzi.Logger import logger\n'), (343, 'lunzi.Logger.logger.info', 'logger.info', (['"""Loaded normalizers:"""'], {}), False, 'from lunzi.Logger import logger\n'), (345, 'lunzi.Logger.logger.info', 'logger.info', (['load_norm'], {}), False, 'from lunzi.Logger import logger\n'), (402, 'lunzi.Logger.logger.info', 'logger.info', (['"""Load the first task dataset!"""'], {}), False, 'from lunzi.Logger import logger\n'), (434, 'numpy.load', 'np.load', (['f"""./{setting}/{taskname}.task{snapshot}.saver.npy"""'], {'allow_pickle': '(True)'}), True, 'import numpy as np\n'), (437, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (438, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (440, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (475, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (534, 'lunzi.Logger.logger.info', 'logger.info', (['"""Task Fixed: %s"""', 'task.goal_velocity'], {}), False, 'from lunzi.Logger import logger\n'), (537, 'lunzi.Logger.logger.info', 'logger.info', (['"""Task Sampled: %s"""', 'task.goal_velocity'], {}), False, 'from lunzi.Logger import logger\n'), (540, 'lunzi.Logger.logger.info', 'logger.info', (['"""Task Sampled: %s"""', 'task.goal_velocity'], {}), False, 'from lunzi.Logger import logger\n'), (542, 'lunzi.Logger.logger.info', 'logger.info', (['"""Tasks dump!"""'], {}), False, 'from lunzi.Logger import logger\n'), (552, 'numpy.linalg.norm', 'np.linalg.norm', (['pol_params'], {}), True, 'import numpy as np\n'), (552, 'numpy.linalg.norm', 'np.linalg.norm', (['pol_params_after'], {}), True, 'import numpy as np\n'), (580, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Sampling prop={prop}, Z={Z}"""'], {}), False, 'from lunzi.Logger import logger\n'), (588, 'lunzi.Logger.logger.info', 'logger.info', (['"""Break because TASK_NUM=0"""'], {}), False, 'from lunzi.Logger import logger\n'), (596, 'lunzi.Logger.logger.info', 'logger.info', (['f"""warmup iter #{i}/{warmup_n_iters}, Do Not train Model during warmup of test time"""'], {}), False, 'from lunzi.Logger import logger\n'), (600, 'lunzi.Logger.logger.info', 'logger.info', (["('Train Model for %d iterations' % n_model_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (645, 'lunzi.Logger.logger.info', 'logger.info', (["('Train policy for %d iterations' % warmup_n_policy_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (662, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (668, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (695, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (702, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (704, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (720, 'lunzi.Logger.logger.info', 'logger.info', (["('-------- Collect data from REAL env for %d samples --------' % FLAGS.\n rollout.n_train_samples)"], {}), False, 'from lunzi.Logger import logger\n'), (724, 'lunzi.Logger.logger.info', 'logger.info', (["('-------- Collect data from REAL env for %d samples --------' % 2000)"], {}), False, 'from lunzi.Logger import logger\n'), (791, 'lunzi.Logger.logger.info', 'logger.info', (['"""Joint train from a joint dataset"""'], {}), False, 'from lunzi.Logger import logger\n'), (811, 'collections.deque', 'deque', ([], {'maxlen': 'slbo_n_model_iters'}), False, 'from collections import deque\n'), (812, 'slbo.utils.average_meter.AverageMeter', 'AverageMeter', ([], {}), False, 'from slbo.utils.average_meter import AverageMeter\n'), (815, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (863, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (908, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (957, 'pickle.dump', 'pickle.dump', (['advtask_info', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), False, 'import pickle\n'), (967, 'slbo.utils.tf_utils.get_tf_config', 'get_tf_config', ([], {}), False, 'from slbo.utils.tf_utils import get_tf_config\n'), (232, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (240, 'slbo.utils.flags.FLAGS.runner.as_dict', 'FLAGS.runner.as_dict', ([], {}), False, 'from slbo.utils.flags import FLAGS\n'), (320, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.trainset.task0.slbo0.pkl"""'], {}), False, 'import os, time\n'), (320, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.task0.saver.npy"""'], {}), False, 'import os, time\n'), (502, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (503, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (549, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (550, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (551, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (554, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (556, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (557, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (584, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Sampling prop={prop}, Z={Z}"""'], {}), False, 'from lunzi.Logger import logger\n'), (621, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (625, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (636, 'numpy.mean', 'np.mean', (['task_val_loss'], {}), True, 'import numpy as np\n'), (643, 'lunzi.Logger.logger.info', 'logger.info', (['f"""# task_val_loss: {task_val_loss}"""'], {}), False, 'from lunzi.Logger import logger\n'), (680, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (682, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (768, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (774, 'numpy.allclose', 'np.allclose', (['(samples.state[i + 1] * masks)', '(samples.next_state[i] * masks)'], {}), True, 'import numpy as np\n'), (795, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Sampling prop={prop}, Z={Z}"""'], {}), False, 'from lunzi.Logger import logger\n'), (814, 'lunzi.Logger.logger.info', 'logger.info', (["('Train model %d iterations' % n_model_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (837, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (841, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (851, 'numpy.mean', 'np.mean', (['task_val_loss'], {}), True, 'import numpy as np\n'), (857, 'lunzi.Logger.logger.info', 'logger.info', (['f"""# task_val_loss: {task_val_loss}"""'], {}), False, 'from lunzi.Logger import logger\n'), (862, 'lunzi.Logger.logger.info', 'logger.info', (["('Train policy %d iterations' % slbo_n_policy_iters)"], {}), False, 'from lunzi.Logger import logger\n'), (880, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (936, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (325, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (332, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.devset.task0.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (338, 'numpy.load', 'np.load', (['f"""./{inittask}/{taskname}.task0.saver.npy"""'], {'allow_pickle': '(True)'}), True, 'import numpy as np\n'), (341, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (404, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (412, 'os.path.exists', 'os.path.exists', (['f"""./{inittask}/{taskname}.devset.task0.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (421, 'os.path.exists', 'os.path.exists', (['f"""./{setting}/{taskname}.trainset.task{t}.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (426, 'os.path.exists', 'os.path.exists', (['f"""./{setting}/{taskname}.devset.task{t}.slbo{i}.pkl"""'], {}), False, 'import os, time\n'), (632, 'numpy.mean', 'np.mean', (['total_loss'], {}), True, 'import numpy as np\n'), (635, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (638, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (639, 'numpy.isnan', 'np.isnan', (['val_loss'], {}), True, 'import numpy as np\n'), (642, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (666, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (799, 'lunzi.Logger.logger.info', 'logger.info', (['f"""Sampling prop={prop}, Z={Z}"""'], {}), False, 'from lunzi.Logger import logger\n'), (848, 'numpy.mean', 'np.mean', (['total_loss'], {}), True, 'import numpy as np\n'), (852, 'time.time', 'time.time', ([], {}), False, 'import os, time\n'), (853, 'numpy.isnan', 'np.isnan', (['val_loss'], {}), True, 'import numpy as np\n'), (856, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (860, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (885, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (897, 'slbo.partial_envs.make_env', 'make_env', (['FLAGS.env.id'], {'task_config': 'task'}), False, 'from slbo.partial_envs import make_env, make_task\n'), (390, 'numpy.array', 'np.array', (['task.fixed_velocities'], {}), True, 'import numpy as np\n'), (398, 'numpy.array', 'np.array', (['task.fixed_velocities'], {}), True, 'import numpy as np\n'), (639, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (640, 'numpy.isnan', 'np.isnan', (['val_loss'], {}), True, 'import numpy as np\n'), (660, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (666, 'numpy.std', 'np.std', (['returns'], {}), True, 'import numpy as np\n'), (853, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (854, 'numpy.isnan', 'np.isnan', (['val_loss'], {}), True, 'import numpy as np\n'), (878, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (611, 'numpy.concatenate', 'np.concatenate', (['all_samples'], {'axis': '(1)'}), True, 'import numpy as np\n'), (640, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (661, 'numpy.mean', 'np.mean', (['returns'], {}), True, 'import numpy as np\n'), (826, 'numpy.concatenate', 'np.concatenate', (['all_samples'], {'axis': '(1)'}), True, 'import numpy as np\n'), (854, 'numpy.mean', 'np.mean', (['losses'], {}), True, 'import numpy as np\n'), (878, 'numpy.std', 'np.std', (['returns'], {}), True, 'import numpy as np\n')] |
rcelebi/android-elfali | 4ea14a58a18356ef9e16aba2e7dae84c02afba12 | # Copyright 2016 The TensorFlow 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.
# ==============================================================================
"""TensorFlow 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 tensorflow.contrib import layers
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.layers.python.layers import feature_column_ops
from tensorflow.contrib.learn.python.learn.estimators import composable_model
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import parsing_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.training import training
# TODO(ispir): Increase test coverage
class _DNNLinearCombinedBaseEstimator(estimator.BaseEstimator):
"""An estimator for TensorFlow 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 `tf.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 `tf.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 `tf.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
tf.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 TensorFlow 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=tf.train.FtrlOptimizer(...),
# deep settings
dnn_feature_columns=[education_emb, occupation_emb],
dnn_hidden_units=[1000, 500, 100],
dnn_optimizer=tf.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 `tf.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 `tf.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 `tf.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
tf.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 TensorFlow 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=tf.train.FtrlOptimizer(...),
# deep settings
dnn_feature_columns=[education_emb, occupation_emb],
dnn_hidden_units=[1000, 500, 100],
dnn_optimizer=tf.train.ProximalAdagradOptimizer(...))
# To apply L1 and L2 regularization, you can set optimizers as follows:
tf.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 `tf.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 `tf.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 `tf.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
tf.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)
| [
"tensorflow.contrib.framework.python.ops.variables.get_global_step",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.tile",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.contrib.layers.python.layers.feature_column_ops.check_feature_columns",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.contrib.learn.python.learn.estimators.composable_model.LinearComposableModel",
"tensorflow.contrib.learn.python.learn.estimators.composable_model.DNNComposableModel",
"tensorflow.python.training.training.AdagradOptimizer",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.logging_ops.scalar_summary",
"tensorflow.contrib.layers.multi_class_target",
"tensorflow.contrib.layers.regression_target",
"tensorflow.python.ops.array_ops.zeros",
"numpy.argmax",
"tensorflow.python.ops.parsing_ops.parse_example",
"tensorflow.python.framework.ops.control_dependencies"
] | jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | [(110, 'tensorflow.contrib.learn.python.learn.estimators.composable_model.LinearComposableModel', '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'}), False, 'from tensorflow.contrib.learn.python.learn.estimators import composable_model\n'), (162, 'tensorflow.contrib.framework.python.ops.variables.get_global_step', 'contrib_variables.get_global_step', ([], {}), True, 'from tensorflow.contrib.framework.python.ops import variables as contrib_variables\n'), (173, 'tensorflow.python.ops.logging_ops.scalar_summary', 'logging_ops.scalar_summary', (['"""loss"""', 'loss'], {}), False, 'from tensorflow.python.ops import logging_ops\n'), (196, 'tensorflow.python.ops.parsing_ops.parse_example', 'parsing_ops.parse_example', (['examples_batch', 'column_types'], {}), False, 'from tensorflow.python.ops import parsing_ops\n'), (202, 'tensorflow.contrib.layers.python.layers.feature_column_ops.check_feature_columns', 'feature_column_ops.check_feature_columns', (['self._linear_feature_columns'], {}), False, 'from tensorflow.contrib.layers.python.layers import feature_column_ops\n'), (208, 'tensorflow.contrib.layers.python.layers.feature_column_ops.check_feature_columns', 'feature_column_ops.check_feature_columns', (['self._dnn_feature_columns'], {}), False, 'from tensorflow.contrib.layers.python.layers import feature_column_ops\n'), (232, 'tensorflow.python.framework.ops.get_collection', 'ops.get_collection', (['self._centered_bias_weight_collection'], {}), False, 'from tensorflow.python.framework import ops\n'), (374, 'tensorflow.contrib.layers.multi_class_target', 'layers.multi_class_target', ([], {'n_classes': 'n_classes', 'weight_column_name': 'weight_column_name'}), False, 'from tensorflow.contrib import layers\n'), (554, 'tensorflow.contrib.layers.regression_target', 'layers.regression_target', ([], {'weight_column_name': 'weight_column_name', 'target_dimension': 'target_dimension'}), False, 'from tensorflow.contrib import layers\n'), (116, 'tensorflow.contrib.learn.python.learn.estimators.composable_model.DNNComposableModel', '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'}), False, 'from tensorflow.contrib.learn.python.learn.estimators import composable_model\n'), (171, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['centered_bias_step'], {}), False, 'from tensorflow.python.framework import ops\n'), (179, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['(linear_train_step + dnn_train_step)'], {}), False, 'from tensorflow.python.framework import ops\n'), (221, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[self._target_column.num_label_columns]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (228, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['centered_bias', '[-1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (233, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['targets'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (235, 'tensorflow.python.ops.array_ops.tile', 'array_ops.tile', (['centered_bias[0]', '[batch_size]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (412, 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(1)'}), True, 'import numpy as np\n'), (240, 'tensorflow.python.training.training.AdagradOptimizer', 'training.AdagradOptimizer', (['(0.1)'], {}), False, 'from tensorflow.python.training import training\n'), (410, 'numpy.argmax', 'np.argmax', (['p'], {'axis': '(0)'}), True, 'import numpy as np\n'), (180, 'tensorflow.python.framework.ops.get_default_graph', 'ops.get_default_graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (181, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['global_step', '(1)'], {}), False, 'from tensorflow.python.ops import state_ops\n')] |
hephaex/probability | 740d0db0bf2b1e1a04cfd0b55481c44380b3cb05 | # Copyright 2018 The TensorFlow 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 tensorflow as tf
from tensorflow_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 `tf.transpose` except that it
transposes only the rightmost "event" dimensions. That is, unlike
`tf.transpose` the `perm` argument is itself a permutation of
`tf.range(rightmost_transposed_ndims)` rather than `tf.range(tf.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 = tf.rank(x) - tf.size(perm)
perm = tf.concat([
tf.range(sample_batch_ndims),
sample_batch_ndims + perm,
], axis=0)
return tf.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 `tf.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 `tf.rank(x) - 1`.
Only one of `perm` and `rightmost_transposed_ndims` can (and must) be
specified.
Default value:
`tf.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: `tf.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 tf.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 = tf.convert_to_tensor(
value=rightmost_transposed_ndims,
dtype=np.int32,
name='rightmost_transposed_ndims')
rightmost_transposed_ndims_ = tf.get_static_value(
rightmost_transposed_ndims)
with tf.control_dependencies(_maybe_validate_rightmost_transposed_ndims(
rightmost_transposed_ndims, validate_args)):
rightmost_transposed_ndims = tf.identity(rightmost_transposed_ndims)
perm = tf.range(
start=rightmost_transposed_ndims - 1,
limit=-1,
delta=-1,
name='perm')
else: # perm is not None:
perm = tf.convert_to_tensor(value=perm, dtype=np.int32, name='perm')
rightmost_transposed_ndims = tf.size(
input=perm, name='rightmost_transposed_ndims')
rightmost_transposed_ndims_ = tf.get_static_value(
rightmost_transposed_ndims)
with tf.control_dependencies(_maybe_validate_perm(perm, validate_args)):
perm = tf.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, tf.argsort(self.perm))
def _inverse_log_det_jacobian(self, y):
return tf.constant(0, dtype=y.dtype)
def _forward_log_det_jacobian(self, x):
return tf.constant(0, dtype=x.dtype)
def _transpose(self, x, perm):
sample_batch_ndims = tf.rank(x) - self.rightmost_transposed_ndims
perm = tf.concat([
tf.range(sample_batch_ndims),
sample_batch_ndims + perm,
], axis=0)
return tf.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 tf.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 += [tf.compat.v1.assert_rank(rightmost_transposed_ndims, 0)]
rightmost_transposed_ndims_ = tf.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 += [
tf.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 tf.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 += [tf.compat.v1.assert_rank(perm, 1, message=msg)]
perm_ = tf.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 += [
tf.compat.v1.assert_equal(
tf.sort(perm), tf.range(tf.size(input=perm)), message=msg)
]
return assertions
| [
"tensorflow.convert_to_tensor",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.range",
"tensorflow.sort",
"tensorflow.identity",
"numpy.sort",
"numpy.size",
"tensorflow.argsort",
"tensorflow.name_scope",
"tensorflow.compat.v1.assert_rank",
"tensorflow.rank",
"tensorflow.get_static_value",
"tensorflow.compat.v1.assert_non_negative",
"tensorflow.size"
] | tensorflow_probability/python/bijectors/transpose.py | [(182, 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'y.dtype'}), True, 'import tensorflow as tf\n'), (185, 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'x.dtype'}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.transpose', 'tf.transpose', ([], {'a': 'x', 'perm': 'perm'}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""maybe_validate_rightmost_transposed_ndims"""', '[rightmost_transposed_ndims]'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.get_static_value', 'tf.get_static_value', (['rightmost_transposed_ndims'], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.name_scope', 'tf.name_scope', (['name', '"""maybe_validate_perm"""', '[perm]'], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.get_static_value', 'tf.get_static_value', (['perm'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {'values': '[perm, rightmost_transposed_ndims]'}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.argsort', 'tf.argsort', (['self.perm'], {}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.rank', 'tf.rank', (['x'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'rightmost_transposed_ndims', 'dtype': 'np.int32', 'name': '"""rightmost_transposed_ndims"""'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.get_static_value', 'tf.get_static_value', (['rightmost_transposed_ndims'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.range', 'tf.range', ([], {'start': '(rightmost_transposed_ndims - 1)', 'limit': '(-1)', 'delta': '(-1)', 'name': '"""perm"""'}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', ([], {'value': 'perm', 'dtype': 'np.int32', 'name': '"""perm"""'}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.size', 'tf.size', ([], {'input': 'perm', 'name': '"""rightmost_transposed_ndims"""'}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.get_static_value', 'tf.get_static_value', (['rightmost_transposed_ndims'], {}), True, 'import tensorflow as tf\n'), (190, 'tensorflow.range', 'tf.range', (['sample_batch_ndims'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.identity', 'tf.identity', (['rightmost_transposed_ndims'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.identity', 'tf.identity', (['perm'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.compat.v1.assert_rank', 'tf.compat.v1.assert_rank', (['rightmost_transposed_ndims', '(0)'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.compat.v1.assert_non_negative', 'tf.compat.v1.assert_non_negative', (['rightmost_transposed_ndims'], {'message': 'msg'}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.compat.v1.assert_rank', 'tf.compat.v1.assert_rank', (['perm', '(1)'], {'message': 'msg'}), True, 'import tensorflow as tf\n'), (247, 'numpy.sort', 'np.sort', (['perm_'], {}), True, 'import numpy as np\n'), (252, 'tensorflow.sort', 'tf.sort', (['perm'], {}), True, 'import tensorflow as tf\n'), (247, 'numpy.size', 'np.size', (['perm_'], {}), True, 'import numpy as np\n'), (252, 'tensorflow.size', 'tf.size', ([], {'input': 'perm'}), True, 'import tensorflow as tf\n')] |
jacke121/MBMD | 2daf5edb4fb40ee652baead4f9332ca00fa111a5 | from object_detection.core.target_assigner import TargetAssigner
import tensorflow as tf
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 = tf.ones(tf.expand_dims(groundtruth_boxes.num_boxes(),
0))
groundtruth_labels = tf.expand_dims(groundtruth_labels, -1)
shape_assert = tf.assert_equal(tf.shape(groundtruth_labels)[1:],
tf.shape(self._unmatched_cls_target))
with tf.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 = tf.cast(match.matched_column_indicator(), tf.float32)
matched_gt_indices = match.matched_row_indices()
matched_label = tf.gather(groundtruth_labels, matched_gt_indices)
matched_is_foreground = tf.cast(matched_label[:,0] <= 0, tf.float32)
matched_anchor_indices = match.matched_column_indices()
unmatched_ignored_anchor_indices=match.unmatched_or_ignored_column_indices()
unmatched_ignored_reg_weights = tf.gather(reg_weights, unmatched_ignored_anchor_indices)
reg_weights= tf.dynamic_stitch(
[matched_anchor_indices, unmatched_ignored_anchor_indices],
[matched_is_foreground, unmatched_ignored_reg_weights])
return reg_weights
| [
"tensorflow.control_dependencies",
"tensorflow.shape",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.gather",
"tensorflow.dynamic_stitch"
] | core/target_assigner.py | [(99, 'tensorflow.gather', 'tf.gather', (['groundtruth_labels', 'matched_gt_indices'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.cast', 'tf.cast', (['(matched_label[:, (0)] <= 0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.gather', 'tf.gather', (['reg_weights', 'unmatched_ignored_anchor_indices'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.dynamic_stitch', 'tf.dynamic_stitch', (['[matched_anchor_indices, unmatched_ignored_anchor_indices]', '[matched_is_foreground, unmatched_ignored_reg_weights]'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.expand_dims', 'tf.expand_dims', (['groundtruth_labels', '(-1)'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.shape', 'tf.shape', (['self._unmatched_cls_target'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[shape_assert]'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.shape', 'tf.shape', (['groundtruth_labels'], {}), True, 'import tensorflow as tf\n')] |