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
muell-monster/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. """Tests for instance_segmentation.core.instance_segment_ops.""" import tensorflow as tf from tf3d.utils import instance_segmentation_utils as isu class InstanceSegmentUtilsTest(tf.test.TestCase): def get_instance_masks(self): mask0 = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0]], dtype=tf.float32) mask1 = tf.constant([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], dtype=tf.float32) mask2 = tf.constant([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]], dtype=tf.float32) masks = tf.stack([mask0, mask1, mask2]) return masks def test_map_labels_to_0_to_n1(self): labels = tf.constant([[-1, 2, 5], [0, 9, 1]], dtype=tf.int32) labels_0_n = isu.map_labels_to_0_to_n(labels) expected_labels_0_n = tf.constant([[-1, 2, 3], [0, 4, 1]], dtype=tf.int32) self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy()) def test_map_labels_to_0_to_n2(self): labels = tf.constant([[-1, 1, 2], [1, 1, 2]], dtype=tf.int32) labels_0_n = isu.map_labels_to_0_to_n(labels) expected_labels_0_n = tf.constant([[-1, 0, 1], [0, 0, 1]], dtype=tf.int32) self.assertAllEqual(labels_0_n.numpy(), expected_labels_0_n.numpy()) def test_randomly_select_one_point_per_segment(self): instance_labels = tf.constant([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 2, 2, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 2, 2], [0, 0, 0, 0, 2, 2, 2, 2], [0, 0, 0, 0, 2, 2, 2, 2]], dtype=tf.int32) instance_labels = tf.reshape(instance_labels, [-1]) (indices, masks_t) = isu.randomly_select_one_point_per_segment(instance_labels) masks = tf.transpose(masks_t) masks = tf.reshape(masks, [3, 5, 8]) expected_masks = self.get_instance_masks() selected_instances = tf.gather(instance_labels, indices) expected_selected_instances = tf.constant([0, 1, 2], dtype=tf.int32) self.assertAllEqual(selected_instances.numpy(), expected_selected_instances.numpy()) self.assertAllClose(masks.numpy(), expected_masks.numpy()) def test_inputs_Distances_to_centers(self): inputs = tf.random.uniform( [100, 8], minval=-10, maxval=10.0, dtype=tf.float32) centers = tf.random.uniform( [5, 8], minval=-10, maxval=10.0, dtype=tf.float32) distances1 = isu.inputs_distances_to_centers(inputs, centers) num_centers = tf.shape(centers)[0] inputs_reshaped = tf.tile(tf.expand_dims(inputs, axis=1), tf.stack([1, num_centers, 1])) distances2 = tf.reduce_sum(tf.square(inputs_reshaped - centers), axis=2) self.assertAllClose(distances1.numpy(), distances2.numpy(), atol=0.001) def test_pairwise_iou_matrix(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32) masks1 = tf.stack([mask0, mask1, mask2]) masks2 = tf.stack([mask3, mask4, mask5]) ious = isu.get_pairwise_iou_matrix(masks1, masks2) expected_ious = tf.constant([[0.5, 0.0, 1.0/3.0], [0.75, 0.0, 0.25], [0.75, 0.0, 2.0/3.0]], dtype=tf.float32) self.assertAllClose(ious.numpy(), expected_ious.numpy()) def test_instance_non_maximum_suppression_1d_scores(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32) masks = tf.stack([mask0, mask1, mask2, mask3, mask4, mask5]) classes = tf.constant([1, 2, 3, 1, 2, 3], dtype=tf.int32) scores = tf.constant([1.0, 0.9, 0.8, 0.95, 0.85, 0.6], dtype=tf.float32) (nms_masks1, nms_scores1, nms_classes1, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=True) nms_masks_expected1 = tf.stack([mask0, mask4]) nms_scores_expected1 = tf.constant([1.0, 0.85], dtype=tf.float32) nms_classes_expected1 = tf.constant([1, 2], dtype=tf.int32) (nms_masks2, nms_scores2, nms_classes2, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=False) nms_masks_expected2 = tf.stack([mask0, mask1, mask4, mask2]) nms_scores_expected2 = tf.constant([1.0, 0.9, 0.85, 0.8], dtype=tf.float32) nms_classes_expected2 = tf.constant([1, 2, 2, 3], dtype=tf.int32) self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy()) self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy()) self.assertAllEqual(nms_classes1.numpy(), nms_classes_expected1.numpy()) self.assertAllEqual(nms_masks2.numpy(), nms_masks_expected2.numpy()) self.assertAllClose(nms_scores2.numpy(), nms_scores_expected2.numpy()) self.assertAllEqual(nms_classes2.numpy(), nms_classes_expected2.numpy()) def test_instance_non_maximum_suppression_1d_scores_empty_inputs(self): masks = tf.constant(1.0, shape=[0, 2, 2], dtype=tf.float32) scores = tf.constant([], dtype=tf.float32) classes = tf.constant([], dtype=tf.int32) (nms_masks1, nms_scores1, nms_classes1, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=True) nms_masks_expected1 = tf.constant(1.0, shape=[0, 2, 2], dtype=tf.float32) nms_scores_expected1 = tf.constant([], dtype=tf.float32) nms_classes_expected1 = tf.constant([], dtype=tf.int32) (nms_masks2, nms_scores2, nms_classes2, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=False) nms_masks_expected2 = tf.constant(1.0, shape=[0, 2, 2], dtype=tf.float32) nms_scores_expected2 = tf.constant([], dtype=tf.float32) nms_classes_expected2 = tf.constant([], dtype=tf.int32) self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy()) self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy()) self.assertAllEqual(nms_classes1.numpy(), nms_classes_expected1.numpy()) self.assertAllEqual(nms_masks2.numpy(), nms_masks_expected2.numpy()) self.assertAllClose(nms_scores2.numpy(), nms_scores_expected2.numpy()) self.assertAllEqual(nms_classes2.numpy(), nms_classes_expected2.numpy()) def test_instance_non_maximum_suppression_2d_scores(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32) masks = tf.stack([mask0, mask1, mask2, mask3, mask4, mask5]) scores = tf.constant([[0.05, 1.0, 0.2], [0.9, 0.1, 0.3], [0.95, 0.92, 0.1], [0.1, 0.05, 0.0], [0.2, 0.3, 0.7], [0.1, 0.2, 0.8]], dtype=tf.float32) (nms_masks1, nms_scores1, nms_classes1) = isu.instance_non_maximum_suppression_2d_scores( masks, scores, 3, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=True) nms_masks_expected1 = tf.stack([mask0, mask5, mask4]) nms_scores_expected1 = tf.constant([1.0, 0.8, 0.7], dtype=tf.float32) nms_classes_expected1 = tf.constant([1, 2, 2], dtype=tf.int32) (nms_masks2, nms_scores2, nms_classes2) = isu.instance_non_maximum_suppression_2d_scores( masks, scores, 3, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=False) nms_masks_expected2 = tf.stack([mask2, mask0, mask5, mask4]) nms_scores_expected2 = tf.constant([0.95, 1.0, 0.8, 0.7], dtype=tf.float32) nms_classes_expected2 = tf.constant([0, 1, 2, 2], dtype=tf.int32) self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy()) self.assertAllClose(nms_scores1.numpy(), nms_scores_expected1.numpy()) self.assertAllEqual(nms_classes1.numpy(), nms_classes_expected1.numpy()) self.assertAllEqual(nms_masks2.numpy(), nms_masks_expected2.numpy()) self.assertAllClose(nms_scores2.numpy(), nms_scores_expected2.numpy()) self.assertAllEqual(nms_classes2.numpy(), nms_classes_expected2.numpy()) def test_points_mask_iou(self): masks1 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]], dtype=tf.int32) masks2 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1]], dtype=tf.int32) iou = isu.points_mask_iou(masks1=masks1, masks2=masks2) expected_iou = tf.constant([[0, 0, 0], [0, 1, 0.6], [0, 0.6, 1.0], [0, 0.4, 0]], dtype=tf.float32) self.assertAllClose(iou.numpy(), expected_iou.numpy()) def test_points_mask_pairwise_iou(self): masks1 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]], dtype=tf.int32) masks2 = tf.constant([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 0, 1, 1, 1]], dtype=tf.int32) pairwise_iou = isu.points_mask_pairwise_iou(masks1=masks1, masks2=masks2) expected_iou = tf.constant([0, 1, 0.4, 0.2], dtype=tf.float32) self.assertAllClose(pairwise_iou.numpy(), expected_iou.numpy()) if __name__ == '__main__': tf.test.main()
[ "tensorflow.transpose", "tensorflow.constant", "tensorflow.shape", "tensorflow.stack", "tensorflow.reshape", "tensorflow.random.uniform", "tensorflow.test.main", "tensorflow.expand_dims", "tensorflow.gather", "tensorflow.square" ]
tf3d/utils/instance_segmentation_utils_test.py
[(283, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, \n 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.constant', 'tf.constant', (['[[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, \n 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, \n 1], [0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.stack', 'tf.stack', (['[mask0, mask1, mask2]'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.constant', 'tf.constant', (['[[-1, 2, 5], [0, 9, 1]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (49, 'tf3d.utils.instance_segmentation_utils.map_labels_to_0_to_n', 'isu.map_labels_to_0_to_n', (['labels'], {}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (50, 'tensorflow.constant', 'tf.constant', (['[[-1, 2, 3], [0, 4, 1]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.constant', 'tf.constant', (['[[-1, 1, 2], [1, 1, 2]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (57, 'tf3d.utils.instance_segmentation_utils.map_labels_to_0_to_n', 'isu.map_labels_to_0_to_n', (['labels'], {}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (58, 'tensorflow.constant', 'tf.constant', (['[[-1, 0, 1], [0, 0, 1]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.constant', 'tf.constant', (['[[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 2, 2, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 2, \n 2], [0, 0, 0, 0, 2, 2, 2, 2], [0, 0, 0, 0, 2, 2, 2, 2]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.reshape', 'tf.reshape', (['instance_labels', '[-1]'], {}), True, 'import tensorflow as tf\n'), (71, 'tf3d.utils.instance_segmentation_utils.randomly_select_one_point_per_segment', 'isu.randomly_select_one_point_per_segment', (['instance_labels'], {}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (72, 'tensorflow.transpose', 'tf.transpose', (['masks_t'], {}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.reshape', 'tf.reshape', (['masks', '[3, 5, 8]'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.gather', 'tf.gather', (['instance_labels', 'indices'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.constant', 'tf.constant', (['[0, 1, 2]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.random.uniform', 'tf.random.uniform', (['[100, 8]'], {'minval': '(-10)', 'maxval': '(10.0)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.random.uniform', 'tf.random.uniform', (['[5, 8]'], {'minval': '(-10)', 'maxval': '(10.0)', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (86, 'tf3d.utils.instance_segmentation_utils.inputs_distances_to_centers', 'isu.inputs_distances_to_centers', (['inputs', 'centers'], {}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (94, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.constant', 'tf.constant', (['[[0, 0], [0, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.stack', 'tf.stack', (['[mask0, mask1, mask2]'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.stack', 'tf.stack', (['[mask3, mask4, mask5]'], {}), True, 'import tensorflow as tf\n'), (108, 'tf3d.utils.instance_segmentation_utils.get_pairwise_iou_matrix', 'isu.get_pairwise_iou_matrix', (['masks1', 'masks2'], {}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (109, 'tensorflow.constant', 'tf.constant', (['[[0.5, 0.0, 1.0 / 3.0], [0.75, 0.0, 0.25], [0.75, 0.0, 2.0 / 3.0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.constant', 'tf.constant', (['[[0, 0], [0, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.stack', 'tf.stack', (['[mask0, mask1, mask2, mask3, mask4, mask5]'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.constant', 'tf.constant', (['[1, 2, 3, 1, 2, 3]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.constant', 'tf.constant', (['[1.0, 0.9, 0.8, 0.95, 0.85, 0.6]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (134, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_1d_scores', 'isu.instance_non_maximum_suppression_1d_scores', (['masks', 'scores', 'classes'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(True)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (141, 'tensorflow.stack', 'tf.stack', (['[mask0, mask4]'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.constant', 'tf.constant', (['[1.0, 0.85]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.constant', 'tf.constant', (['[1, 2]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (147, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_1d_scores', 'isu.instance_non_maximum_suppression_1d_scores', (['masks', 'scores', 'classes'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(False)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (154, 'tensorflow.stack', 'tf.stack', (['[mask0, mask1, mask4, mask2]'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.constant', 'tf.constant', (['[1.0, 0.9, 0.85, 0.8]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.constant', 'tf.constant', (['[1, 2, 2, 3]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[0, 2, 2]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (171, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_1d_scores', 'isu.instance_non_maximum_suppression_1d_scores', (['masks', 'scores', 'classes'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(True)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (178, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[0, 2, 2]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (180, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (184, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_1d_scores', 'isu.instance_non_maximum_suppression_1d_scores', (['masks', 'scores', 'classes'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(False)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (191, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[0, 2, 2]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.constant', 'tf.constant', (['[]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [0, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.constant', 'tf.constant', (['[[1, 1], [1, 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.constant', 'tf.constant', (['[[0, 0], [0, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.constant', 'tf.constant', (['[[1, 0], [1, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.stack', 'tf.stack', (['[mask0, mask1, mask2, mask3, mask4, mask5]'], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.constant', 'tf.constant', (['[[0.05, 1.0, 0.2], [0.9, 0.1, 0.3], [0.95, 0.92, 0.1], [0.1, 0.05, 0.0], [\n 0.2, 0.3, 0.7], [0.1, 0.2, 0.8]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (224, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_2d_scores', 'isu.instance_non_maximum_suppression_2d_scores', (['masks', 'scores', '(3)'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(True)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (231, 'tensorflow.stack', 'tf.stack', (['[mask0, mask5, mask4]'], {}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.constant', 'tf.constant', (['[1.0, 0.8, 0.7]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.constant', 'tf.constant', (['[1, 2, 2]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (236, 'tf3d.utils.instance_segmentation_utils.instance_non_maximum_suppression_2d_scores', 'isu.instance_non_maximum_suppression_2d_scores', (['masks', 'scores', '(3)'], {'min_score_thresh': '(0.65)', 'min_iou_thresh': '(0.5)', 'is_class_agnostic': '(False)'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (243, 'tensorflow.stack', 'tf.stack', (['[mask2, mask0, mask5, mask4]'], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.constant', 'tf.constant', (['[0.95, 1.0, 0.8, 0.7]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.constant', 'tf.constant', (['[0, 1, 2, 2]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (261, 'tf3d.utils.instance_segmentation_utils.points_mask_iou', 'isu.points_mask_iou', ([], {'masks1': 'masks1', 'masks2': 'masks2'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (262, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0], [0, 1, 0.6], [0, 0.6, 1.0], [0, 0.4, 0]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.constant', 'tf.constant', (['[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0], [1, 0, 1, 1, 1]]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (277, 'tf3d.utils.instance_segmentation_utils.points_mask_pairwise_iou', 'isu.points_mask_pairwise_iou', ([], {'masks1': 'masks1', 'masks2': 'masks2'}), True, 'from tf3d.utils import instance_segmentation_utils as isu\n'), (278, 'tensorflow.constant', 'tf.constant', (['[0, 1, 0.4, 0.2]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.shape', 'tf.shape', (['centers'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.expand_dims', 'tf.expand_dims', (['inputs'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.stack', 'tf.stack', (['[1, num_centers, 1]'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.square', 'tf.square', (['(inputs_reshaped - centers)'], {}), True, 'import tensorflow as tf\n')]
muell-monster/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. """Replay buffer that performs relabeling.""" import gin import numpy as np import tensorflow as tf from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.utils import common @gin.configurable class RelabellingReplayBuffer(tf_uniform_replay_buffer.TFUniformReplayBuffer): """A replay buffer that relabels experience.""" def __init__(self, *args, **kwargs): """Initialize the replay buffer. Args: *args: Arguments. **kwargs: Keyword arguments. Additional arguments: task_distribution: an instance of multitask.TaskDistribution. sample_batch_size: (int) the batch size. num_parallel_calls: (int) number of parallel calls for sampling. num_future_states: (int) number of future states to consider for future state relabeling. actor: the actor network. critic: the critic network. gamma: (float) the discount factor. relabel_type: (str) indicator of the relabeling strategy. candidate_task_type: (str) within each back, should we use the states, next_states, or originally commanded tasks as possible tasks when relabeling. relabel_prob: (float) fraction of experience to relabel when sampling. keep_current_goal: (bool) for ``last'' and ``final'' relabeling, should we add both the originally commanded task and the relabeled task when inserting new experience into the replay buffer. normalize_cols: (bool) Normalizing the columns has the effect of including the partition function. """ self._task_distribution = kwargs.pop("task_distribution") self._sample_batch_size = kwargs.pop("sample_batch_size") self._num_parallel_calls = kwargs.pop("num_parallel_calls") self._num_future_states = kwargs.pop("num_future_states", 4) self._actor = kwargs.pop("actor") self._critic = kwargs.pop("critic") self._gamma = kwargs.pop("gamma") self._relabel_type = kwargs.pop("relabel_type", None) assert self._relabel_type in [None, "last", "future", "soft", "random"] self._candidate_task_type = kwargs.pop("candidate_task_type", "states") assert self._candidate_task_type in ["states", "next_states", "tasks"] self._relabel_prob = kwargs.pop("relabel_prob", 1.0) self._keep_current_goal = kwargs.pop("keep_current_goal", False) self._normalize_cols = kwargs.pop("normalize_cols", True) self._iterator = None super(RelabellingReplayBuffer, self).__init__(*args, **kwargs) def get_batch(self): if self._iterator is None: dataset = self.as_dataset( sample_batch_size=self._sample_batch_size, num_parallel_calls=self._num_parallel_calls, num_steps=2, ).prefetch(3) self._iterator = iter(dataset) experience, unused_info = next(self._iterator) if self._relabel_type in ["soft", "random"]: experience = self._soft_relabel(experience) elif self._relabel_type in ["last", "future"]: # Reassign the next_states to have the same goal as the current states _, tasks = self._task_distribution.split(experience.observation[:, 0]) next_states, _ = self._task_distribution.split(experience.observation[:, 1]) next_states_and_tasks = self._task_distribution.combine( next_states, tasks) new_observation = tf.concat( [ experience.observation[:, 0][:, None], next_states_and_tasks[:, None] ], axis=1, ) assert new_observation.shape == experience.observation.shape experience = experience.replace(observation=new_observation) if self._relabel_type is not None: # Recompute rewards and done flags states, tasks = self._task_distribution.split(experience.observation[:, 0]) next_states, next_tasks = self._task_distribution.split( experience.observation[:, 1]) rewards, dones = self._task_distribution.evaluate(states, experience.action[:, 0], tasks) # Strictly speaking, we don't need to relabel the next rewards and next # dones because they end up being thrown away. Only the current rewards # and dones end up being important. next_rewards, next_dones = self._task_distribution.evaluate( next_states, experience.action[:, 1], next_tasks) new_rewards = tf.concat([rewards[:, None], next_rewards[:, None]], axis=1) new_dones = tf.concat([dones[:, None], next_dones[:, None]], axis=1) # 0 if episode is done, 1 if episode is continuing new_discount = 1.0 - tf.cast(new_dones, tf.float32) assert new_rewards.shape == experience.reward.shape assert new_discount.shape == experience.discount.shape experience = experience.replace(reward=new_rewards, discount=new_discount) return experience def _soft_relabel(self, experience): """Reassigns tasks to each state and next state. Does not recompute the rewards or done flags. Args: experience: The experience that we want to relabel with inverse RL. Returns: relabeled_experience: The relabeled experience. """ raise NotImplementedError def _add_batch(self, items): """Adds a trajectory to the replay buffer.""" assert items[0].is_first() for item in items: # The items are batched already, so we remove the first dimension. assert item.observation.shape[1:] == self.data_spec.observation.shape super(RelabellingReplayBuffer, self)._add_batch(item) class GoalRelabellingReplayBuffer(RelabellingReplayBuffer): """Implements a replay buffer for relabeling goals.""" def _add_batch(self, items): """Adds a trajectory to the replay buffer.""" batch_size = len(items) if self._relabel_type in ["future", "last"]: relabelled_items = [] for i in range(batch_size): if self._relabel_type == "future": relabel_indices = np.random.randint( i, batch_size, size=self._num_future_states) else: relabel_indices = [batch_size - 1] if self._keep_current_goal: relabelled_items.append(items[i]) for j in relabel_indices: state, _ = self._task_distribution.split(items[i].observation) next_state, _ = self._task_distribution.split(items[j].observation) task = self._task_distribution.state_to_task(next_state) state_and_task = self._task_distribution.combine(state, task) new_item = items[i].replace(observation=state_and_task) relabelled_items.append(new_item) items = relabelled_items super(GoalRelabellingReplayBuffer, self)._add_batch(items) @tf.function def _soft_relabel(self, experience): # experience.observation.shape = [B x T=2 x obs_dim+state_dim] states, orig_tasks = self._task_distribution.split( experience.observation[:, 0]) if self._task_distribution.tasks is None: tasks = orig_tasks else: tasks = tf.constant(self._task_distribution.tasks, dtype=tf.float32) next_states, _ = self._task_distribution.split(experience.observation[:, 1]) if self._candidate_task_type == "states": candidate_tasks = self._task_distribution.state_to_task(states) elif self._candidate_task_type == "next_states": candidate_tasks = self._task_distribution.state_to_task(next_states) else: assert self._candidate_task_type == "tasks" candidate_tasks = tasks actions = experience.action[:, 0] num_tasks = tasks.shape[0] batch_size = states.shape[0] task_dim = tasks.shape[1] obs_dim = states.shape[1] action_dim = actions.shape[1] action_spec = self._actor.output_tensor_spec states_tiled = tf.tile(states[:, None], [1, num_tasks, 1]) # B x B x D states_tiled = tf.reshape(states_tiled, [batch_size * num_tasks, obs_dim]) # B*B x D actions_tiled = tf.tile(actions[:, None], [1, num_tasks, 1]) # B x B x D actions_tiled = tf.reshape(actions_tiled, [batch_size * num_tasks, action_dim]) # B*B x D tasks_tiled = tf.tile(tasks[None], [batch_size, 1, 1]) # B x B x D tasks_tiled = tf.reshape(tasks_tiled, [batch_size * num_tasks, task_dim]) # B*B x D next_states_tiled = tf.tile(next_states[:, None], [1, num_tasks, 1]) next_states_tiled = tf.reshape(next_states_tiled, [batch_size * num_tasks, obs_dim]) # B*B x D next_relabelled_obs = self._task_distribution.combine( next_states_tiled, tasks_tiled) sampled_actions_tiled = self._actor( next_relabelled_obs, step_type=(), network_state=())[0].sample() critic_input = (next_relabelled_obs, sampled_actions_tiled) q_vals, _ = self._critic(critic_input, training=False) q_vals_vec = tf.reshape(q_vals, (batch_size, num_tasks)) rewards, dones = self._task_distribution.evaluate(states_tiled, actions_tiled, tasks_tiled) dones = tf.cast(dones, tf.float32) rewards_vec = tf.reshape(rewards, (batch_size, num_tasks)) dones_vec = tf.reshape(dones, (batch_size, num_tasks)) relabelled_obs = self._task_distribution.combine(states_tiled, tasks_tiled) action_distribution = self._actor( relabelled_obs, step_type=(), network_state=())[0] log_pi = common.log_probability(action_distribution, actions_tiled, action_spec) log_pi_vec = tf.reshape(log_pi, (batch_size, num_tasks)) logits_vec = ( rewards_vec - log_pi_vec + self._gamma * (1.0 - dones_vec) * q_vals_vec) if self._relabel_type == "random": logits_vec = tf.ones_like(logits_vec) # Hack to make sampling random ## End new version if self._normalize_cols: logits_vec = logits_vec - tf.math.reduce_logsumexp( logits_vec, axis=0)[None] relabel_indices = tf.random.categorical(logits=logits_vec, num_samples=1) ### Metrics global_step = tf.compat.v1.train.get_or_create_global_step() orig_indices = tf.range( self._sample_batch_size, dtype=relabel_indices.dtype) with tf.name_scope("relabelling"): # How often are the originally commanded goals most optimal? opt_indices = tf.argmax(logits_vec, axis=1) orig_is_opt = opt_indices == orig_indices orig_opt_frac = tf.reduce_mean(tf.cast(orig_is_opt, tf.float32)) tf.compat.v2.summary.scalar( name="orig_task_optimal", data=orig_opt_frac, step=global_step) # How often is the relabelled goal optimal? # The relabel_indices are [B, 1], so we need to remove the extra dim. relabel_is_opt = tf.squeeze(relabel_indices) == orig_indices relabel_opt_frac = tf.reduce_mean(tf.cast(relabel_is_opt, tf.float32)) tf.compat.v2.summary.scalar( name="relabel_task_optimal", data=relabel_opt_frac, step=global_step) # What are the average Q values of the original tasks? if batch_size == num_tasks: indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0)) orig_q_vals = tf.gather_nd(logits_vec, indices) tf.compat.v2.summary.scalar( name="orig_q_vals", data=tf.reduce_mean(orig_q_vals), step=global_step, ) # What are the average Q values of the relabelled tasks? indices = tf.transpose( tf.stack([orig_indices, tf.squeeze(relabel_indices)], axis=0)) relabel_q_vals = tf.gather_nd(logits_vec, indices) tf.compat.v2.summary.scalar( name="relabel_q_vals", data=tf.reduce_mean(relabel_q_vals), step=global_step, ) max_q = tf.reduce_max(logits_vec, axis=1) tf.compat.v2.summary.scalar( name="max_q", data=tf.reduce_mean(max_q), step=global_step) ### End metrics # For both state-centric and goal-centric relabelling, the implementation of # mixing is the same: we randomly replace some of the indices with the # diagonal. relabelled_tasks = tf.gather(candidate_tasks, tf.squeeze(relabel_indices)) if self._relabel_prob == 0: relabelled_tasks = orig_tasks elif 0 < self._relabel_prob < 1: logits = tf.log([1.0 - self._relabel_prob, self._relabel_prob]) mask = tf.squeeze( tf.random.categorical( logits[None], num_samples=self._sample_batch_size)) mask = tf.cast(mask, tf.float32)[:, None] relabelled_tasks = mask * orig_tasks + (1 - mask) * relabelled_tasks states_and_tasks = self._task_distribution.combine(states, relabelled_tasks) next_states_and_tasks = self._task_distribution.combine( next_states, relabelled_tasks) new_observation = tf.concat( [states_and_tasks[:, None], next_states_and_tasks[:, None]], axis=1) assert new_observation.shape == experience.observation.shape experience = experience.replace(observation=new_observation) return experience
[ "tensorflow.concat", "tensorflow.stack", "tensorflow.cast", "numpy.random.randint", "tensorflow.squeeze", "tensorflow.compat.v1.train.get_or_create_global_step", "tensorflow.name_scope", "tensorflow.argmax", "tensorflow.tile", "tensorflow.gather_nd", "tensorflow.math.reduce_logsumexp", "tensorflow.compat.v2.summary.scalar", "tensorflow.reduce_max", "tensorflow.constant", "tensorflow.range", "tensorflow.reduce_mean", "tensorflow.random.categorical", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.log" ]
hipi/relabelling_replay_buffer.py
[(199, 'tensorflow.tile', 'tf.tile', (['states[:, (None)]', '[1, num_tasks, 1]'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.reshape', 'tf.reshape', (['states_tiled', '[batch_size * num_tasks, obs_dim]'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.tile', 'tf.tile', (['actions[:, (None)]', '[1, num_tasks, 1]'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.reshape', 'tf.reshape', (['actions_tiled', '[batch_size * num_tasks, action_dim]'], {}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.tile', 'tf.tile', (['tasks[None]', '[batch_size, 1, 1]'], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.reshape', 'tf.reshape', (['tasks_tiled', '[batch_size * num_tasks, task_dim]'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.tile', 'tf.tile', (['next_states[:, (None)]', '[1, num_tasks, 1]'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.reshape', 'tf.reshape', (['next_states_tiled', '[batch_size * num_tasks, obs_dim]'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.reshape', 'tf.reshape', (['q_vals', '(batch_size, num_tasks)'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.cast', 'tf.cast', (['dones', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.reshape', 'tf.reshape', (['rewards', '(batch_size, num_tasks)'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.reshape', 'tf.reshape', (['dones', '(batch_size, num_tasks)'], {}), True, 'import tensorflow as tf\n'), (231, 'tf_agents.utils.common.log_probability', 'common.log_probability', (['action_distribution', 'actions_tiled', 'action_spec'], {}), False, 'from tf_agents.utils import common\n'), (233, 'tensorflow.reshape', 'tf.reshape', (['log_pi', '(batch_size, num_tasks)'], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.random.categorical', 'tf.random.categorical', ([], {'logits': 'logits_vec', 'num_samples': '(1)'}), True, 'import tensorflow as tf\n'), (247, 'tensorflow.compat.v1.train.get_or_create_global_step', 'tf.compat.v1.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.range', 'tf.range', (['self._sample_batch_size'], {'dtype': 'relabel_indices.dtype'}), True, 'import tensorflow as tf\n'), (309, 'tensorflow.concat', 'tf.concat', (['[states_and_tasks[:, (None)], next_states_and_tasks[:, (None)]]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.concat', 'tf.concat', (['[rewards[:, (None)], next_rewards[:, (None)]]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.concat', 'tf.concat', (['[dones[:, (None)], next_dones[:, (None)]]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.constant', 'tf.constant', (['self._task_distribution.tasks'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.ones_like', 'tf.ones_like', (['logits_vec'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.name_scope', 'tf.name_scope', (['"""relabelling"""'], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.argmax', 'tf.argmax', (['logits_vec'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.compat.v2.summary.scalar', 'tf.compat.v2.summary.scalar', ([], {'name': '"""orig_task_optimal"""', 'data': 'orig_opt_frac', 'step': 'global_step'}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.compat.v2.summary.scalar', 'tf.compat.v2.summary.scalar', ([], {'name': '"""relabel_task_optimal"""', 'data': 'relabel_opt_frac', 'step': 'global_step'}), True, 'import tensorflow as tf\n'), (278, 'tensorflow.gather_nd', 'tf.gather_nd', (['logits_vec', 'indices'], {}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.reduce_max', 'tf.reduce_max', (['logits_vec'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (294, 'tensorflow.squeeze', 'tf.squeeze', (['relabel_indices'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.concat', 'tf.concat', (['[experience.observation[:, (0)][:, (None)], next_states_and_tasks[:, (None)]]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.cast', 'tf.cast', (['new_dones', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.cast', 'tf.cast', (['orig_is_opt', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.squeeze', 'tf.squeeze', (['relabel_indices'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.cast', 'tf.cast', (['relabel_is_opt', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.gather_nd', 'tf.gather_nd', (['logits_vec', 'indices'], {}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.log', 'tf.log', (['[1.0 - self._relabel_prob, self._relabel_prob]'], {}), True, 'import tensorflow as tf\n'), (157, 'numpy.random.randint', 'np.random.randint', (['i', 'batch_size'], {'size': 'self._num_future_states'}), True, 'import numpy as np\n'), (242, 'tensorflow.math.reduce_logsumexp', 'tf.math.reduce_logsumexp', (['logits_vec'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.stack', 'tf.stack', (['[orig_indices, orig_indices]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['relabel_q_vals'], {}), True, 'import tensorflow as tf\n'), (287, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['max_q'], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.random.categorical', 'tf.random.categorical', (['logits[None]'], {'num_samples': 'self._sample_batch_size'}), True, 'import tensorflow as tf\n'), (303, 'tensorflow.cast', 'tf.cast', (['mask', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['orig_q_vals'], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.squeeze', 'tf.squeeze', (['relabel_indices'], {}), True, 'import tensorflow as tf\n')]
muell-monster/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. """Tests for feature utils.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from etcmodel import feature_utils class TensorUtilsTest(tf.test.TestCase, parameterized.TestCase): def test_relative_position_generator_init(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) self.assertEqual(3, relative_pos_gen.max_distance) self.assertEqual(False, relative_pos_gen.ignore_direction) self.assertEqual(7, relative_pos_gen.relative_vocab_size) self.assertEqual(6, relative_pos_gen.left_pad_value) self.assertEqual(3, relative_pos_gen.right_pad_value) def test_relative_position_generator_init_ignore_direction(self): relative_pos_gen = feature_utils.RelativePositionGenerator( max_distance=3, ignore_direction=True) self.assertEqual(3, relative_pos_gen.max_distance) self.assertEqual(True, relative_pos_gen.ignore_direction) self.assertEqual(4, relative_pos_gen.relative_vocab_size) self.assertEqual(3, relative_pos_gen.left_pad_value) self.assertEqual(3, relative_pos_gen.right_pad_value) def test_relative_position_generator_init_max_distance_0(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=0) self.assertEqual(0, relative_pos_gen.max_distance) self.assertEqual(False, relative_pos_gen.ignore_direction) self.assertEqual(1, relative_pos_gen.relative_vocab_size) self.assertEqual(0, relative_pos_gen.left_pad_value) self.assertEqual(0, relative_pos_gen.right_pad_value) def test_relative_position_generator_init_invalid_arguments(self): with self.assertRaises(ValueError): feature_utils.RelativePositionGenerator(max_distance=-1) def test_make_relative_att_ids_padding_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [[ [0, 1, 2, 3, 3, 3], # [4, 0, 1, 2, 3, 3], # [5, 4, 0, 1, 2, 3], # [6, 5, 4, 0, 1, 2], # [6, 6, 5, 4, 0, 1], # [6, 6, 6, 5, 4, 0], # ]] self.assertAllEqual(expected, relative_pos_gen.make_relative_att_ids(6)) def test_make_relative_att_ids_padding_case_ignore_direction(self): relative_pos_gen = feature_utils.RelativePositionGenerator( max_distance=3, ignore_direction=True) expected = [[ [0, 1, 2, 3, 3, 3], # [1, 0, 1, 2, 3, 3], # [2, 1, 0, 1, 2, 3], # [3, 2, 1, 0, 1, 2], # [3, 3, 2, 1, 0, 1], # [3, 3, 3, 2, 1, 0], # ]] self.assertAllEqual(expected, relative_pos_gen.make_relative_att_ids(6)) def test_make_relative_att_ids_trimming_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=9) expected = [[ [0, 1, 2, 3, 4], # [10, 0, 1, 2, 3], # [11, 10, 0, 1, 2], # [12, 11, 10, 0, 1], # [13, 12, 11, 10, 0], # ]] self.assertAllEqual(expected, relative_pos_gen.make_relative_att_ids(5)) def test_make_relative_att_ids_no_pad_or_trim_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=4) expected = [[ [0, 1, 2, 3, 4], # [5, 0, 1, 2, 3], # [6, 5, 0, 1, 2], # [7, 6, 5, 0, 1], # [8, 7, 6, 5, 0], # ]] self.assertAllEqual(expected, relative_pos_gen.make_relative_att_ids(5)) def test_make_relative_att_ids_max_distance_0(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=0) expected = [[ [0, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 0, 0], # ]] self.assertAllEqual(expected, relative_pos_gen.make_relative_att_ids(4)) def test_make_relative_att_ids_batch_size_2(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [ [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ], [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ] ] self.assertAllEqual( expected, relative_pos_gen.make_relative_att_ids(seq_len=5, batch_size=2)) def test_make_relative_att_ids_batch_size_2_tensor(self): dummy_batch = tf.ones([2, 5]) relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [ [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ], [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ] ] self.assertAllEqual( expected, relative_pos_gen.make_relative_att_ids( seq_len=5, batch_size=tf.shape(dummy_batch)[0])) def test_overwrite_relative_att_ids_outside_segments(self): # batch_size = 2, seq_len = 5, max_distance = 3 rel_att_ids = [ [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ], [ [0, 1, 2, 3, 3], # [4, 0, 1, 2, 3], # [5, 4, 0, 1, 2], # [6, 5, 4, 0, 1], # [6, 6, 5, 4, 0], # ] ] segment_ids = [[10, 10, 20, 30, 30], [10, 20, 20, 10, 10]] overwrite_value = 100 expected_rel_att_ids = [ [ [0, 1, 100, 100, 100], # [4, 0, 100, 100, 100], # [100, 100, 0, 100, 100], # [100, 100, 100, 0, 1], # [100, 100, 100, 4, 0], # ], [ [0, 100, 100, 3, 3], # [100, 0, 1, 100, 100], # [100, 4, 0, 100, 100], # [6, 100, 100, 0, 1], # [6, 100, 100, 4, 0], # ] ] self.assertAllEqual( expected_rel_att_ids, feature_utils.overwrite_relative_att_ids_outside_segments( rel_att_ids=rel_att_ids, segment_ids=segment_ids, overwrite_value=overwrite_value)) def test_make_relative_att_ids_invalid_arguments(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) with self.assertRaises(ValueError): relative_pos_gen.make_relative_att_ids(0) with self.assertRaises(ValueError): relative_pos_gen.make_relative_att_ids(seq_len=5, batch_size=0) def test_make_local_relative_att_ids_padding_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [[ [6, 6, 6, 5, 4, 0, 1, 2, 3, 3, 3], # [6, 6, 6, 5, 4, 0, 1, 2, 3, 3, 3], # [6, 6, 6, 5, 4, 0, 1, 2, 3, 3, 3], # [6, 6, 6, 5, 4, 0, 1, 2, 3, 3, 3], # ]] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids(seq_len=4, local_radius=5)) def test_make_local_relative_att_ids_padding_case_ignore_direction(self): relative_pos_gen = feature_utils.RelativePositionGenerator( max_distance=3, ignore_direction=True) expected = [[ [3, 3, 3, 2, 1, 0, 1, 2, 3, 3, 3], # [3, 3, 3, 2, 1, 0, 1, 2, 3, 3, 3], # [3, 3, 3, 2, 1, 0, 1, 2, 3, 3, 3], # [3, 3, 3, 2, 1, 0, 1, 2, 3, 3, 3], # ]] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids(seq_len=4, local_radius=5)) def test_make_local_relative_att_ids_trimming_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=9) expected = [[ [13, 12, 11, 10, 0, 1, 2, 3, 4], # [13, 12, 11, 10, 0, 1, 2, 3, 4], # [13, 12, 11, 10, 0, 1, 2, 3, 4], # ]] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids(seq_len=3, local_radius=4)) def test_make_local_relative_att_ids_no_pad_or_trim_case(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=4) expected = [[ [8, 7, 6, 5, 0, 1, 2, 3, 4], # [8, 7, 6, 5, 0, 1, 2, 3, 4], # [8, 7, 6, 5, 0, 1, 2, 3, 4], # ]] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids(seq_len=3, local_radius=4)) def test_make_local_relative_att_ids_max_distance_0(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=0) expected = [[ [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0], # ]] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids(seq_len=2, local_radius=2)) def test_make_local_relative_att_ids_batch_size_2(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [ [ [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], [ [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], ] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids( seq_len=3, local_radius=4, batch_size=2)) def test_make_local_relative_att_ids_batch_size_2_tensor(self): dummy_batch = tf.ones([2, 5]) relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) expected = [ [ [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], [ [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # [6, 6, 5, 4, 0, 1, 2, 3, 3], # ], ] self.assertAllEqual( expected, relative_pos_gen.make_local_relative_att_ids( seq_len=3, local_radius=4, batch_size=tf.shape(dummy_batch)[0])) def test_make_local_relative_att_ids_invalid_arguments(self): relative_pos_gen = feature_utils.RelativePositionGenerator(max_distance=3) with self.assertRaises(ValueError): relative_pos_gen.make_local_relative_att_ids(seq_len=0, local_radius=3) with self.assertRaises(ValueError): relative_pos_gen.make_local_relative_att_ids(seq_len=5, local_radius=0) with self.assertRaises(ValueError): relative_pos_gen.make_local_relative_att_ids( seq_len=5, local_radius=3, batch_size=0) def test_make_att_mask_from_input_mask(self): input_mask = [ [1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], ] expected = [ [ [1, 1, 1, 0, 0, 0], # [1, 1, 1, 0, 0, 0], # [1, 1, 1, 0, 0, 0], # [0, 0, 0, 1, 1, 1], # [0, 0, 0, 1, 1, 1], # [0, 0, 0, 1, 1, 1], # ], # [ [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # ], # [ [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 1], # ], # [ [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # ], # ] self.assertAllEqual(expected, feature_utils.make_att_mask_from_input_mask(input_mask)) def test_make_segmented_att_mask(self): segment_ids = [ [0, 0, 1, 1, 0, 0], [2, 2, 2, 2, 2, 2], [0, 0, 3, 0, 3, 0], [0, 5, 4, 3, 2, 1], ] expected = [ [ [1, 1, 0, 0, 1, 1], # [1, 1, 0, 0, 1, 1], # [0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0], # [1, 1, 0, 0, 1, 1], # [1, 1, 0, 0, 1, 1], # ], # [ [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # ], # [ [1, 1, 0, 1, 0, 1], # [1, 1, 0, 1, 0, 1], # [0, 0, 1, 0, 1, 0], # [1, 1, 0, 1, 0, 1], # [0, 0, 1, 0, 1, 0], # [1, 1, 0, 1, 0, 1], # ], # [ [1, 0, 0, 0, 0, 0], # [0, 1, 0, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 0, 1, 0, 0], # [0, 0, 0, 0, 1, 0], # [0, 0, 0, 0, 0, 1], # ], # ] self.assertAllEqual(expected, feature_utils.make_segmented_att_mask(segment_ids)) def test_make_att_mask_from_breakpoints(self): att_breakpoints = [ [0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1], ] expected = [ [ [1, 1, 0, 0, 0, 0], # [1, 1, 0, 0, 0, 0], # [0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0], # [0, 0, 0, 0, 1, 1], # [0, 0, 0, 0, 1, 1], # ], # [ [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # ], # [ [1, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1], # ], # [ [1, 0, 0, 0, 0, 0], # [0, 1, 0, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 0, 1, 0, 0], # [0, 0, 0, 0, 1, 0], # [0, 0, 0, 0, 0, 1], # ], # ] self.assertAllEqual( expected, feature_utils.make_att_mask_from_breakpoints(att_breakpoints)) def test_make_att_mask_from_breakpoints_use_starting_breakpoints(self): att_breakpoints = [ [0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1], ] expected = [ [ [1, 1, 0, 0, 0, 0], # [1, 1, 0, 0, 0, 0], # [0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0], # [0, 0, 0, 0, 1, 1], # [0, 0, 0, 0, 1, 1], # ], # [ [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1], # ], # [ [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 1], # ], # [ [1, 0, 0, 0, 0, 0], # [0, 1, 0, 0, 0, 0], # [0, 0, 1, 0, 0, 0], # [0, 0, 0, 1, 0, 0], # [0, 0, 0, 0, 1, 0], # [0, 0, 0, 0, 0, 1], # ], # ] self.assertAllEqual( expected, feature_utils.make_att_mask_from_breakpoints( att_breakpoints, use_starting_breakpoints=True)) def test_make_local_segmented_att_mask(self): segment_ids = [ [0, 0, 1, 0, 1, 0, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2], [4, 3, 3, 3, 4, 1, 1, 1], [0, 6, 5, 4, 3, 2, 1, 0], ] expected = [ [ [0, 0, 1, 1, 0], # [0, 1, 1, 0, 1], # [0, 0, 1, 0, 1], # [1, 0, 1, 0, 1], # [1, 0, 1, 0, 1], # [1, 0, 1, 0, 0], # [1, 0, 1, 1, 0], # [0, 1, 1, 0, 0], # ], # [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # ], # ] self.assertAllEqual( expected, feature_utils.make_local_segmented_att_mask( segment_ids, local_radius=2)) def test_make_local_segmented_att_mask_uneven_blocking_case(self): segment_ids = [ [0, 0, 1, 0, 1, 0, 1, 1, 2, 2], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] expected = [ [ [0, 0, 0, 1, 1, 0, 1], # [0, 0, 1, 1, 0, 1, 0], # [0, 0, 0, 1, 0, 1, 0], # [1, 1, 0, 1, 0, 1, 0], # [0, 1, 0, 1, 0, 1, 1], # [0, 1, 0, 1, 0, 0, 0], # [0, 1, 0, 1, 1, 0, 0], # [1, 0, 1, 1, 0, 0, 0], # [0, 0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0, 0], # ], # [ [0, 0, 0, 1, 1, 1, 1], # [0, 0, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1, 1], # [1, 1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 0, 0], # [1, 1, 1, 1, 0, 0, 0], # ], # ] self.assertAllEqual( expected, feature_utils.make_local_segmented_att_mask( segment_ids, local_radius=3)) def test_make_local_segmented_att_mask_single_block_case(self): segment_ids = [ [0, 1], [0, 0], ] expected = [ [ [0, 0, 0, 1, 0, 0, 0], # [0, 0, 0, 1, 0, 0, 0], # ], # [ [0, 0, 0, 1, 1, 0, 0], # [0, 0, 1, 1, 0, 0, 0], # ], # ] self.assertAllEqual( expected, feature_utils.make_local_segmented_att_mask( segment_ids, local_radius=3)) def test_make_local_segmented_att_mask_static_shape(self): # This test is only relevant for TF v1 session mode. If the batch size # is statically unknown (None), we want to make sure all shapes in the # output other than batch size are still statically known. # We use `placeholder_with_default` to simulate the TF v1 situation where # the static `batch_size` is unknown. segment_ids = tf.compat.v1.placeholder_with_default( np.zeros([1, 8]), shape=[None, 8]) local_radius = 2 result = feature_utils.make_local_segmented_att_mask( segment_ids, local_radius=local_radius) self.assertAllEqual([8, 2 * local_radius + 1], result.shape.as_list()[1:]) def test_make_local_att_mask_from_breakpoints(self): att_breakpoints = [ [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], ] expected = [ [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # ], # ] self.assertAllEqual( expected, feature_utils.make_local_att_mask_from_breakpoints( att_breakpoints, local_radius=2)) def test_make_local_att_mask_from_breakpoints_use_starting_breakpoints(self): att_breakpoints = [ [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 1, 1, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], ] expected = [ [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 1], # [1, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # ], # [ [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 1, 1], # [0, 1, 1, 1, 0], # [1, 1, 1, 0, 0], # [0, 0, 1, 0, 0], # ], # [ [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # [0, 0, 1, 0, 0], # ], # ] self.assertAllEqual( expected, feature_utils.make_local_att_mask_from_breakpoints( att_breakpoints, local_radius=2, use_starting_breakpoints=True)) if __name__ == '__main__': tf.test.main()
[ "tensorflow.ones", "tensorflow.test.main", "numpy.zeros", "tensorflow.shape" ]
etcmodel/feature_utils_test.py
[(766, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (28, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (37, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)', 'ignore_direction': '(True)'}), False, 'from etcmodel import feature_utils\n'), (47, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(0)'}), False, 'from etcmodel import feature_utils\n'), (60, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (73, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)', 'ignore_direction': '(True)'}), False, 'from etcmodel import feature_utils\n'), (87, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(9)'}), False, 'from etcmodel import feature_utils\n'), (99, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(4)'}), False, 'from etcmodel import feature_utils\n'), (111, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(0)'}), False, 'from etcmodel import feature_utils\n'), (122, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (145, 'tensorflow.ones', 'tf.ones', (['[2, 5]'], {}), True, 'import tensorflow as tf\n'), (147, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (218, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (227, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (240, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)', 'ignore_direction': '(True)'}), False, 'from etcmodel import feature_utils\n'), (254, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(9)'}), False, 'from etcmodel import feature_utils\n'), (266, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(4)'}), False, 'from etcmodel import feature_utils\n'), (278, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(0)'}), False, 'from etcmodel import feature_utils\n'), (289, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (309, 'tensorflow.ones', 'tf.ones', (['[2, 5]'], {}), True, 'import tensorflow as tf\n'), (311, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (331, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(3)'}), False, 'from etcmodel import feature_utils\n'), (649, 'etcmodel.feature_utils.make_local_segmented_att_mask', 'feature_utils.make_local_segmented_att_mask', (['segment_ids'], {'local_radius': 'local_radius'}), False, 'from etcmodel import feature_utils\n'), (57, 'etcmodel.feature_utils.RelativePositionGenerator', 'feature_utils.RelativePositionGenerator', ([], {'max_distance': '(-1)'}), False, 'from etcmodel import feature_utils\n'), (212, 'etcmodel.feature_utils.overwrite_relative_att_ids_outside_segments', 'feature_utils.overwrite_relative_att_ids_outside_segments', ([], {'rel_att_ids': 'rel_att_ids', 'segment_ids': 'segment_ids', 'overwrite_value': 'overwrite_value'}), False, 'from etcmodel import feature_utils\n'), (386, 'etcmodel.feature_utils.make_att_mask_from_input_mask', 'feature_utils.make_att_mask_from_input_mask', (['input_mask'], {}), False, 'from etcmodel import feature_utils\n'), (431, 'etcmodel.feature_utils.make_segmented_att_mask', 'feature_utils.make_segmented_att_mask', (['segment_ids'], {}), False, 'from etcmodel import feature_utils\n'), (476, 'etcmodel.feature_utils.make_att_mask_from_breakpoints', 'feature_utils.make_att_mask_from_breakpoints', (['att_breakpoints'], {}), False, 'from etcmodel import feature_utils\n'), (522, 'etcmodel.feature_utils.make_att_mask_from_breakpoints', 'feature_utils.make_att_mask_from_breakpoints', (['att_breakpoints'], {'use_starting_breakpoints': '(True)'}), False, 'from etcmodel import feature_utils\n'), (577, 'etcmodel.feature_utils.make_local_segmented_att_mask', 'feature_utils.make_local_segmented_att_mask', (['segment_ids'], {'local_radius': '(2)'}), False, 'from etcmodel import feature_utils\n'), (614, 'etcmodel.feature_utils.make_local_segmented_att_mask', 'feature_utils.make_local_segmented_att_mask', (['segment_ids'], {'local_radius': '(3)'}), False, 'from etcmodel import feature_utils\n'), (635, 'etcmodel.feature_utils.make_local_segmented_att_mask', 'feature_utils.make_local_segmented_att_mask', (['segment_ids'], {'local_radius': '(3)'}), False, 'from etcmodel import feature_utils\n'), (646, 'numpy.zeros', 'np.zeros', (['[1, 8]'], {}), True, 'import numpy as np\n'), (706, 'etcmodel.feature_utils.make_local_att_mask_from_breakpoints', 'feature_utils.make_local_att_mask_from_breakpoints', (['att_breakpoints'], {'local_radius': '(2)'}), False, 'from etcmodel import feature_utils\n'), (761, 'etcmodel.feature_utils.make_local_att_mask_from_breakpoints', 'feature_utils.make_local_att_mask_from_breakpoints', (['att_breakpoints'], {'local_radius': '(2)', 'use_starting_breakpoints': '(True)'}), False, 'from etcmodel import feature_utils\n'), (168, 'tensorflow.shape', 'tf.shape', (['dummy_batch'], {}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.shape', 'tf.shape', (['dummy_batch'], {}), True, 'import tensorflow as tf\n')]
zhoudoufu/lingvo
bd0f89809942fd0508ff43bd4b6bca1b598220cb
# 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. """Tests for Asr Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re import numpy as np import six from six.moves import range import tensorflow as tf from lingvo.core import base_layer from lingvo.core import cluster_factory from lingvo.core import py_utils from lingvo.core import schedule from lingvo.core import summary_utils from lingvo.core import test_helper from lingvo.core import test_utils from lingvo.tasks.asr import decoder from lingvo.tasks.asr import input_generator from lingvo.tasks.asr import model from lingvo.tasks.asr import model_test_input_generator as tig class DecoderForTest(decoder.AsrDecoder): """Unit test class for AsrDecoder with functional.for based unrolling.""" @classmethod def Params(cls): p = super(DecoderForTest, cls).Params() p.use_while_loop_based_unrolling = False return p class AsrModelTest(test_utils.TestCase): def _testParams(self): input_shape = [2, 16, 8, 3] p = model.AsrModel.Params() p.decoder.target_seq_len = 5 p.encoder.input_shape = input_shape p.input = tig.TestInputGenerator.Params() p.input.target_max_length = 5 p.input.source_shape = input_shape p.input.target_shape = [2, 5] p.name = 'test_mdl' return p def testMakeDecoderTheta(self): # Test that decoder theta returns a copy of theta.decoder without changes. with self.session(use_gpu=False, graph=tf.Graph()): tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() decoder_theta = mdl._MakeDecoderTheta(theta=mdl.theta, input_batch=None) mdl.BProp() self.assertEqual(decoder_theta, mdl.theta.decoder) def testFProp(self): with self.session(use_gpu=False): tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() tf.global_variables_initializer().run() test_utils.CompareToGoldenSingleFloat(self, 4.472597, mdl.loss.eval()) actual_var_names = [_.name for _ in tf.all_variables()] print('all vars \n', '\n'.join(actual_var_names)) expected_var_names = [ 'global_step:0', 'test_mdl/enc/conv_L0/w/var:0', 'test_mdl/enc/conv_L0/beta/var:0', 'test_mdl/enc/conv_L0/gamma/var:0', 'test_mdl/enc/conv_L0/moving_mean/var:0', 'test_mdl/enc/conv_L0/moving_variance/var:0', 'test_mdl/enc/conv_L1/w/var:0', 'test_mdl/enc/conv_L1/beta/var:0', 'test_mdl/enc/conv_L1/gamma/var:0', 'test_mdl/enc/conv_L1/moving_mean/var:0', 'test_mdl/enc/conv_L1/moving_variance/var:0', 'test_mdl/enc/f_conv_lstm_0/wm/var:0', 'test_mdl/enc/f_conv_lstm_0/b/var:0', 'test_mdl/enc/b_conv_lstm_0/wm/var:0', 'test_mdl/enc/b_conv_lstm_0/b/var:0', 'test_mdl/enc/conv_lstm_cnn_0/w/var:0', 'test_mdl/enc/conv_lstm_cnn_0/beta/var:0', 'test_mdl/enc/conv_lstm_cnn_0/gamma/var:0', 'test_mdl/enc/conv_lstm_cnn_0/moving_mean/var:0', 'test_mdl/enc/conv_lstm_cnn_0/moving_variance/var:0', 'test_mdl/enc/fwd_rnn_L0/wm/var:0', 'test_mdl/enc/fwd_rnn_L0/b/var:0', 'test_mdl/enc/bak_rnn_L0/wm/var:0', 'test_mdl/enc/bak_rnn_L0/b/var:0', 'test_mdl/enc/proj_L0/w/var:0', 'test_mdl/enc/proj_L0/beta/var:0', 'test_mdl/enc/proj_L0/gamma/var:0', 'test_mdl/enc/proj_L0/moving_mean/var:0', 'test_mdl/enc/proj_L0/moving_variance/var:0', 'test_mdl/enc/fwd_rnn_L1/wm/var:0', 'test_mdl/enc/fwd_rnn_L1/b/var:0', 'test_mdl/enc/bak_rnn_L1/wm/var:0', 'test_mdl/enc/bak_rnn_L1/b/var:0', 'test_mdl/enc/proj_L1/w/var:0', 'test_mdl/enc/proj_L1/beta/var:0', 'test_mdl/enc/proj_L1/gamma/var:0', 'test_mdl/enc/proj_L1/moving_mean/var:0', 'test_mdl/enc/proj_L1/moving_variance/var:0', 'test_mdl/enc/fwd_rnn_L2/wm/var:0', 'test_mdl/enc/fwd_rnn_L2/b/var:0', 'test_mdl/enc/bak_rnn_L2/wm/var:0', 'test_mdl/enc/bak_rnn_L2/b/var:0', 'test_mdl/dec/emb/var_0/var:0', 'test_mdl/dec/rnn_cell/wm/var:0', 'test_mdl/dec/rnn_cell/b/var:0', 'test_mdl/dec/atten/source_var/var:0', 'test_mdl/dec/atten/query_var/var:0', 'test_mdl/dec/atten/hidden_var/var:0', 'test_mdl/dec/softmax/weight_0/var:0', 'test_mdl/dec/softmax/bias_0/var:0' ] self.assertEqual(sorted(expected_var_names), sorted(actual_var_names)) def testDecode(self): with self.session(use_gpu=False) as sess: tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate() input_batch = mdl.input_generator.GetPreprocessedInputBatch() dec_out_dict = mdl.Decode(input_batch) tf.global_variables_initializer().run() dec_out = sess.run(dec_out_dict) print('dec_out', dec_out) metrics_dict = mdl.CreateDecoderMetrics() key_value_pairs = mdl.PostProcessDecodeOut(dec_out, metrics_dict) self.assertEqual(1.0, metrics_dict['wer'].value) self.assertEqual(1.0, metrics_dict['norm_wer'].value) self.assertEqual(1.0, metrics_dict['ter'].value) self.assertEqual(0, len(key_value_pairs)) def testPostProcessDecodeOut(self): p = self._testParams() p.decoder.beam_search.num_hyps_per_beam = 2 mdl = p.Instantiate() fake_dec_out = { 'utt_id': ['utt1', 'utt2'], 'transcripts': ['a b c d', 'a'], 'topk_decoded': [['a b c d', 'a b c d'], ['wrong', '']], 'topk_scores': [[1.0, 0.9], [1.0, 0.9]], 'topk_ids': [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]], 'topk_lens': [2, 4, 4, 2], 'target_labels': [[1, 2, 3, 4], [2, 3, 4, 5]], 'target_paddings': [[0, 0, 0, 1], [0, 0, 0, 1]], 'norm_wer_errors': [[0, 0], [1, 1]], 'norm_wer_words': [[4, 4], [1, 1]], } metrics_dict = mdl.CreateDecoderMetrics() key_value_pairs = mdl.PostProcessDecodeOut(fake_dec_out, metrics_dict) self.assertEqual(0 + 1, metrics_dict['wer'].total_value) self.assertEqual(4 + 1, metrics_dict['wer'].total_weight) self.assertEqual(0 + 1, metrics_dict['norm_wer'].total_value) self.assertEqual(4 + 1, metrics_dict['norm_wer'].total_weight) self.assertEqual(4, metrics_dict['ter'].total_value) self.assertEqual(6, metrics_dict['ter'].total_weight) self.assertEqual(2, metrics_dict['num_samples_in_batch'].total_value) self.assertEqual(1.0, metrics_dict['num_samples_in_batch'].total_weight) self.assertEqual((4 / 5 * 3 / 3 * 2 / 2 * 1 / 1)**(1 / 4), metrics_dict['corpus_bleu'].value) self.assertEqual((0 + 1) / 2, metrics_dict['sacc'].value) self.assertEqual((0 + 1) / (4 + 1), metrics_dict['oracle_norm_wer'].value) self.assertEqual(0, len(key_value_pairs)) def testPostProcessDecodeOutFiltersEpsilonTokensForWER(self): p = self._testParams() p.decoder.beam_search.num_hyps_per_beam = 1 mdl = p.Instantiate() fake_dec_out = { 'utt_id': ['utt1', 'utt2'], 'transcripts': ['a b c d', 'a b c'], 'topk_decoded': [['a b<epsilon>c d'], ['<epsilon>a b<epsilon>']], 'topk_scores': [[1.0], [1.0]], 'topk_ids': [[1, 2, 3, 4], [2, 3, 4, 5]], 'topk_lens': [3, 4], 'target_labels': [[1, 2, 3, 4], [2, 3, 4, 5]], 'target_paddings': [[0, 0, 0, 1], [0, 0, 1, 1]], 'norm_wer_errors': [[0], [1]], 'norm_wer_words': [[4], [3]], } metrics_dict = mdl.CreateDecoderMetrics() kv_pairs = mdl.PostProcessDecodeOut(fake_dec_out, metrics_dict) self.assertEqual(0 + 1, metrics_dict['wer'].total_value) self.assertEqual(7, metrics_dict['wer'].total_weight) self.assertEqual(0 + 1, metrics_dict['norm_wer'].total_value) self.assertEqual(7, metrics_dict['norm_wer'].total_weight) self.assertEqual(0, len(kv_pairs)) def testPostProcessDecodeOutFiltersNoiseTokensForWER(self): p = self._testParams() p.decoder.beam_search.num_hyps_per_beam = 1 mdl = p.Instantiate() fake_dec_out = { 'utt_id': ['utt1', 'utt2'], 'transcripts': ['a b c d', 'a b c'], 'topk_decoded': [['a b <noise> c d'], ['<noise> a b <noise>']], 'topk_scores': [[1.0], [1.0]], 'topk_ids': [[1, 2, 3, 4], [2, 3, 4, 5]], 'topk_lens': [3, 4], 'target_labels': [[1, 2, 3, 4], [2, 3, 4, 5]], 'target_paddings': [[0, 0, 0, 1], [0, 0, 1, 1]], 'norm_wer_errors': [[0], [1]], 'norm_wer_words': [[4], [3]], } metrics_dict = mdl.CreateDecoderMetrics() kv_pairs = mdl.PostProcessDecodeOut(fake_dec_out, metrics_dict) self.assertEqual(0 + 1, metrics_dict['wer'].total_value) self.assertEqual(7, metrics_dict['wer'].total_weight) self.assertEqual(0 + 1, metrics_dict['norm_wer'].total_value) self.assertEqual(7, metrics_dict['norm_wer'].total_weight) self.assertEqual(0, len(kv_pairs)) def testPostProcessDecodeOutHandlesEmptyRef(self): p = self._testParams() p.decoder.beam_search.num_hyps_per_beam = 1 mdl = p.Instantiate() fake_dec_out = { 'utt_id': ['utt1', 'utt2'], 'transcripts': ['', 'a b c d'], 'topk_decoded': [['a'], ['a b c d']], 'topk_scores': [[1.0], [1.0]], 'topk_ids': [[1, 2, 3, 4], [2, 3, 4, 5]], 'topk_lens': [3, 4], 'target_labels': [[1, 2, 3, 4], [2, 3, 4, 5]], 'target_paddings': [[1, 1, 1, 1], [0, 0, 1, 1]], 'norm_wer_errors': [[1], [0]], 'norm_wer_words': [[0], [4]], } metrics_dict = mdl.CreateDecoderMetrics() mdl.PostProcessDecodeOut(fake_dec_out, metrics_dict) self.assertEqual(1 + 0, metrics_dict['wer'].total_value) self.assertEqual(0 + 4, metrics_dict['wer'].total_weight) self.assertEqual(1 + 0, metrics_dict['norm_wer'].total_value) self.assertEqual(0 + 4, metrics_dict['norm_wer'].total_weight) def testBProp(self): with self.session(use_gpu=False): tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() mdl.BProp() tf.global_variables_initializer().run() test_utils.CompareToGoldenSingleFloat(self, 4.472597, mdl.loss.eval()) mdl.train_op.run() def testBPropSmoothDecay(self): with self.session(use_gpu=False): tf.set_random_seed(93820985) p = self._testParams() p.train.lr_schedule = ( schedule.ContinuousLearningRateSchedule.Params().Set( start_step=350000, half_life_steps=45000)) mdl = p.Instantiate() mdl.FPropDefaultTheta() mdl.BProp() tf.global_variables_initializer().run() test_utils.CompareToGoldenSingleFloat(self, 4.472597, mdl.loss.eval()) mdl.train_op.run() def testAllLayerParams(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() lps = base_layer.RecursiveFindLayerParams(mdl.params) l_names = sorted([p.cls.__name__ for p in lps]) expected_layers = sorted([ 'Adam', 'AdditiveAttention', 'AsciiTokenizer', 'AsrDecoder', 'AsrEncoder', 'AsrModel', 'BeamSearchHelper', 'TargetSequenceSampler', 'ConvLSTMCell', 'Conv2DLayer', 'Conv2DLayer', 'EmbeddingLayer', 'HighwaySkipLayer', 'LSTMCellSimple', 'LSTMCellSimple', 'NullContextualizer', 'NullFusion', 'NullLm', 'Learner', 'PiecewiseConstantLearningRateSchedule', 'ProjectionLayer', 'SimpleFullSoftmax', 'SpectrumAugmenter', 'StackingOverTime', 'TestInputGenerator', ]) self.assertEqual(expected_layers, l_names) def testParamValueSumSquared(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() all_vars = tf.trainable_variables() py_utils.SumSquared(all_vars) def testCollectVarHistogram(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() var_grads = py_utils.ComputeGradients(mdl.loss, mdl.vars) summary_utils.CollectVarHistogram(var_grads) def testGradientMult(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() var_grads = py_utils.ComputeGradients(mdl.loss, mdl.vars) py_utils.ApplyGradMultiplier(var_grads, -1.1) def testLRDecay(self): with self.session(use_gpu=False, graph=tf.Graph()) as sess: p = self._testParams() tp = p.train tp.lr_schedule.boundaries = [300000, 400000, 500000] tp.lr_schedule.values = [1.0, 0.1, 0.01, 0.001] lrs = tp.lr_schedule.Instantiate() steps = [299999, 300001, 399999, 400001, 499999, 500001] fetches = [lrs.Value(_) for _ in steps] values = sess.run(fetches) self.assertAllClose([1.0, 0.1, 0.1, 0.01, 0.01, 0.001], values) def testBatchSplit(self): def Run(num_splits): p = self._testParams() with self.session(use_gpu=False, graph=tf.Graph()) as sess: tf.set_random_seed(93820981) p.is_eval = True p.input.cur_iter_in_seed = False p.input.bucket_batch_limit = [ b * 2 / num_splits for b in p.input.bucket_batch_limit ] with cluster_factory.ForTestingWorker(gpus=num_splits): mdl = p.Instantiate() metrics = mdl.FPropDefaultTheta()[0] tf.global_variables_initializer().run() return sess.run(metrics['loss']) res1, res2 = Run(1), Run(2) self.assertAllClose(res1[0], res2[0]) self.assertAllEqual(res1[1], res2[1]) def testInference(self): def _CreateModelParamsForTest(): p = model.AsrModel.Params() p.name = 'test_config' # Encoder params. ep = p.encoder ep.input_shape = [None, None, 80, 1] ep.lstm_cell_size = 16 ep.num_lstm_layers = 2 ep.conv_filter_shapes = [(3, 3, 1, 32), (3, 3, 32, 32)] ep.conv_filter_strides = [(2, 2), (2, 2)] ep.num_conv_lstm_layers = 0 # Initialize decoder params. dp = p.decoder dp.rnn_cell_dim = 16 dp.rnn_layers = 2 dp.source_dim = ep.lstm_cell_size * 2 # Use functional while based unrolling. dp.use_while_loop_based_unrolling = False p.input = input_generator.AsrInput.Params() ip = p.input ip.frame_size = 80 ip.append_eos_frame = True ip.pad_to_max_seq_length = False p.is_eval = True return p with self.session(use_gpu=False, graph=tf.Graph()) as sess: p = _CreateModelParamsForTest() mdl = p.Instantiate() subgraphs = mdl.Inference() self.assertTrue('default' in subgraphs) fetches, feeds = subgraphs['default'] self.assertTrue('wav' in feeds) for name in ['hypotheses', 'scores', 'src_frames', 'encoder_frames']: self.assertTrue(name in fetches) with open( test_helper.test_src_dir_path('tools/testdata/gan_or_vae.16k.wav'), 'rb') as f: wav = f.read() sess.run(tf.global_variables_initializer()) fetches = sess.run(fetches, {feeds['wav']: wav}) self.assertAllEqual((1, p.decoder.beam_search.num_hyps_per_beam), fetches['hypotheses'].shape) self.assertAllEqual((1, p.decoder.beam_search.num_hyps_per_beam), fetches['scores'].shape) self.assertAllEqual((1, 314, p.encoder.input_shape[2], 1), fetches['src_frames'].shape) self.assertAllEqual((80, 1, 2 * p.encoder.lstm_cell_size), fetches['encoder_frames'].shape) if __name__ == '__main__': tf.test.main()
[ "tensorflow.Graph", "tensorflow.all_variables", "tensorflow.test.main", "tensorflow.trainable_variables", "tensorflow.global_variables_initializer", "tensorflow.set_random_seed" ]
lingvo/tasks/asr/model_test.py
[(434, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (57, 'lingvo.tasks.asr.model.AsrModel.Params', 'model.AsrModel.Params', ([], {}), False, 'from lingvo.tasks.asr import model\n'), (60, 'lingvo.tasks.asr.model_test_input_generator.TestInputGenerator.Params', 'tig.TestInputGenerator.Params', ([], {}), True, 'from lingvo.tasks.asr import model_test_input_generator as tig\n'), (70, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820985)'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820985)'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820985)'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820985)'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820985)'], {}), True, 'import tensorflow as tf\n'), (286, 'lingvo.core.base_layer.RecursiveFindLayerParams', 'base_layer.RecursiveFindLayerParams', (['mdl.params'], {}), False, 'from lingvo.core import base_layer\n'), (322, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (323, 'lingvo.core.py_utils.SumSquared', 'py_utils.SumSquared', (['all_vars'], {}), False, 'from lingvo.core import py_utils\n'), (330, 'lingvo.core.py_utils.ComputeGradients', 'py_utils.ComputeGradients', (['mdl.loss', 'mdl.vars'], {}), False, 'from lingvo.core import py_utils\n'), (331, 'lingvo.core.summary_utils.CollectVarHistogram', 'summary_utils.CollectVarHistogram', (['var_grads'], {}), False, 'from lingvo.core import summary_utils\n'), (338, 'lingvo.core.py_utils.ComputeGradients', 'py_utils.ComputeGradients', (['mdl.loss', 'mdl.vars'], {}), False, 'from lingvo.core import py_utils\n'), (339, 'lingvo.core.py_utils.ApplyGradMultiplier', 'py_utils.ApplyGradMultiplier', (['var_grads', '(-1.1)'], {}), False, 'from lingvo.core import py_utils\n'), (377, 'lingvo.tasks.asr.model.AsrModel.Params', 'model.AsrModel.Params', ([], {}), False, 'from lingvo.tasks.asr import model\n'), (396, 'lingvo.tasks.asr.input_generator.AsrInput.Params', 'input_generator.AsrInput.Params', ([], {}), False, 'from lingvo.tasks.asr import input_generator\n'), (358, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(93820981)'], {}), True, 'import tensorflow as tf\n'), (420, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.all_variables', 'tf.all_variables', ([], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (272, 'lingvo.core.schedule.ContinuousLearningRateSchedule.Params', 'schedule.ContinuousLearningRateSchedule.Params', ([], {}), False, 'from lingvo.core import schedule\n'), (277, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (282, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (318, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (364, 'lingvo.core.cluster_factory.ForTestingWorker', 'cluster_factory.ForTestingWorker', ([], {'gpus': 'num_splits'}), False, 'from lingvo.core import cluster_factory\n'), (405, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (417, 'lingvo.core.test_helper.test_src_dir_path', 'test_helper.test_src_dir_path', (['"""tools/testdata/gan_or_vae.16k.wav"""'], {}), False, 'from lingvo.core import test_helper\n'), (357, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (367, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n')]
qrsforever/workspace
53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @file tf_print.py # @brief # @author QRS # @blog qrsforever.github.io # @version 1.0 # @date 2019-06-02 15:40:55 ################################ jupyter-vim ####################################### # https://github.com/qrsforever/vim/blob/master/bundle/.configs/jupyter-vim_conf.vim # %pylab --no-import-all # noqa ##################################################################################### # https://github.com/yaroslavvb/memory_util import sys import tensorflow as tf import memory_util memory_util.vlog(1) sess = tf.Session() with sess.as_default(): tensor = tf.range(10) print_op = tf.print("tensors:", tensor, {'2': tensor * 2}, output_stream=sys.stderr) with tf.control_dependencies([print_op]): tripled_tensor = tensor * 3 with memory_util.capture_stderr() as stderr: print(sess.run(tripled_tensor)) print(stderr.getvalue())
[ "tensorflow.print", "tensorflow.range", "tensorflow.Session", "tensorflow.control_dependencies" ]
ML/learn/tensorflow/tf_print.py
[(22, 'memory_util.vlog', 'memory_util.vlog', (['(1)'], {}), False, 'import memory_util\n'), (24, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.range', 'tf.range', (['(10)'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.print', 'tf.print', (['"""tensors:"""', 'tensor', "{'2': tensor * 2}"], {'output_stream': 'sys.stderr'}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[print_op]'], {}), True, 'import tensorflow as tf\n'), (30, 'memory_util.capture_stderr', 'memory_util.capture_stderr', ([], {}), False, 'import memory_util\n')]
KoconJan/BERT-NER-CLI
6f1323bf6294bc05ee3ee9a58e5b932a68bb85c0
#! usr/bin/env python3 # -*- coding:utf-8 -*- """ Copyright 2018 The Google AI Language Team Authors. BASED ON Google_BERT. @Author:zhoukaiyin """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os from bert import modeling from bert import optimization from bert import tokenization import tensorflow as tf from sklearn.metrics import f1_score,precision_score,recall_score from tensorflow.python.ops import math_ops import tf_metrics flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string( "data_dir", './drive/My Drive/ai/NERdata', "The input datadir.", ) flags.DEFINE_string( "bert_config_file", './drive/My Drive/ai/checkpoint/bert_config.json', "The config json file corresponding to the pre-trained BERT model." ) flags.DEFINE_string( "task_name", 'NER', "The name of the task to train." ) flags.DEFINE_string( "output_dir", './drive/My Drive/ai/output/result_dir/', "The output directory where the model checkpoints will be written." ) flags.DEFINE_string( "tpu_name", 'gcp_tpu', "Use Google Cloud Colaborator TPU to train" ) ## Other parameters flags.DEFINE_string( "init_checkpoint", './drive/My Drive/ai/checkpoint/bert_model.ckpt', "Initial checkpoint (usually from a pre-trained BERT model)." ) flags.DEFINE_bool( "do_lower_case", True, "Whether to lower case the input text." ) flags.DEFINE_integer( "max_seq_length", 128, "The maximum total input sequence length after WordPiece tokenization." ) flags.DEFINE_bool( "do_train", True, "Whether to run training." ) flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") 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_float("num_train_epochs", 3.0, "Total number of training epochs to perform.") flags.DEFINE_float( "warmup_proportion", 0.1, "Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") 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_string("vocab_file", './drive/My Drive/ai/checkpoint/vocab.txt', "The vocabulary file that the BERT model was trained on.") 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.") class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text, label=None): """Constructs a InputExample. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. """ self.guid = guid self.text = text self.label = label class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_ids): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_ids = label_ids class DataProcessor(object): """Base class for data converters for sequence classification data sets.""" def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`s for the dev set.""" raise NotImplementedError() def get_labels(self): """Gets the list of labels for this data set.""" raise NotImplementedError() @classmethod def _read_data(cls, input_file): """Reads a BIO data.""" with open(input_file) as f: lines = [] words = [] labels = [] for line in f: contends = line.strip() word = line.strip().split(' ')[0] label = line.strip().split(' ')[-1] if contends.startswith("-DOCSTART-"): words.append('') continue if len(contends) == 0 and words[-1] == '.': l = ' '.join([label for label in labels if len(label) > 0]) w = ' '.join([word for word in words if len(word) > 0]) lines.append([l, w]) words = [] labels = [] continue words.append(word) labels.append(label) return lines class NerProcessor(DataProcessor): def get_train_examples(self, data_dir): return self._create_example( self._read_data(os.path.join(data_dir, "train.txt")), "train" ) def get_dev_examples(self, data_dir): return self._create_example( self._read_data(os.path.join(data_dir, "dev.txt")), "dev" ) def get_labels(self): return ["B-MISC", "I-MISC", "O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "X"] def _create_example(self, lines, set_type): examples = [] for (i, line) in enumerate(lines): guid = "%s-%s" % (set_type, i) text = tokenization.convert_to_unicode(line[1]) label = tokenization.convert_to_unicode(line[0]) examples.append(InputExample(guid=guid, text=text, label=label)) return examples def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer): label_map = {} for (i, label) in enumerate(label_list, 1): label_map[label] = i textlist = example.text.split(' ') labellist = example.label.split(' ') tokens = [] labels = [] for i, word in enumerate(textlist): token = tokenizer.tokenize(word) tokens.extend(token) label_1 = labellist[i] for m in range(len(token)): if m == 0: labels.append(label_1) else: labels.append("X") # tokens = tokenizer.tokenize(example.text) if len(tokens) >= max_seq_length - 1: tokens = tokens[0:(max_seq_length - 2)] labels = labels[0:(max_seq_length - 2)] ntokens = [] segment_ids = [] label_ids = [] ntokens.append("[CLS]") segment_ids.append(0) label_ids.append(0) for i, token in enumerate(tokens): ntokens.append(token) segment_ids.append(0) label_ids.append(label_map[labels[i]]) ntokens.append("[SEP]") segment_ids.append(0) label_ids.append(0) input_ids = tokenizer.convert_tokens_to_ids(ntokens) input_mask = [1] * len(input_ids) while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) label_ids.append(0) # print(len(input_ids)) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length assert len(label_ids) == max_seq_length if ex_index < 5: tf.logging.info("*** Example ***") tf.logging.info("guid: %s" % (example.guid)) tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in tokens])) tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) tf.logging.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) tf.logging.info("segment_ids: %s" % " ".join([str(x) for x in segment_ids])) tf.logging.info("label_ids: %s" % " ".join([str(x) for x in label_ids])) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_ids=label_ids ) return feature def filed_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file ): writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 5000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f features = collections.OrderedDict() features["input_ids"] = create_int_feature(feature.input_ids) features["input_mask"] = create_int_feature(feature.input_mask) features["segment_ids"] = create_int_feature(feature.segment_ids) features["label_ids"] = create_int_feature(feature.label_ids) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writer.write(tf_example.SerializeToString()) def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.FixedLenFeature([seq_length], tf.int64), } def _decode_record(record, name_to_features): example = tf.parse_single_example(record, name_to_features) 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 input_fn(params): batch_size = params["batch_size"] d = tf.data.TFRecordDataset(input_file) if is_training: d = d.repeat() d = d.shuffle(buffer_size=100) d = d.apply(tf.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, drop_remainder=drop_remainder )) return d return input_fn def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): 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 ) output_layer = model.get_sequence_output() hidden_size = output_layer.shape[-1].value output_weight = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02) ) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer() ) with tf.variable_scope("loss"): if is_training: output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) output_layer = tf.reshape(output_layer, [-1, hidden_size]) logits = tf.matmul(output_layer, output_weight, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, 11]) log_probs = tf.nn.log_softmax(logits, axis=-1) # labels = tf.cast(labels,dtype=tf.float32) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_sum(per_example_loss) return (loss, per_example_loss, logits) def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): def model_fn(features, labels, mode, params): 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"] label_ids = features["label_ids"] is_training = (mode == tf.estimator.ModeKeys.TRAIN) (total_loss, per_example_loss, logits) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,init_checkpoint) tf.train.init_from_checkpoint(init_checkpoint, assignment_map) 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(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) precision = tf_metrics.precision(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro") recall = tf_metrics.recall(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro") f = tf_metrics.f1(label_ids,predictions,11,[1,2,4,5,6,7,8,9],average="macro") loss = tf.metrics.mean(per_example_loss) return { "eval_precision":precision, "eval_recall":recall, "eval_f": f, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits]) 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 main(_): tf.logging.set_verbosity(tf.logging.INFO) processors = { "ner": NerProcessor } 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) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( "Cannot use sequence length %d because the BERT model " "was only trained up to sequence length %d" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR']) 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, 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)) train_examples = None num_train_steps = None num_warmup_steps = None if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs) num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion) model_fn = model_fn_builder( bert_config=bert_config, num_labels=len(label_list)+1, init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, use_tpu=FLAGS.use_tpu, use_one_hot_embeddings=FLAGS.use_tpu) 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: train_file = os.path.join(FLAGS.output_dir, "train.tf_record") filed_based_convert_examples_to_features( train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=train_file, seq_length=FLAGS.max_seq_length, is_training=True, drop_remainder=True) estimator.train(input_fn=train_input_fn, max_steps=num_train_steps) if FLAGS.do_eval: eval_examples = processor.get_dev_examples(FLAGS.data_dir) eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record") filed_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Num examples = %d", len(eval_examples)) tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size) eval_steps = None if FLAGS.use_tpu: eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size) eval_drop_remainder = True if FLAGS.use_tpu else False eval_input_fn = file_based_input_fn_builder( input_file=eval_file, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=eval_drop_remainder) result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with open(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__": tf.app.run()
[ "tensorflow.contrib.cluster_resolver.TPUClusterResolver", "tensorflow.FixedLenFeature", "tensorflow.nn.log_softmax", "tensorflow.reduce_sum", "tensorflow.train.init_from_checkpoint", "tensorflow.to_int32", "tensorflow.contrib.tpu.TPUEstimatorSpec", "tensorflow.contrib.tpu.TPUEstimator", "tensorflow.data.TFRecordDataset", "tensorflow.truncated_normal_initializer", "tensorflow.python_io.TFRecordWriter", "tensorflow.logging.set_verbosity", "tensorflow.trainable_variables", "tensorflow.parse_single_example", "tensorflow.argmax", "tensorflow.app.run", "tensorflow.nn.dropout", "tensorflow.metrics.mean", "tensorflow.matmul", "tensorflow.zeros_initializer", "tensorflow.logging.info", "tensorflow.one_hot", "tensorflow.contrib.tpu.TPUConfig", "tensorflow.train.Features", "tensorflow.nn.bias_add", "tensorflow.train.Scaffold", "tensorflow.flags.DEFINE_string", "tensorflow.reshape", "tensorflow.variable_scope" ]
bert_ner.py
[(95, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""master"""', 'None', '"""[Optional] TensorFlow master URL."""'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.python_io.TFRecordWriter', 'tf.python_io.TFRecordWriter', (['output_file'], {}), True, 'import tensorflow as tf\n'), (314, 'bert.modeling.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'}), False, 'from bert import modeling\n'), (426, 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), True, 'import tensorflow as tf\n'), (433, 'bert.modeling.BertConfig.from_json_file', 'modeling.BertConfig.from_json_file', (['FLAGS.bert_config_file'], {}), False, 'from bert import modeling\n'), (448, 'bert.tokenization.FullTokenizer', 'tokenization.FullTokenizer', ([], {'vocab_file': 'FLAGS.vocab_file', 'do_lower_case': 'FLAGS.do_lower_case'}), False, 'from bert import tokenization\n'), (481, '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'), (531, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.logging.info', 'tf.logging.info', (['"""*** Example ***"""'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.logging.info', 'tf.logging.info', (["('guid: %s' % example.guid)"], {}), True, 'import tensorflow as tf\n'), (271, 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), False, 'import collections\n'), (282, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (283, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (284, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.parse_single_example', 'tf.parse_single_example', (['record', 'name_to_features'], {}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['input_file'], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""loss"""'], {}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.reshape', 'tf.reshape', (['output_layer', '[-1, hidden_size]'], {}), True, 'import tensorflow as tf\n'), (338, 'tensorflow.matmul', 'tf.matmul', (['output_layer', 'output_weight'], {'transpose_b': '(True)'}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['logits', 'output_bias'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1, FLAGS.max_seq_length, 11]'], {}), True, 'import tensorflow as tf\n'), (341, 'tensorflow.nn.log_softmax', 'tf.nn.log_softmax', (['logits'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.one_hot', 'tf.one_hot', (['labels'], {'depth': 'num_labels', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (346, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['per_example_loss'], {}), True, 'import tensorflow as tf\n'), (354, 'tensorflow.logging.info', 'tf.logging.info', (['"""*** Features ***"""'], {}), True, 'import tensorflow as tf\n'), (367, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (379, 'tensorflow.logging.info', 'tf.logging.info', (['"""**** Trainable Variables ****"""'], {}), True, 'import tensorflow as tf\n'), (452, 'tensorflow.contrib.cluster_resolver.TPUClusterResolver', 'tf.contrib.cluster_resolver.TPUClusterResolver', (["('grpc://' + os.environ['COLAB_TPU_ADDR'])"], {}), True, 'import tensorflow as tf\n'), (489, 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""train.tf_record"""'], {}), False, 'import os\n'), (492, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Running training *****"""'], {}), True, 'import tensorflow as tf\n'), (494, 'tensorflow.logging.info', 'tf.logging.info', (['""" Batch size = %d"""', 'FLAGS.train_batch_size'], {}), True, 'import tensorflow as tf\n'), (495, 'tensorflow.logging.info', 'tf.logging.info', (['""" Num steps = %d"""', 'num_train_steps'], {}), True, 'import tensorflow as tf\n'), (504, 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""eval.tf_record"""'], {}), False, 'import os\n'), (508, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Running evaluation *****"""'], {}), True, 'import tensorflow as tf\n'), (510, 'tensorflow.logging.info', 'tf.logging.info', (['""" Batch size = %d"""', 'FLAGS.eval_batch_size'], {}), True, 'import tensorflow as tf\n'), (521, 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""eval_results.txt"""'], {}), False, 'import os\n'), (187, 'bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[1]'], {}), False, 'from bert import tokenization\n'), (188, 'bert.tokenization.convert_to_unicode', 'tokenization.convert_to_unicode', (['line[0]'], {}), False, 'from bert import tokenization\n'), (329, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.02)'}), True, 'import tensorflow as tf\n'), (332, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['output_layer'], {'keep_prob': '(0.9)'}), True, 'import tensorflow as tf\n'), (345, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(one_hot_labels * log_probs)'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.logging.info', 'tf.logging.info', (["(' name = %s, shape = %s' % (name, features[name].shape))"], {}), True, 'import tensorflow as tf\n'), (370, 'bert.modeling.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['tvars', 'init_checkpoint'], {}), False, 'from bert import modeling\n'), (371, 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), True, 'import tensorflow as tf\n'), (385, 'tensorflow.logging.info', 'tf.logging.info', (['""" name = %s, shape = %s%s"""', 'var.name', 'var.shape', 'init_string'], {}), True, 'import tensorflow as tf\n'), (389, 'bert.optimization.create_optimizer', 'optimization.create_optimizer', (['total_loss', 'learning_rate', 'num_train_steps', 'num_warmup_steps', 'use_tpu'], {}), False, 'from bert import optimization\n'), (391, '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'), (459, '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'), (523, 'tensorflow.logging.info', 'tf.logging.info', (['"""***** Eval results *****"""'], {}), True, 'import tensorflow as tf\n'), (172, 'os.path.join', 'os.path.join', (['data_dir', '"""train.txt"""'], {}), False, 'import os\n'), (177, 'os.path.join', 'os.path.join', (['data_dir', '"""dev.txt"""'], {}), False, 'import os\n'), (276, 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'features'}), True, 'import tensorflow as tf\n'), (293, 'tensorflow.to_int32', 'tf.to_int32', (['t'], {}), True, 'import tensorflow as tf\n'), (378, 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), True, 'import tensorflow as tf\n'), (412, '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'), (374, 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), True, 'import tensorflow as tf\n'), (375, 'tensorflow.train.Scaffold', 'tf.train.Scaffold', ([], {}), True, 'import tensorflow as tf\n'), (399, 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(-1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (400, 'tf_metrics.precision', 'tf_metrics.precision', (['label_ids', 'predictions', '(11)', '[1, 2, 4, 5, 6, 7, 8, 9]'], {'average': '"""macro"""'}), False, 'import tf_metrics\n'), (401, 'tf_metrics.recall', 'tf_metrics.recall', (['label_ids', 'predictions', '(11)', '[1, 2, 4, 5, 6, 7, 8, 9]'], {'average': '"""macro"""'}), False, 'import tf_metrics\n'), (402, 'tf_metrics.f1', 'tf_metrics.f1', (['label_ids', 'predictions', '(11)', '[1, 2, 4, 5, 6, 7, 8, 9]'], {'average': '"""macro"""'}), False, 'import tf_metrics\n'), (403, 'tensorflow.metrics.mean', 'tf.metrics.mean', (['per_example_loss'], {}), True, 'import tensorflow as tf\n'), (244, 'bert.tokenization.printable_text', 'tokenization.printable_text', (['x'], {}), False, 'from bert import tokenization\n')]
golunovas/onnx-tensorflow
b6340b3e66aa08af1ea4382e98257c2098177371
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import unittest import numpy as np import tensorflow as tf from onnx_tf.backend import run_node from onnx_tf.common import supports_device from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver from onnx import helper from onnx import TensorProto from onnx import defs class TestNode(unittest.TestCase): """ Tests for nodes """ def _get_rnd_float32(self, low=-1.0, high=1.0, shape=None): output = np.random.uniform(low, high, shape) if shape == None: return np.float32(output) else: return output.astype(np.float32) def _get_rnd_int(self, low, high=None, shape=None, dtype=np.int32): return np.random.randint(low, high, size=shape, dtype=dtype) def _elu(self, x): # f(x) = alpha * (exp(x) - 1.) for x < 0, # f(x) = x for x >= 0 if x < 0.: return np.expm1(x) return x def _leaky_relu(self, x, alpha): # f(x) = alpha * x for x < 0, # f(x) = x for x >= 0 if x < 0.: return alpha * x return x def test_abs(self): node_def = helper.make_node("Abs", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.abs(x)) def test_acosh(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Acosh.".format( defs.onnx_opset_version())) node_def = helper.make_node("Acosh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.arccosh(x)) def test_add(self): node_def = helper.make_node("Add", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[5, 10, 5, 5]) y = self._get_rnd_float32(shape=[10, 1, 1]) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.add(x, y.reshape([1, 10, 1, 1]))) # node_def = helper.make_node("Add", ["A", "B"], ["C"], broadcast=1) # a = self._get_rnd([10, 10]) # b = self._get_rnd([10, 10]) # output = run_node(node_def, [a, b]) # np.testing.assert_almost_equal(output["C"], np.add(a, b)) # node_def = helper.make_node("Add", ["A", "B"], ["C"], broadcast=1) # a = self._get_rnd([10, 10]) # b = self._get_rnd([10,]) # output = run_node(node_def, [a, b]) # np.testing.assert_almost_equal(output["C"], np.add(a, b)) def test_arg_max(self): # TODO: need to fix this test return for axis in [0, 1]: node_def = helper.make_node( "ArgMax", ["data"], ["reduced"], axis=axis, keepdims=0) data = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [data]) np.testing.assert_almost_equal(output["reduced"], np.argmax(data, axis=axis)) def test_arg_min(self): # TODO: need to fix this test return for axis in [0, 1]: node_def = helper.make_node( "ArgMin", ["data"], ["reduced"], axis=axis, keepdims=0) data = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [data]) np.testing.assert_almost_equal(output["reduced"], np.argmin(data, axis=axis)) def test_asinh(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Asinh.".format( defs.onnx_opset_version())) node_def = helper.make_node("Asinh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.arcsinh(x)) def test_atanh(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Atanh.".format( defs.onnx_opset_version())) node_def = helper.make_node("Atanh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.arctanh(x)) def test_average_pool(self): # TODO: fix this test return device = "CUDA" if not supports_device(device): raise unittest.SkipTest( "Backend doesn't support device {}".format(device)) shape = [1, 1, 40, 40] node_def = helper.make_node( "AveragePool", ["X"], ["Y"], kernel_shape=[1, 2], pads=[1, 1], strides=[1, 1]) x = self._get_rnd_float32(shape=shape) output = run_node(node_def, [x], device=device) test_output = np.zeros(shape) for i1 in range(0, shape[0]): for i2 in range(0, shape[1]): for j1 in range(0, shape[2]): for j2 in range(0, shape[3]): test_output[i1][i2][j1][j2] = 0 count = 0 for k in range(j2, min(j2 + 2, shape[3])): test_output[i1][i2][j1][j2] += x[i1][i2][j1][k] count += 1 test_output[i1][i2][j1][j2] /= count np.testing.assert_almost_equal(output["Y"], test_output) def _batch_normalization(self, x, mean, variance, bias, scale, variance_epsilon): inv = np.reciprocal(np.sqrt(variance + variance_epsilon)) if scale is not None: inv *= scale return x * inv + (bias - mean * inv if bias is not None else -mean * inv) def test_batch_normalization(self): if legacy_opset_pre_ver(6): raise unittest.SkipTest("Backend doesn't support consumed flag") node_def = helper.make_node( "BatchNormalization", ["X", "scale", "bias", "mean", "var"], ["Y"], epsilon=0.001) x_shape = [3, 5, 4, 2] param_shape = [5] _param_shape = [1, 5, 1, 1] x = self._get_rnd_float32(0, 1, shape=x_shape) m = self._get_rnd_float32(0, 1, shape=param_shape) _m = m.reshape(_param_shape) v = self._get_rnd_float32(0, 1, shape=param_shape) _v = v.reshape(_param_shape) scale = self._get_rnd_float32(0, 1, shape=param_shape) _scale = scale.reshape(_param_shape) bias = self._get_rnd_float32(0, 1, shape=param_shape) _bias = bias.reshape(_param_shape) golden = self._batch_normalization(x, _m, _v, _bias, _scale, 0.001) output = run_node(node_def, [x, scale, bias, m, v]) np.testing.assert_almost_equal(output["Y"], golden, decimal=5) def test_cast(self): if legacy_onnx_pre_ver(1, 2) or legacy_opset_pre_ver(6): test_cases = [("FLOAT", tf.float32), ("UINT8", tf.uint8), ("INT8", tf.int8), ("UINT16", tf.uint16), ("INT16", tf.int16), ("INT32", tf.int32), ("INT64", tf.int64), ("BOOL", tf.bool), ("FLOAT16", tf.float16), ("DOUBLE", tf.float64), ("COMPLEX64", tf.complex64), ("COMPLEX128", tf.complex128)] else: test_cases = [(TensorProto.FLOAT, tf.float32), (TensorProto.UINT8, tf.uint8), (TensorProto.INT8, tf.int8), (TensorProto.UINT16, tf.uint16), (TensorProto.INT16, tf.int16), (TensorProto.INT32, tf.int32), (TensorProto.INT64, tf.int64), (TensorProto.BOOL, tf.bool), (TensorProto.FLOAT16, tf.float16), (TensorProto.DOUBLE, tf.float64), (TensorProto.COMPLEX64, tf.complex64), (TensorProto.COMPLEX128, tf.complex128)] if not legacy_opset_pre_ver(9): test_cases.append((TensorProto.STRING, tf.string)) for ty, tf_type in test_cases: node_def = helper.make_node("Cast", ["input"], ["output"], to=ty) vector = [2, 3] output = run_node(node_def, [vector]) np.testing.assert_equal(output["output"].dtype, tf_type) if not legacy_opset_pre_ver(9): test_cases2 = [(TensorProto.FLOAT, tf.float32), (TensorProto.INT32, tf.int32), (TensorProto.INT64, tf.int64), (TensorProto.DOUBLE, tf.float64)] for ty, tf_type in test_cases2: node_def = helper.make_node("Cast", ["input"], ["output"], to=ty) vector = ['2', '3'] output = run_node(node_def, [vector]) np.testing.assert_equal(output["output"].dtype, tf_type) def test_ceil(self): node_def = helper.make_node("Ceil", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.ceil(x)) def test_compress(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest( "ONNX version {} doesn't support Compress.".format( defs.onnx_opset_version())) axis = 1 node_def = helper.make_node( "Compress", inputs=['X', 'condition'], outputs=['Y'], axis=axis) x = self._get_rnd_float32(shape=[5, 5, 5]) cond = np.array([1, 0, 1]) output = run_node(node_def, inputs=[x, cond]) np.testing.assert_almost_equal(output['Y'], np.compress(cond, x, axis=axis)) def test_concat(self): shape = [10, 20, 5] for axis in range(len(shape)): node_def = helper.make_node("Concat", ["X1", "X2"], ["Y"], axis=axis) x1 = self._get_rnd_float32(shape=shape) x2 = self._get_rnd_float32(shape=shape) output = run_node(node_def, [x1, x2]) np.testing.assert_almost_equal(output["Y"], np.concatenate((x1, x2), axis)) def test_constant(self): shape = [16, 16] values = np.random.randn(*shape).flatten().astype(float) const2_onnx = helper.make_tensor("const2", TensorProto.DOUBLE, shape, values) node_def = helper.make_node("Constant", [], ["Y"], value=const2_onnx) output = run_node(node_def, []) np.testing.assert_equal(output["Y"].shape, shape) np.testing.assert_almost_equal(output["Y"].flatten(), values) # test sparse tensor if not legacy_opset_pre_ver(11): expected = np.array([[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]) x = np.array([[0, 0], [1, 2]]).flatten().astype(np.int64) values = helper.make_tensor("values", TensorProto.INT32, [2], [1, 2]) indices = helper.make_tensor("indices", TensorProto.INT64, [2, 2], x) a = helper.make_sparse_tensor(values, indices,[3, 4]) node_def = helper.make_node("Constant", [], ["Y"], sparse_value=a) output = run_node(node_def, []) b = tf.sparse_to_dense(output["Y"].indices, output["Y"].dense_shape, output["Y"].values) result = b.eval(session=tf.Session()) np.testing.assert_equal(result, expected) def test_constant_fill(self): if not legacy_opset_pre_ver(9): raise unittest.SkipTest( "ONNX version {} doesn't support ConstantFill.".format( defs.onnx_opset_version())) shape = [1, 2, 3, 4] extra_shape = [5, 6] value = 3. node_def = helper.make_node( "ConstantFill", ["X"], ["Y"], value=value, extra_shape=extra_shape, dtype=1, ) x = self._get_rnd_float32(shape=shape) y = np.zeros(shape + extra_shape) y.fill(value) output = run_node(node_def, [x]) np.testing.assert_equal(output["Y"].dtype, tf.float32) np.testing.assert_equal(output["Y"], y) def test_constant_of_shape(self): if defs.onnx_opset_version() < 9: raise unittest.SkipTest( "ONNX version {} doesn't support ConstantOfShape.".format( defs.onnx_opset_version())) v = helper.make_tensor("value", TensorProto.FLOAT, [1], [1]) node_def = helper.make_node("ConstantOfShape", ["X"], ["Y"], value=v) x = np.array([4, 3, 2]) output = run_node(node_def, inputs=[x]) np.testing.assert_almost_equal(output["Y"], np.ones(x, dtype=np.float32)) v = helper.make_tensor("value", TensorProto.INT32, [1], [0]) node_def = helper.make_node("ConstantOfShape", ["X"], ["Y"], value=v) x = np.array([10, 6]) output = run_node(node_def, inputs=[x]) np.testing.assert_almost_equal(output["Y"], np.zeros(x, dtype=np.int32)) def test_conv(self): device = "CUDA" if not supports_device(device): raise unittest.SkipTest( "Backend doesn't support device {}".format(device)) N, C, H, W = 4, 3, 5, 5 x_shape = [N, C, H, W] K, kH, kW = 6, 3, 3 weight_shape = [K, C, kH, kW] node_def = helper.make_node( "Conv", ["X", "weights"], ["Y"], pads=[1, 1, 1, 1], kernel_shape=[kH, kW]) x = self._get_rnd_float32(shape=x_shape) weights = self._get_rnd_float32(shape=weight_shape) output = run_node(node_def, [x, weights], device=device) out_shape = [N, K, H, W] test_output = np.zeros(out_shape) for n in range(N): for c in range(C): for h in range(H): for w in range(W): for k in range(K): for kh in range(kH): for kw in range(kW): h_in_range = (h - kH // 2 + kh) < H and ( h - kH // 2 + kh) >= 0 w_in_range = (w - kW // 2 + kw) < W and ( w - kW // 2 + kw) >= 0 if h_in_range and w_in_range: test_output[n][k][h][w] += (x[n][c][h - kH // 2 + kh][ w - kW // 2 + kw] * weights[k][c][kh][kw]) np.testing.assert_almost_equal(output["Y"], test_output, decimal=5) def test_conv_transpose(self): # Fix test in the future. return device = "CUDA" if not supports_device(device): raise unittest.SkipTest( "Backend doesn't support device {}".format(device)) node_def = helper.make_node( "ConvTranspose", ["X", "weights"], ["Y"], pads=[1, 1]) x_shape = [1, 5, 4] x = self._get_rnd(x_shape) weight_shape = [5, 3, 2] weights = self._get_rnd_float32(shape=weight_shape) output = run_node(node_def, [x, weights], device=device) out_shape = [x_shape[0], weight_shape[1], x_shape[2]] test_output = np.zeros(out_shape) for b in range(0, x_shape[0]): for m in range(0, weight_shape[1]): for h in range(0, x_shape[2]): v = 0 for c in range(0, x_shape[1]): for k in range(h, min(h + weight_shape[2], x_shape[2])): v += x[b][c][k] * weights[c][m][k - h] test_output[b][m][h] = v np.testing.assert_almost_equal(output["Y"], test_output, decimal=5) def test_cosh(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Cosh.".format( defs.onnx_opset_version())) node_def = helper.make_node("Cosh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.cosh(x)) def test_depth_to_space(self): node_def = helper.make_node("DepthToSpace", ["X"], ["Y"], blocksize=2) x_shape = [1, 12, 1, 1] x = self._get_rnd_float32(shape=x_shape) output = run_node(node_def, [x]) x = np.transpose(x, (0, 2, 3, 1)) y = np.reshape(np.swapaxes(x.reshape(1, 1, 1, 2, 2, 3), 2, 3), (1, 2, 2, 3)) y = np.transpose(y, (0, 3, 1, 2)) np.testing.assert_almost_equal(output["Y"], y, decimal=5) def test_dequantize_linear(self): node_def = helper.make_node("DequantizeLinear", ["x", "x_scale", "x_zero_point"], ["y"]) for x, x_zero_point in [ [ self._get_rnd_int(-128, 127, [2, 6], np.int8), self._get_rnd_int(-128, 127, dtype=np.int8) ], [ self._get_rnd_int(0, 255, [2, 6], np.uint8), self._get_rnd_int(0, 255, dtype=np.uint8) ], [ self._get_rnd_int(-512, 512, [2, 6]), np.int32(0) ] ]: x_scale = self._get_rnd_float32(-10., 10) y = np.subtract(np.float32(x), np.float32(x_zero_point)) y = np.multiply(y, x_scale) output = run_node(node_def, [x, x_scale, x_zero_point]) np.testing.assert_almost_equal(output["y"], y) def test_div(self): node_def = helper.make_node("Div", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[10, 10]) y = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.divide(x, y)) def test_dropout(self): # Since current ONNX only support inference and # dropout at inference mode is a no-op, # therefore dropout is always a no-op operator # in ONNX. node_def = helper.make_node("Dropout", ["X"], ["Y"]) if legacy_opset_pre_ver(7): # at inference mode, is_test is always set to 1 node_def = helper.make_node("Dropout", ["X"], ["Y"], is_test=1) x = self._get_rnd_float32(shape=[3, 4, 5]) y = x output = run_node(node_def, [x]) np.testing.assert_equal(output["Y"], y) def test_dot(self): # this op is removed # remove this test in the future return node_def = helper.make_node("Dot", ["X", "Y"], ["Z"]) x = np.floor(self._get_rnd_float32(shape=[10, 10])) y = np.floor(self._get_rnd_float32(shape=[10, 10])) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.dot(x, y)) def test_elu(self): node_def = helper.make_node("Elu", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[100]) output = run_node(node_def, [x]) test_output = [self._elu(a) for a in x] np.testing.assert_almost_equal(output["Y"], test_output) def test_equal(self): node_def = helper.make_node("Equal", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[5, 3, 3, 2]) y = self._get_rnd_float32(shape=[3, 3, 1]) output = run_node(node_def, [x, y]) np.testing.assert_equal(output["Z"], np.equal(x, np.reshape( y, [1, 3, 3, 1]))) def test_erf(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Erf.".format( defs.onnx_opset_version())) node_def = helper.make_node("Erf", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) exp_output = np.vectorize(math.erf)(x).astype(np.float32) np.testing.assert_almost_equal(output["Y"], exp_output) def test_exp(self): node_def = helper.make_node("Exp", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[100]) x = x - 3.6 output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.exp(x)) def test_eye_like(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support EyeLike.".format( defs.onnx_opset_version())) for shape in [[6, 10], [10, 6]]: for off_diagonal_offset in [-10, -6, -3, 0, 3, 6, 7, 10]: node_def = helper.make_node( "EyeLike", ['x'], ['y'], dtype=1, k=off_diagonal_offset) x = self._get_rnd_int(0, 100, shape=shape) y = np.eye(shape[0], shape[1], k=off_diagonal_offset, dtype=np.float32) output = run_node(node_def, [x]) np.testing.assert_equal(output['y'], y) def test_flatten(self): # If input tensor has shape (d_0, d_1, ... d_n) then the # output will have shape: # # (d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn) # # TODO: pass axis attribute which is supported in newer # versions of onnx node_def = helper.make_node("Flatten", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[10, 2, 3, 4, 5]) output = run_node(node_def, [x]) # TODO: pass axis=3 and uncomment the line below # np.testing.assert_almost_equal(output["Y"], x.reshape([60, 20])) np.testing.assert_almost_equal(output["Y"], x.reshape([10, 120])) def test_gather(self): node_def = helper.make_node("Gather", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[10, 10]) y = [[0, 1], [1, 2]] output = run_node(node_def, [x, y]) test_output = np.zeros((2, 2, 10)) for i in range(0, 2): for j in range(0, 10): test_output[0][i][j] = x[i][j] for i in range(0, 2): for j in range(0, 10): test_output[1][i][j] = x[i + 1][j] np.testing.assert_almost_equal(output["Z"], test_output) def test_gemm(self): # Compute Y = alpha * A * B + beta * C node_def = helper.make_node( "Gemm", ["A", "B", "C"], ["Y"], transA=0, transB=0, alpha=1.0, beta=1.0) x = np.floor(self._get_rnd_float32(shape=[10, 10])) y = np.floor(self._get_rnd_float32(shape=[10, 10])) z = np.floor(self._get_rnd_float32(shape=[10, 10])) output = run_node(node_def, [x, y, z]) test_output = np.matmul(x, y) + z np.testing.assert_almost_equal(output["Y"], test_output) def test_global_average_pool(self): # Image case: (N x C x H x W), where N is the batch size, # C is the number of channels, and H and W are the height # and the width of the data # # Non-image case: (N x C x D1 x D2 ... Dn) # # Output data tensor from pooling across the input tensor. # Dimensions will be N x C x 1 x 1 node_def = helper.make_node("GlobalAveragePool", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[10, 10, 2, 3]) output = run_node(node_def, [x]) test_output = np.zeros([10, 10, 1, 1]) for i1 in range(0, 10): for i2 in range(0, 10): sum = 0 for j1 in range(0, 2): for j2 in range(0, 3): sum += x[i1][i2][j1][j2] test_output[i1][i2][0][0] = sum / 6. np.testing.assert_almost_equal(output["Y"], test_output) def test_image_sacler(self): # Input: (N x C x H x W), where N is the batch size, # C is the number of channels, and H and W are the height # and the width of the data # Scale: (flout, default 1.0) the scale to apply # Bias: applied to each channel, same size as C # Output has same shape and type as input x = self._get_rnd_float32(shape=[1, 3, 224, 224]) #random distribution over [0,1), so add 0.1 scale = np.random.rand(1)[0] + 0.1 bias = np.random.rand(3) node_def = helper.make_node( "ImageScaler", ["X"], ["Y"], scale=scale, bias=bias) output = run_node(node_def, [x]) test_out = np.multiply(x, scale) test_out = np.transpose(test_out, [0, 2, 3, 1]) test_out = np.add(test_out, bias) test_out = np.transpose(test_out, [0, 3, 1, 2]) np.testing.assert_almost_equal(output["Y"], test_out) def test_is_inf(self): if legacy_opset_pre_ver(10): raise unittest.SkipTest("ONNX version {} doesn't support IsInf.".format( defs.onnx_opset_version())) input = np.array( [-1.2, np.nan, np.inf, 2.8, np.NINF, np.inf], dtype=np.float32) expected_output = { "node_def": np.isinf(input), "node_def_neg_false": np.isposinf(input), "node_def_pos_false": np.isneginf(input) } node_defs = { "node_def": helper.make_node("IsInf", ["X"], ["Y"]), "node_def_neg_false": helper.make_node("IsInf", ["X"], ["Y"], detect_negative=0), "node_def_pos_false": helper.make_node("IsInf", ["X"], ["Y"], detect_positive=0) } for key in node_defs: output = run_node(node_defs[key], [input]) np.testing.assert_equal(output["Y"], expected_output[key]) def test_isnan(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support IsNaN.".format( defs.onnx_opset_version())) node_def = helper.make_node("IsNaN", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 3]) x[0][1] = x[1][0] = x[2][2] = np.nan output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.isnan(x)) def test_global_lp_pool(self): # Image case: (N x C x H x W), where N is the batch size, # C is the number of channels, and H and W are the height # and the width of the data # # Non-image case: (N x C x D1 x D2 ... Dn) # # Output data tensor from pooling across the input tensor. # Dimensions will be N x C x 1 x 1 node_def = helper.make_node("GlobalLpPool", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[10, 10, 2, 3]) output = run_node(node_def, [x]) test_output = np.zeros([10, 10, 1, 1]) for i1 in range(0, 10): for i2 in range(0, 10): tmp = np.zeros([2, 3]) for j1 in range(0, 2): for j2 in range(0, 3): tmp[j1][j2] = x[i1][i2][j1][j2] test_output[i1][i2][0][0] = np.linalg.norm(tmp) np.testing.assert_almost_equal(output["Y"], test_output, decimal=5) def test_global_max_pool(self): # Image case: (N x C x H x W), where N is the batch size, # C is the number of channels, and H and W are the height # and the width of the data # # Non-image case: (N x C x D1 x D2 ... Dn) # # Output data tensor from pooling across the input tensor. # Dimensions will be N x C x 1 x 1 node_def = helper.make_node("GlobalMaxPool", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[10, 10, 2, 3]) output = run_node(node_def, [x]) test_output = np.zeros([10, 10, 1, 1]) for i1 in range(0, 10): for i2 in range(0, 10): max = x[i1][i2][0][0] for j1 in range(0, 2): for j2 in range(0, 3): if max < x[i1][i2][j1][j2]: max = x[i1][i2][j1][j2] test_output[i1][i2][0][0] = max np.testing.assert_almost_equal(output["Y"], test_output) def test_less(self): node_def = helper.make_node("Less", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[5, 3, 3, 2]) y = self._get_rnd_float32(shape=[3, 3, 1]) output = run_node(node_def, [x, y]) np.testing.assert_equal(output["Z"], np.less(x, np.reshape(y, [1, 3, 3, 1]))) def test_lp_normalization(self): for ordr in range(1, 3): node_def = helper.make_node("LpNormalization", ["X"], ["Y"], p=ordr) x = self._get_rnd([2, 2, 3, 2]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], x / np.expand_dims(np.linalg.norm(x, axis=-1, ord=ordr), -1), rtol=1e-3) def test_l_r_n(self): # Each input value is divided by: # # (bias+(alpha/size)*sum(xi^2 for every xi in the local region))^beta alpha = 2.0 beta = 1.0 bias = 5.0 size = 3 node_def = helper.make_node( "LRN", ["X"], ["Y"], alpha=alpha, beta=beta, bias=bias, size=size) x = self._get_rnd_float32(shape=[10, 2, 10, 10]) output = run_node(node_def, [x]) test_output = np.zeros([10, 10, 10, 2]) x = np.transpose(x, axes=[0, 2, 3, 1]) for i1 in range(0, 10): for i2 in range(0, 10): for j1 in range(0, 10): for j2 in range(0, 2): sqr_sum = 0. # size of 3 means radius 1 in TF speak # i.e. the immediate neighbouring values # if "previous" neighbour exists if j2 > 0: sqr_sum += x[i1][i2][j1][j2 - 1] * x[i1][i2][j1][j2 - 1] # current value sqr_sum += x[i1][i2][j1][j2] * x[i1][i2][j1][j2] # if "next" neighbour exists if j2 < 2 - 1: sqr_sum += x[i1][i2][j1][j2 + 1] * x[i1][i2][j1][j2 + 1] test_output[i1][i2][j1][j2] = \ x[i1][i2][j1][j2] / ((bias + (alpha * 1. / size) * sqr_sum) ** beta) test_output = np.transpose(test_output, axes=[0, 3, 1, 2]) np.testing.assert_almost_equal(output["Y"], test_output) def test_floor(self): node_def = helper.make_node("Floor", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[100]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.floor(x)) def test_leakyrelu(self): node_def = helper.make_node("LeakyRelu", ["X"], ["Y"], alpha=0.8) x = np.floor(self._get_rnd_float32(shape=[100])) output = run_node(node_def, [x]) test_output = [self._leaky_relu(a, 0.8) for a in x] np.testing.assert_almost_equal(output["Y"], test_output) def test_log(self): node_def = helper.make_node("Log", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[100]) x = x + 3.6 output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.log(x)) def test_max(self): node_def = helper.make_node("Max", ["X1", "X2", "X3", "X4"], ["Z"]) x1 = self._get_rnd_float32(shape=[10, 10]) x2 = self._get_rnd_float32(shape=[10, 10]) x3 = self._get_rnd_float32(shape=[10, 10]) x4 = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [x1, x2, x3, x4]) test_output = np.maximum(np.maximum(np.maximum(x1, x2), x3), x4) np.testing.assert_almost_equal(output["Z"], test_output) def test_max_pool(self): return node_def = helper.make_node( "MaxPool", ["X"], ["Y"], dilations=[1, 1], kernel_shape=[1, 2], pads=[0, 0], strides=[1, 2]) x = self._get_rnd_float32(shape=[10, 10, 4, 4]) output = run_node(node_def, [x]) test_output = np.zeros([10, 10, 4, 2]) for i1 in range(0, 10): for i2 in range(0, 10): for j1 in range(0, 4): for j2 in range(0, 2): test_output[i1][i2][j1][j2] = \ max(x[i1][i2][j1][2*j2], x[i1][i2][j1][2*j2 + 1]) np.testing.assert_almost_equal(output["Y"], test_output) def test_mean_variance_normalization(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest( "ONNX version {} doesn't have test for MeanVarianceNormalization" .format(defs.onnx_opset_version())) input_data = self._get_rnd_float32(shape=[2,2,2,2]) # Calculate expected output data using formula: # (Input - Mean)/SD mean = np.mean(input_data, keepdims=1, axis=(0,2,3)) std = np.std(input_data, keepdims=1, axis=(0,2,3)) expected_output = (input_data - mean) / std # Testing without "axes" argument should default to axes=[0,2,3] node_def = helper.make_node("MeanVarianceNormalization", ["X"], ["Y"]) output = run_node(node_def, [input_data]) np.testing.assert_almost_equal(output["Y"], expected_output, decimal=5) def test_min(self): node_def = helper.make_node("Min", ["X1", "X2", "X3", "X4"], ["Z"]) x1 = self._get_rnd_float32(shape=[10, 10]) x2 = self._get_rnd_float32(shape=[10, 10]) x3 = self._get_rnd_float32(shape=[10, 10]) x4 = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [x1, x2, x3, x4]) test_output = np.minimum(np.minimum(np.minimum(x1, x2), x3), x4) np.testing.assert_almost_equal(output["Z"], test_output) def test_mul(self): node_def = helper.make_node("Mul", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[5, 10, 5, 5]) y = self._get_rnd_float32(shape=[10, 1, 1]) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.multiply(x, y.reshape([1, 10, 1, 1]))) def test_mod(self): if legacy_opset_pre_ver(10): raise unittest.SkipTest("ONNX version {} doesn't support Mod.".format( defs.onnx_opset_version())) x = self._get_rnd_float32(shape=[5, 5]) y = self._get_rnd_float32(shape=[5, 5]) node_def = helper.make_node("Mod", ["X", "Y"], ["Z"], fmod=0) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.mod(x, y)) node_def = helper.make_node("Mod", ["X", "Y"], ["Z"], fmod=1) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.fmod(x, y)) def test_neg(self): node_def = helper.make_node("Neg", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.negative(x)) def test_non_zero(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support NonZero.".format( defs.onnx_opset_version())) node_def = helper.make_node("NonZero", ["x"], ["y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) y = np.array(np.nonzero(x)) output = run_node(node_def, [x]) np.testing.assert_equal(output["y"], y) def test_onehot(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support OneHot.".format( defs.onnx_opset_version())) indices = np.array([[0, 2], [1, 2], [0, 1]]) depth = np.int32(5) on_value = 6.0 off_value = 2.0 values = np.array([off_value, on_value]) node_def = helper.make_node( 'OneHot', inputs=['indices', 'depth', 'values'], outputs=['y'], axis=-1) y = (np.arange(depth) == indices[..., None]).astype(int) y = y * (on_value - off_value) + off_value output = run_node(node_def, inputs=[indices, depth, values]) np.testing.assert_equal(output['y'], y) def test_range(self): if legacy_opset_pre_ver(11): raise unittest.SkipTest("ONNX version {} doesn't support Range.".format( defs.onnx_opset_version())) node_def = helper.make_node( "Range", ['start', 'limit', 'delta'], ['y']) # test positive_delta start = self._get_rnd_int(low=0, high=3) limit = self._get_rnd_int(low=10, high=30) delta = np.int32(3) output = run_node(node_def, [start, limit, delta]) np.testing.assert_equal(output['y'], range(start, limit, delta)) # test negative_delta start = self._get_rnd_int(low=20, high=30) limit = self._get_rnd_int(low=1, high=5) delta = np.int32(-2) output = run_node(node_def, [start, limit, delta]) np.testing.assert_equal(output['y'], range(start, limit, delta)) def test_round(self): if legacy_opset_pre_ver(11): raise unittest.SkipTest("ONNX version {} doesn't support Round.".format( defs.onnx_opset_version())) node_def = helper.make_node("Round", ["X"], ["Y"]) x = self._get_rnd_float32(-20.0, 20.0, shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.round(x)) def test_relu(self): node_def = helper.make_node("Relu", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.maximum(x, 0)) def test_pad(self): node_def = helper.make_node( "Pad", ["X"], ["Y"], mode="constant", pads=[1, 1, 1, 1], value=2.0) x = self._get_rnd_float32(shape=[100, 100]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.lib.pad( x, ((1, 1), (1, 1)), 'constant', constant_values=(2, 2))) def test_quantize_linear(self): node_def = helper.make_node("QuantizeLinear", ["x", "y_scale", "y_zero_point"], ["y"]) for x in [ self._get_rnd_float32(-512., 512., [2, 6]), self._get_rnd_int(-512, 512, [2, 6]) ]: y_scale = self._get_rnd_float32(-10., 10.) for y_zero_point in [ self._get_rnd_int(-128, 127, dtype=np.int8), self._get_rnd_int(0, 255, dtype=np.uint8) ]: y = np.divide(x, y_scale) y = np.round(y) y = np.add(y, y_zero_point) if y_zero_point.dtype.type is np.int8: y = np.clip(y, -128, 127).astype(np.int8) else: y = np.clip(y, 0, 255).astype(np.uint8) output = run_node(node_def, [x, y_scale, y_zero_point]) np.testing.assert_almost_equal(output["y"], y) def test_reciprocal(self): node_def = helper.make_node("Reciprocal", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], 1.0 / x) def test_reduce_l1(self): node_def = helper.make_node("ReduceL1", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.linalg.norm(x, 1, (1, 2), True)) def test_reduce_log_sum_exp(self): node_def = helper.make_node("ReduceLogSumExp", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.log(np.sum(np.exp(x), axis=(1, 2), keepdims=True)), rtol=1e-3) def test_reduce_max(self): node_def = helper.make_node("ReduceMax", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.max(x, (1, 2), keepdims=True), rtol=1e-3) def test_reduce_mean(self): node_def = helper.make_node("ReduceMean", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.mean(x, (1, 2), keepdims=True), rtol=1e-3) def test_reduce_min(self): node_def = helper.make_node("ReduceMin", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.min(x, (1, 2), keepdims=True), rtol=1e-3) def test_reduce_prod(self): node_def = helper.make_node("ReduceProd", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[1, 5, 5, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.prod(x, (1, 2), keepdims=True), rtol=1e-3) def test_reduce_sum(self): node_def = helper.make_node("ReduceSum", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.sum(x, (1, 2), keepdims=True), rtol=1e-3) def test_reduce_sum_square(self): node_def = helper.make_node("ReduceSumSquare", ["X"], ["Y"], axes=[1, 2]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose( output["Y"], np.sum(np.square(x), (1, 2), keepdims=True), rtol=1e-3) def test_pow(self): node_def = helper.make_node("Pow", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=1000) / 2.0 + 0.5 y = self._get_rnd_float32(shape=1000) / 2.0 + 0.5 output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.power(x, y)) def test_reshape(self): x = self._get_rnd_float32(shape=100) shape = [10, 10] if defs.onnx_opset_version() < 5: node_def = helper.make_node("Reshape", ["X"], ["Z"], shape=shape) output = run_node(node_def, [x]) else: node_def = helper.make_node("Reshape", ["X", "Y"], ["Z"]) output = run_node(node_def, [x, shape]) np.testing.assert_almost_equal(output["Z"], x.reshape([10, 10])) def test_reshape_with_copy(self): x = self._get_rnd_float32(shape=[10, 20 * 30]) shape = [0, 20, 30] if defs.onnx_opset_version() < 5: node_def = helper.make_node("Reshape", ["X"], ["Z"], shape=shape) output = run_node(node_def, [x]) else: node_def = helper.make_node("Reshape", ["X", "Y"], ["Z"]) output = run_node(node_def, [x, shape]) np.testing.assert_almost_equal(output["Z"], x.reshape([10, 20, 30])) def test_selu(self): node_def = helper.make_node("Selu", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) alpha = 1.6732 gamma = 1.0507 x[x <= 0] = gamma * (alpha * np.exp(x[x <= 0]) - alpha) x[x > 0] = gamma * x[x > 0] np.testing.assert_allclose(output["Y"], x, rtol=1e-3, atol=1e-7) def test_shape(self): node_def = helper.make_node("Shape", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_allclose(output["Y"], np.shape(x)) def test_shrink(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Shrink.".format( defs.onnx_opset_version())) node_def = helper.make_node("Shrink", ["X"], ["Y"], bias=1.5, lambd=1.5) X = np.arange(-2.0, 2.1, dtype=np.float32) Y = np.array([-0.5, 0, 0, 0, 0.5], dtype=np.float32) output = run_node(node_def, [X]) np.testing.assert_almost_equal(output["Y"], Y) def test_sigmoid(self): node_def = helper.make_node("Sigmoid", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], 1 / (1 + np.exp(-x))) def test_sign(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Sign.".format( defs.onnx_opset_version())) node_def = helper.make_node("Sign", ["X"], ["Y"]) x = self._get_rnd_float32(-10, 10, [3, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.sign(x)) def test_sinh(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Sinh.".format( defs.onnx_opset_version())) node_def = helper.make_node("Sinh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.sinh(x)) def test_size(self): node_def = helper.make_node("Size", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[5, 10, 10, 3]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.size(x)) def test_slice(self): # test case 1 with normal inputs axes = [0, 1, 2] starts = [0, 0, 0] ends = [2, 2, 2] steps = [1, 1, 1] if legacy_opset_pre_ver(10): node_def = helper.make_node( "Slice", ["X"], ["S"], axes=axes, starts=starts, ends=ends) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["S"], x[0:2, 0:2, 0:2]) else: node_def = helper.make_node( "Slice", ["X", "starts", "ends", "axes", "steps"], ["S"]) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x, starts, ends, axes, steps]) np.testing.assert_almost_equal(output["S"], x[0:2, 0:2, 0:2]) # test case 2 with negative, out-of-bound and default inputs axes = [0, 2] starts = [0, -7] ends = [-8, 20] if legacy_opset_pre_ver(10): node_def = helper.make_node( "Slice", ["X"], ["S"], axes=axes, starts=starts, ends=ends) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["S"], x[0:-8, :, -7:20]) else: node_def = helper.make_node( "Slice", ["X", "starts", "ends", "axes"], ["S"]) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x, starts, ends, axes]) np.testing.assert_almost_equal(output["S"], x[0:-8, :, -7:20]) # test case 3 with non-default steps axes = [0, 1, 2] starts = [0, 0, 0] ends = [2, 2, 2] steps = [2, -2, -1] if legacy_opset_pre_ver(10) == False: node_def = helper.make_node( "Slice", ["X", "starts", "ends", "axes", "steps"], ["S"]) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x, starts, ends, axes, steps]) np.testing.assert_almost_equal(output["S"], x[0:2:2, 0:2:-2, 0:2:-1]) def test_softplus(self): node_def = helper.make_node("Softplus", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.log(np.exp(x) + 1)) def test_softsign(self): node_def = helper.make_node("Softsign", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[3, 4, 5]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], x / (1 + np.abs(x))) def test_space_to_depth(self): node_def = helper.make_node("SpaceToDepth", ["X"], ["Y"], blocksize=2) x_shape = [1, 3, 2, 2] x = self._get_rnd_float32(shape=x_shape) output = run_node(node_def, [x]) x = np.transpose(x, (0, 2, 3, 1)) y = np.reshape( np.swapaxes(x.reshape(1, 1, 1, 1, 1, 12), 2, 3), (1, 1, 1, 12)) y = np.transpose(y, (0, 3, 1, 2)) np.testing.assert_allclose(output["Y"], y, rtol=1e-3) def test_split(self): split = [3, 3, 4] node_def = helper.make_node( "Split", ["X"], ["Z%i" % i for i in range(len(split))], axis=0, split=split) x = self._get_rnd_float32(shape=[100]).reshape([10, 10]) output = run_node(node_def, [x]) for a, b in zip(list(output), np.split(x, np.cumsum(split))[:-1]): np.testing.assert_almost_equal(a, b) def test_sqrt(self): node_def = helper.make_node("Sqrt", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) + 1.0 output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.sqrt(x), decimal=5) def test_squeeze(self): node_def = helper.make_node("Squeeze", ["X"], ["Y"], axes=[2]) x = np.array([[[0], [1], [2]]]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.squeeze(x, axis=2)) def test_sub(self): node_def = helper.make_node("Sub", ["X", "Y"], ["Z"]) x = self._get_rnd_float32(shape=[10, 10]) y = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [x, y]) np.testing.assert_almost_equal(output["Z"], np.subtract(x, y)) def test_sum(self): node_def = helper.make_node("Sum", ["X1", "X2", "X3", "X4"], ["Z"]) x1 = self._get_rnd_float32(shape=[10, 10]) x2 = self._get_rnd_float32(shape=[10, 10]) x3 = self._get_rnd_float32(shape=[10, 10]) x4 = self._get_rnd_float32(shape=[10, 10]) output = run_node(node_def, [x1, x2, x3, x4]) test_output = x1 + x2 + x3 + x4 np.testing.assert_almost_equal(output["Z"], test_output) def test_tanh(self): node_def = helper.make_node("Tanh", ["X"], ["Y"]) x = self._get_rnd_float32(shape=[1000]) + 1.0 output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.tanh(x), decimal=5) def test_thresholded_relu(self): alpha = 2.0 node_def = helper.make_node( "ThresholdedRelu", ["X"], ["Y"], alpha=alpha) x = self._get_rnd_float32(-3.0, 3.0, [10]) y = np.clip(x, alpha, np.inf) y[y == alpha] = 0 output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], y) def test_tile(self): if legacy_onnx_pre_ver(1, 2): raise unittest.SkipTest( "The current version of ONNX does not record correctly the opset of Tile." ) node_def = helper.make_node("Tile", ["X1", "X2"], ["Z"]) x = self._get_rnd_float32(shape=[3, 5, 5, 3]) repeats = [1, 1, 2, 1] output = run_node(node_def, [x, repeats]) np.testing.assert_allclose(output["Z"], np.tile(x, repeats), rtol=1e-3) def test_transpose(self): node_def = helper.make_node("Transpose", ["X"], ["Y"], perm=[0, 2, 1]) x = self._get_rnd_float32(shape=[1000]).reshape([10, 10, 10]) output = run_node(node_def, [x]) np.testing.assert_almost_equal(output["Y"], np.transpose(x, (0, 2, 1))) def test_topk(self): x = np.arange(15, dtype=np.float32).reshape(3, 5) values = np.array([[4, 3], [9, 8], [14, 13]], dtype=np.float32) indices = np.array([[4, 3], [4, 3], [4, 3]], dtype=np.int64) if legacy_opset_pre_ver(10): # for opset = 1 node_def = helper.make_node("TopK", ["x"], ["values", "indices"], k=2) output = run_node(node_def, [x]) elif legacy_opset_pre_ver(11): # for opset = 10 k = np.array([2], dtype=np.int64) node_def = helper.make_node("TopK", ["x", "k"], ["values", "indices"]) output = run_node(node_def, [x, k]) else: # for opset = 11 x = np.array([[3, 2, 5, 10, 7], [12, 15, 10, 7, 20], [21, 16, 5, 3, 6]], dtype=np.float32) values = np.array([[3, 2], [10, 7], [5, 3]], dtype=np.float32) indices = np.array([[0, 1], [2, 3], [2, 3]], dtype=np.int64) k = np.array([2], dtype=np.int64) node_def = helper.make_node( "TopK", ["x", "k"], ["values", "indices"], largest=0, sorted=0) output = run_node(node_def, [x, k]) np.testing.assert_almost_equal(output["values"], values) np.testing.assert_almost_equal(output["indices"], indices) def test_where(self): if legacy_opset_pre_ver(9): raise unittest.SkipTest("ONNX version {} doesn't support Where.".format( defs.onnx_opset_version())) node_def = helper.make_node("Where", ["C", "X", "Y"], ["Z"]) c = np.array([[1, 0], [1, 1]], dtype=np.bool) x = np.array([[1, 2], [3, 4]], dtype=np.float32) y = np.array([[9, 8], [7, 6]], dtype=np.float32) output = run_node(node_def, [c, x, y]) np.testing.assert_almost_equal(output["Z"], np.where(c, x, y)) if __name__ == '__main__': unittest.main()
[ "numpy.dot", "numpy.arctanh", "numpy.sqrt", "numpy.minimum", "numpy.squeeze", "numpy.cumsum", "numpy.isneginf", "numpy.round", "numpy.max", "numpy.concatenate", "numpy.mean", "numpy.argmin", "numpy.random.randn", "numpy.negative", "numpy.exp", "numpy.where", "numpy.divide", "numpy.random.randint", "numpy.square", "numpy.testing.assert_equal", "numpy.fmod", "tensorflow.sparse_to_dense", "numpy.clip", "numpy.reshape", "numpy.arange", "numpy.eye", "numpy.matmul", "numpy.subtract", "numpy.testing.assert_almost_equal", "numpy.std", "numpy.ceil", "numpy.size", "numpy.argmax", "numpy.float32", "tensorflow.Session", "numpy.zeros", "numpy.lib.pad", "numpy.log", "numpy.cosh", "numpy.multiply", "numpy.nonzero", "numpy.isnan", "numpy.min", "numpy.arccosh", "numpy.power", "numpy.random.rand", "numpy.floor", "numpy.transpose", "numpy.testing.assert_allclose", "numpy.array", "numpy.arcsinh", "numpy.sum", "numpy.tanh", "numpy.maximum", "numpy.abs", "numpy.int32", "numpy.isposinf", "numpy.compress", "numpy.expm1", "numpy.ones", "numpy.linalg.norm", "numpy.random.uniform", "numpy.sign", "numpy.sinh", "numpy.shape", "numpy.tile", "numpy.prod", "numpy.vectorize", "numpy.mod", "numpy.add", "numpy.isinf" ]
test/backend/test_node.py
[(1237, 'unittest.main', 'unittest.main', ([], {}), False, 'import unittest\n'), (23, 'numpy.random.uniform', 'np.random.uniform', (['low', 'high', 'shape'], {}), True, 'import numpy as np\n'), (30, 'numpy.random.randint', 'np.random.randint', (['low', 'high'], {'size': 'shape', 'dtype': 'dtype'}), True, 'import numpy as np\n'), (47, 'onnx.helper.make_node', 'helper.make_node', (['"""Abs"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (49, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (53, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (56, 'onnx.helper.make_node', 'helper.make_node', (['"""Acosh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (58, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (62, 'onnx.helper.make_node', 'helper.make_node', (['"""Add"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (65, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (104, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (107, 'onnx.helper.make_node', 'helper.make_node', (['"""Asinh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (109, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (113, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (116, 'onnx.helper.make_node', 'helper.make_node', (['"""Atanh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (118, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (129, 'onnx.helper.make_node', 'helper.make_node', (['"""AveragePool"""', "['X']", "['Y']"], {'kernel_shape': '[1, 2]', 'pads': '[1, 1]', 'strides': '[1, 1]'}), False, 'from onnx import helper\n'), (135, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {'device': 'device'}), False, 'from onnx_tf.backend import run_node\n'), (136, 'numpy.zeros', 'np.zeros', (['shape'], {}), True, 'import numpy as np\n'), (147, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (157, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(6)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (159, 'onnx.helper.make_node', 'helper.make_node', (['"""BatchNormalization"""', "['X', 'scale', 'bias', 'mean', 'var']", "['Y']"], {'epsilon': '(0.001)'}), False, 'from onnx import helper\n'), (175, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, scale, bias, m, v]'], {}), False, 'from onnx_tf.backend import run_node\n'), (176, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'golden'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (220, 'onnx.helper.make_node', 'helper.make_node', (['"""Ceil"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (222, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (226, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (231, 'onnx.helper.make_node', 'helper.make_node', (['"""Compress"""'], {'inputs': "['X', 'condition']", 'outputs': "['Y']", 'axis': 'axis'}), False, 'from onnx import helper\n'), (234, 'numpy.array', 'np.array', (['[1, 0, 1]'], {}), True, 'import numpy as np\n'), (235, 'onnx_tf.backend.run_node', 'run_node', (['node_def'], {'inputs': '[x, cond]'}), False, 'from onnx_tf.backend import run_node\n'), (251, 'onnx.helper.make_tensor', 'helper.make_tensor', (['"""const2"""', 'TensorProto.DOUBLE', 'shape', 'values'], {}), False, 'from onnx import helper\n'), (253, 'onnx.helper.make_node', 'helper.make_node', (['"""Constant"""', '[]', "['Y']"], {'value': 'const2_onnx'}), False, 'from onnx import helper\n'), (254, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[]'], {}), False, 'from onnx_tf.backend import run_node\n'), (255, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['Y'].shape", 'shape'], {}), True, 'import numpy as np\n'), (279, 'onnx.helper.make_node', 'helper.make_node', (['"""ConstantFill"""', "['X']", "['Y']"], {'value': 'value', 'extra_shape': 'extra_shape', 'dtype': '(1)'}), False, 'from onnx import helper\n'), (288, 'numpy.zeros', 'np.zeros', (['(shape + extra_shape)'], {}), True, 'import numpy as np\n'), (290, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (291, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['Y'].dtype", 'tf.float32'], {}), True, 'import numpy as np\n'), (292, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['Y']", 'y'], {}), True, 'import numpy as np\n'), (299, 'onnx.helper.make_tensor', 'helper.make_tensor', (['"""value"""', 'TensorProto.FLOAT', '[1]', '[1]'], {}), False, 'from onnx import helper\n'), (300, 'onnx.helper.make_node', 'helper.make_node', (['"""ConstantOfShape"""', "['X']", "['Y']"], {'value': 'v'}), False, 'from onnx import helper\n'), (301, 'numpy.array', 'np.array', (['[4, 3, 2]'], {}), True, 'import numpy as np\n'), (302, 'onnx_tf.backend.run_node', 'run_node', (['node_def'], {'inputs': '[x]'}), False, 'from onnx_tf.backend import run_node\n'), (304, 'onnx.helper.make_tensor', 'helper.make_tensor', (['"""value"""', 'TensorProto.INT32', '[1]', '[0]'], {}), False, 'from onnx import helper\n'), (305, 'onnx.helper.make_node', 'helper.make_node', (['"""ConstantOfShape"""', "['X']", "['Y']"], {'value': 'v'}), False, 'from onnx import helper\n'), (306, 'numpy.array', 'np.array', (['[10, 6]'], {}), True, 'import numpy as np\n'), (307, 'onnx_tf.backend.run_node', 'run_node', (['node_def'], {'inputs': '[x]'}), False, 'from onnx_tf.backend import run_node\n'), (320, 'onnx.helper.make_node', 'helper.make_node', (['"""Conv"""', "['X', 'weights']", "['Y']"], {'pads': '[1, 1, 1, 1]', 'kernel_shape': '[kH, kW]'}), False, 'from onnx import helper\n'), (327, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, weights]'], {'device': 'device'}), False, 'from onnx_tf.backend import run_node\n'), (330, 'numpy.zeros', 'np.zeros', (['out_shape'], {}), True, 'import numpy as np\n'), (346, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (355, 'onnx.helper.make_node', 'helper.make_node', (['"""ConvTranspose"""', "['X', 'weights']", "['Y']"], {'pads': '[1, 1]'}), False, 'from onnx import helper\n'), (361, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, weights]'], {'device': 'device'}), False, 'from onnx_tf.backend import run_node\n'), (363, 'numpy.zeros', 'np.zeros', (['out_shape'], {}), True, 'import numpy as np\n'), (372, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (375, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (378, 'onnx.helper.make_node', 'helper.make_node', (['"""Cosh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (380, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (384, 'onnx.helper.make_node', 'helper.make_node', (['"""DepthToSpace"""', "['X']", "['Y']"], {'blocksize': '(2)'}), False, 'from onnx import helper\n'), (387, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (388, 'numpy.transpose', 'np.transpose', (['x', '(0, 2, 3, 1)'], {}), True, 'import numpy as np\n'), (390, 'numpy.transpose', 'np.transpose', (['y', '(0, 3, 1, 2)'], {}), True, 'import numpy as np\n'), (391, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'y'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (394, 'onnx.helper.make_node', 'helper.make_node', (['"""DequantizeLinear"""', "['x', 'x_scale', 'x_zero_point']", "['y']"], {}), False, 'from onnx import helper\n'), (417, 'onnx.helper.make_node', 'helper.make_node', (['"""Div"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (420, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (428, 'onnx.helper.make_node', 'helper.make_node', (['"""Dropout"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (429, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(7)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (434, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (435, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['Y']", 'y'], {}), True, 'import numpy as np\n'), (441, 'onnx.helper.make_node', 'helper.make_node', (['"""Dot"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (444, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (448, 'onnx.helper.make_node', 'helper.make_node', (['"""Elu"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (450, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (452, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (455, 'onnx.helper.make_node', 'helper.make_node', (['"""Equal"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (458, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (463, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (466, 'onnx.helper.make_node', 'helper.make_node', (['"""Erf"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (468, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (470, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'exp_output'], {}), True, 'import numpy as np\n'), (473, 'onnx.helper.make_node', 'helper.make_node', (['"""Exp"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (476, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (480, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (500, 'onnx.helper.make_node', 'helper.make_node', (['"""Flatten"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (502, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (508, 'onnx.helper.make_node', 'helper.make_node', (['"""Gather"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (511, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (512, 'numpy.zeros', 'np.zeros', (['(2, 2, 10)'], {}), True, 'import numpy as np\n'), (519, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Z']", 'test_output'], {}), True, 'import numpy as np\n'), (523, 'onnx.helper.make_node', 'helper.make_node', (['"""Gemm"""', "['A', 'B', 'C']", "['Y']"], {'transA': '(0)', 'transB': '(0)', 'alpha': '(1.0)', 'beta': '(1.0)'}), False, 'from onnx import helper\n'), (528, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y, z]'], {}), False, 'from onnx_tf.backend import run_node\n'), (530, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (541, 'onnx.helper.make_node', 'helper.make_node', (['"""GlobalAveragePool"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (543, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (544, 'numpy.zeros', 'np.zeros', (['[10, 10, 1, 1]'], {}), True, 'import numpy as np\n'), (552, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (564, 'numpy.random.rand', 'np.random.rand', (['(3)'], {}), True, 'import numpy as np\n'), (565, 'onnx.helper.make_node', 'helper.make_node', (['"""ImageScaler"""', "['X']", "['Y']"], {'scale': 'scale', 'bias': 'bias'}), False, 'from onnx import helper\n'), (567, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (568, 'numpy.multiply', 'np.multiply', (['x', 'scale'], {}), True, 'import numpy as np\n'), (569, 'numpy.transpose', 'np.transpose', (['test_out', '[0, 2, 3, 1]'], {}), True, 'import numpy as np\n'), (570, 'numpy.add', 'np.add', (['test_out', 'bias'], {}), True, 'import numpy as np\n'), (571, 'numpy.transpose', 'np.transpose', (['test_out', '[0, 3, 1, 2]'], {}), True, 'import numpy as np\n'), (572, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_out'], {}), True, 'import numpy as np\n'), (575, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (578, 'numpy.array', 'np.array', (['[-1.2, np.nan, np.inf, 2.8, np.NINF, np.inf]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (598, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (601, 'onnx.helper.make_node', 'helper.make_node', (['"""IsNaN"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (604, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (616, 'onnx.helper.make_node', 'helper.make_node', (['"""GlobalLpPool"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (618, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (619, 'numpy.zeros', 'np.zeros', (['[10, 10, 1, 1]'], {}), True, 'import numpy as np\n'), (627, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (638, 'onnx.helper.make_node', 'helper.make_node', (['"""GlobalMaxPool"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (640, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (641, 'numpy.zeros', 'np.zeros', (['[10, 10, 1, 1]'], {}), True, 'import numpy as np\n'), (650, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (653, 'onnx.helper.make_node', 'helper.make_node', (['"""Less"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (656, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (678, 'onnx.helper.make_node', 'helper.make_node', (['"""LRN"""', "['X']", "['Y']"], {'alpha': 'alpha', 'beta': 'beta', 'bias': 'bias', 'size': 'size'}), False, 'from onnx import helper\n'), (681, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (682, 'numpy.zeros', 'np.zeros', (['[10, 10, 10, 2]'], {}), True, 'import numpy as np\n'), (683, 'numpy.transpose', 'np.transpose', (['x'], {'axes': '[0, 2, 3, 1]'}), True, 'import numpy as np\n'), (701, 'numpy.transpose', 'np.transpose', (['test_output'], {'axes': '[0, 3, 1, 2]'}), True, 'import numpy as np\n'), (702, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (705, 'onnx.helper.make_node', 'helper.make_node', (['"""Floor"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (707, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (711, 'onnx.helper.make_node', 'helper.make_node', (['"""LeakyRelu"""', "['X']", "['Y']"], {'alpha': '(0.8)'}), False, 'from onnx import helper\n'), (713, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (715, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (718, 'onnx.helper.make_node', 'helper.make_node', (['"""Log"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (721, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (725, 'onnx.helper.make_node', 'helper.make_node', (['"""Max"""', "['X1', 'X2', 'X3', 'X4']", "['Z']"], {}), False, 'from onnx import helper\n'), (730, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x1, x2, x3, x4]'], {}), False, 'from onnx_tf.backend import run_node\n'), (732, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Z']", 'test_output'], {}), True, 'import numpy as np\n'), (736, 'onnx.helper.make_node', 'helper.make_node', (['"""MaxPool"""', "['X']", "['Y']"], {'dilations': '[1, 1]', 'kernel_shape': '[1, 2]', 'pads': '[0, 0]', 'strides': '[1, 2]'}), False, 'from onnx import helper\n'), (743, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (744, 'numpy.zeros', 'np.zeros', (['[10, 10, 4, 2]'], {}), True, 'import numpy as np\n'), (751, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'test_output'], {}), True, 'import numpy as np\n'), (754, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (762, 'numpy.mean', 'np.mean', (['input_data'], {'keepdims': '(1)', 'axis': '(0, 2, 3)'}), True, 'import numpy as np\n'), (763, 'numpy.std', 'np.std', (['input_data'], {'keepdims': '(1)', 'axis': '(0, 2, 3)'}), True, 'import numpy as np\n'), (766, 'onnx.helper.make_node', 'helper.make_node', (['"""MeanVarianceNormalization"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (767, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[input_data]'], {}), False, 'from onnx_tf.backend import run_node\n'), (768, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'expected_output'], {'decimal': '(5)'}), True, 'import numpy as np\n'), (771, 'onnx.helper.make_node', 'helper.make_node', (['"""Min"""', "['X1', 'X2', 'X3', 'X4']", "['Z']"], {}), False, 'from onnx import helper\n'), (776, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x1, x2, x3, x4]'], {}), False, 'from onnx_tf.backend import run_node\n'), (778, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Z']", 'test_output'], {}), True, 'import numpy as np\n'), (781, 'onnx.helper.make_node', 'helper.make_node', (['"""Mul"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (784, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (789, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (794, 'onnx.helper.make_node', 'helper.make_node', (['"""Mod"""', "['X', 'Y']", "['Z']"], {'fmod': '(0)'}), False, 'from onnx import helper\n'), (795, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (797, 'onnx.helper.make_node', 'helper.make_node', (['"""Mod"""', "['X', 'Y']", "['Z']"], {'fmod': '(1)'}), False, 'from onnx import helper\n'), (798, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (802, 'onnx.helper.make_node', 'helper.make_node', (['"""Neg"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (804, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (808, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (811, 'onnx.helper.make_node', 'helper.make_node', (['"""NonZero"""', "['x']", "['y']"], {}), False, 'from onnx import helper\n'), (814, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (815, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['y']", 'y'], {}), True, 'import numpy as np\n'), (818, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (821, 'numpy.array', 'np.array', (['[[0, 2], [1, 2], [0, 1]]'], {}), True, 'import numpy as np\n'), (822, 'numpy.int32', 'np.int32', (['(5)'], {}), True, 'import numpy as np\n'), (825, 'numpy.array', 'np.array', (['[off_value, on_value]'], {}), True, 'import numpy as np\n'), (826, 'onnx.helper.make_node', 'helper.make_node', (['"""OneHot"""'], {'inputs': "['indices', 'depth', 'values']", 'outputs': "['y']", 'axis': '(-1)'}), False, 'from onnx import helper\n'), (830, 'onnx_tf.backend.run_node', 'run_node', (['node_def'], {'inputs': '[indices, depth, values]'}), False, 'from onnx_tf.backend import run_node\n'), (831, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['y']", 'y'], {}), True, 'import numpy as np\n'), (834, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(11)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (837, 'onnx.helper.make_node', 'helper.make_node', (['"""Range"""', "['start', 'limit', 'delta']", "['y']"], {}), False, 'from onnx import helper\n'), (842, 'numpy.int32', 'np.int32', (['(3)'], {}), True, 'import numpy as np\n'), (843, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[start, limit, delta]'], {}), False, 'from onnx_tf.backend import run_node\n'), (848, 'numpy.int32', 'np.int32', (['(-2)'], {}), True, 'import numpy as np\n'), (849, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[start, limit, delta]'], {}), False, 'from onnx_tf.backend import run_node\n'), (853, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(11)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (856, 'onnx.helper.make_node', 'helper.make_node', (['"""Round"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (858, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (862, 'onnx.helper.make_node', 'helper.make_node', (['"""Relu"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (864, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (868, 'onnx.helper.make_node', 'helper.make_node', (['"""Pad"""', "['X']", "['Y']"], {'mode': '"""constant"""', 'pads': '[1, 1, 1, 1]', 'value': '(2.0)'}), False, 'from onnx import helper\n'), (871, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (879, 'onnx.helper.make_node', 'helper.make_node', (['"""QuantizeLinear"""', "['x', 'y_scale', 'y_zero_point']", "['y']"], {}), False, 'from onnx import helper\n'), (901, 'onnx.helper.make_node', 'helper.make_node', (['"""Reciprocal"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (903, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (904, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", '(1.0 / x)'], {}), True, 'import numpy as np\n'), (907, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceL1"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (909, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (914, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceLogSumExp"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (916, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (923, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceMax"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (925, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (930, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceMean"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (932, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (937, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceMin"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (939, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (944, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceProd"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (946, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (951, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceSum"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (953, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (958, 'onnx.helper.make_node', 'helper.make_node', (['"""ReduceSumSquare"""', "['X']", "['Y']"], {'axes': '[1, 2]'}), False, 'from onnx import helper\n'), (960, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (965, 'onnx.helper.make_node', 'helper.make_node', (['"""Pow"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (968, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (996, 'onnx.helper.make_node', 'helper.make_node', (['"""Selu"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (998, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1003, 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (["output['Y']", 'x'], {'rtol': '(0.001)', 'atol': '(1e-07)'}), True, 'import numpy as np\n'), (1006, 'onnx.helper.make_node', 'helper.make_node', (['"""Shape"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1008, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1012, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1016, 'onnx.helper.make_node', 'helper.make_node', (['"""Shrink"""', "['X']", "['Y']"], {'bias': '(1.5)', 'lambd': '(1.5)'}), False, 'from onnx import helper\n'), (1018, 'numpy.arange', 'np.arange', (['(-2.0)', '(2.1)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1019, 'numpy.array', 'np.array', (['[-0.5, 0, 0, 0, 0.5]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1020, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[X]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1021, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'Y'], {}), True, 'import numpy as np\n'), (1024, 'onnx.helper.make_node', 'helper.make_node', (['"""Sigmoid"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1026, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1030, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1033, 'onnx.helper.make_node', 'helper.make_node', (['"""Sign"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1035, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1039, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1042, 'onnx.helper.make_node', 'helper.make_node', (['"""Sinh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1044, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1048, 'onnx.helper.make_node', 'helper.make_node', (['"""Size"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1050, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1060, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1078, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1105, 'onnx.helper.make_node', 'helper.make_node', (['"""Softplus"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1107, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1111, 'onnx.helper.make_node', 'helper.make_node', (['"""Softsign"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1113, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1117, 'onnx.helper.make_node', 'helper.make_node', (['"""SpaceToDepth"""', "['X']", "['Y']"], {'blocksize': '(2)'}), False, 'from onnx import helper\n'), (1120, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1121, 'numpy.transpose', 'np.transpose', (['x', '(0, 2, 3, 1)'], {}), True, 'import numpy as np\n'), (1124, 'numpy.transpose', 'np.transpose', (['y', '(0, 3, 1, 2)'], {}), True, 'import numpy as np\n'), (1125, 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (["output['Y']", 'y'], {'rtol': '(0.001)'}), True, 'import numpy as np\n'), (1135, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1140, 'onnx.helper.make_node', 'helper.make_node', (['"""Sqrt"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1142, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1146, 'onnx.helper.make_node', 'helper.make_node', (['"""Squeeze"""', "['X']", "['Y']"], {'axes': '[2]'}), False, 'from onnx import helper\n'), (1147, 'numpy.array', 'np.array', (['[[[0], [1], [2]]]'], {}), True, 'import numpy as np\n'), (1148, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1152, 'onnx.helper.make_node', 'helper.make_node', (['"""Sub"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (1155, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1159, 'onnx.helper.make_node', 'helper.make_node', (['"""Sum"""', "['X1', 'X2', 'X3', 'X4']", "['Z']"], {}), False, 'from onnx import helper\n'), (1164, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x1, x2, x3, x4]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1166, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Z']", 'test_output'], {}), True, 'import numpy as np\n'), (1169, 'onnx.helper.make_node', 'helper.make_node', (['"""Tanh"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (1171, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1176, 'onnx.helper.make_node', 'helper.make_node', (['"""ThresholdedRelu"""', "['X']", "['Y']"], {'alpha': 'alpha'}), False, 'from onnx import helper\n'), (1179, 'numpy.clip', 'np.clip', (['x', 'alpha', 'np.inf'], {}), True, 'import numpy as np\n'), (1181, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1182, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['Y']", 'y'], {}), True, 'import numpy as np\n'), (1185, 'onnx_tf.common.legacy.legacy_onnx_pre_ver', 'legacy_onnx_pre_ver', (['(1)', '(2)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1189, 'onnx.helper.make_node', 'helper.make_node', (['"""Tile"""', "['X1', 'X2']", "['Z']"], {}), False, 'from onnx import helper\n'), (1192, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, repeats]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1196, 'onnx.helper.make_node', 'helper.make_node', (['"""Transpose"""', "['X']", "['Y']"], {'perm': '[0, 2, 1]'}), False, 'from onnx import helper\n'), (1198, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1203, 'numpy.array', 'np.array', (['[[4, 3], [9, 8], [14, 13]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1204, 'numpy.array', 'np.array', (['[[4, 3], [4, 3], [4, 3]]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (1205, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1221, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['values']", 'values'], {}), True, 'import numpy as np\n'), (1222, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['indices']", 'indices'], {}), True, 'import numpy as np\n'), (1225, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1228, 'onnx.helper.make_node', 'helper.make_node', (['"""Where"""', "['C', 'X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (1229, 'numpy.array', 'np.array', (['[[1, 0], [1, 1]]'], {'dtype': 'np.bool'}), True, 'import numpy as np\n'), (1230, 'numpy.array', 'np.array', (['[[1, 2], [3, 4]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1231, 'numpy.array', 'np.array', (['[[9, 8], [7, 6]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1232, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[c, x, y]'], {}), False, 'from onnx_tf.backend import run_node\n'), (25, 'numpy.float32', 'np.float32', (['output'], {}), True, 'import numpy as np\n'), (36, 'numpy.expm1', 'np.expm1', (['x'], {}), True, 'import numpy as np\n'), (50, 'numpy.abs', 'np.abs', (['x'], {}), True, 'import numpy as np\n'), (59, 'numpy.arccosh', 'np.arccosh', (['x'], {}), True, 'import numpy as np\n'), (85, 'onnx.helper.make_node', 'helper.make_node', (['"""ArgMax"""', "['data']", "['reduced']"], {'axis': 'axis', 'keepdims': '(0)'}), False, 'from onnx import helper\n'), (88, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[data]'], {}), False, 'from onnx_tf.backend import run_node\n'), (96, 'onnx.helper.make_node', 'helper.make_node', (['"""ArgMin"""', "['data']", "['reduced']"], {'axis': 'axis', 'keepdims': '(0)'}), False, 'from onnx import helper\n'), (99, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[data]'], {}), False, 'from onnx_tf.backend import run_node\n'), (110, 'numpy.arcsinh', 'np.arcsinh', (['x'], {}), True, 'import numpy as np\n'), (119, 'numpy.arctanh', 'np.arctanh', (['x'], {}), True, 'import numpy as np\n'), (125, 'onnx_tf.common.supports_device', 'supports_device', (['device'], {}), False, 'from onnx_tf.common import supports_device\n'), (151, 'numpy.sqrt', 'np.sqrt', (['(variance + variance_epsilon)'], {}), True, 'import numpy as np\n'), (158, 'unittest.SkipTest', 'unittest.SkipTest', (['"""Backend doesn\'t support consumed flag"""'], {}), False, 'import unittest\n'), (179, 'onnx_tf.common.legacy.legacy_onnx_pre_ver', 'legacy_onnx_pre_ver', (['(1)', '(2)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (179, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(6)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (203, 'onnx.helper.make_node', 'helper.make_node', (['"""Cast"""', "['input']", "['output']"], {'to': 'ty'}), False, 'from onnx import helper\n'), (205, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[vector]'], {}), False, 'from onnx_tf.backend import run_node\n'), (206, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['output'].dtype", 'tf_type'], {}), True, 'import numpy as np\n'), (208, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (223, 'numpy.ceil', 'np.ceil', (['x'], {}), True, 'import numpy as np\n'), (236, 'numpy.compress', 'np.compress', (['cond', 'x'], {'axis': 'axis'}), True, 'import numpy as np\n'), (241, 'onnx.helper.make_node', 'helper.make_node', (['"""Concat"""', "['X1', 'X2']", "['Y']"], {'axis': 'axis'}), False, 'from onnx import helper\n'), (244, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x1, x2]'], {}), False, 'from onnx_tf.backend import run_node\n'), (259, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(11)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (260, 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 0]]'], {}), True, 'import numpy as np\n'), (262, 'onnx.helper.make_tensor', 'helper.make_tensor', (['"""values"""', 'TensorProto.INT32', '[2]', '[1, 2]'], {}), False, 'from onnx import helper\n'), (263, 'onnx.helper.make_tensor', 'helper.make_tensor', (['"""indices"""', 'TensorProto.INT64', '[2, 2]', 'x'], {}), False, 'from onnx import helper\n'), (264, 'onnx.helper.make_sparse_tensor', 'helper.make_sparse_tensor', (['values', 'indices', '[3, 4]'], {}), False, 'from onnx import helper\n'), (265, 'onnx.helper.make_node', 'helper.make_node', (['"""Constant"""', '[]', "['Y']"], {'sparse_value': 'a'}), False, 'from onnx import helper\n'), (266, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[]'], {}), False, 'from onnx_tf.backend import run_node\n'), (267, 'tensorflow.sparse_to_dense', 'tf.sparse_to_dense', (["output['Y'].indices", "output['Y'].dense_shape", "output['Y'].values"], {}), True, 'import tensorflow as tf\n'), (269, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['result', 'expected'], {}), True, 'import numpy as np\n'), (272, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (295, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (303, 'numpy.ones', 'np.ones', (['x'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (308, 'numpy.zeros', 'np.zeros', (['x'], {'dtype': 'np.int32'}), True, 'import numpy as np\n'), (312, 'onnx_tf.common.supports_device', 'supports_device', (['device'], {}), False, 'from onnx_tf.common import supports_device\n'), (352, 'onnx_tf.common.supports_device', 'supports_device', (['device'], {}), False, 'from onnx_tf.common import supports_device\n'), (381, 'numpy.cosh', 'np.cosh', (['x'], {}), True, 'import numpy as np\n'), (412, 'numpy.multiply', 'np.multiply', (['y', 'x_scale'], {}), True, 'import numpy as np\n'), (413, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, x_scale, x_zero_point]'], {}), False, 'from onnx_tf.backend import run_node\n'), (414, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['y']", 'y'], {}), True, 'import numpy as np\n'), (421, 'numpy.divide', 'np.divide', (['x', 'y'], {}), True, 'import numpy as np\n'), (431, 'onnx.helper.make_node', 'helper.make_node', (['"""Dropout"""', "['X']", "['Y']"], {'is_test': '(1)'}), False, 'from onnx import helper\n'), (445, 'numpy.dot', 'np.dot', (['x', 'y'], {}), True, 'import numpy as np\n'), (477, 'numpy.exp', 'np.exp', (['x'], {}), True, 'import numpy as np\n'), (529, 'numpy.matmul', 'np.matmul', (['x', 'y'], {}), True, 'import numpy as np\n'), (581, 'numpy.isinf', 'np.isinf', (['input'], {}), True, 'import numpy as np\n'), (582, 'numpy.isposinf', 'np.isposinf', (['input'], {}), True, 'import numpy as np\n'), (583, 'numpy.isneginf', 'np.isneginf', (['input'], {}), True, 'import numpy as np\n'), (587, 'onnx.helper.make_node', 'helper.make_node', (['"""IsInf"""', "['X']", "['Y']"], {}), False, 'from onnx import helper\n'), (589, 'onnx.helper.make_node', 'helper.make_node', (['"""IsInf"""', "['X']", "['Y']"], {'detect_negative': '(0)'}), False, 'from onnx import helper\n'), (591, 'onnx.helper.make_node', 'helper.make_node', (['"""IsInf"""', "['X']", "['Y']"], {'detect_positive': '(0)'}), False, 'from onnx import helper\n'), (594, 'onnx_tf.backend.run_node', 'run_node', (['node_defs[key]', '[input]'], {}), False, 'from onnx_tf.backend import run_node\n'), (595, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['Y']", 'expected_output[key]'], {}), True, 'import numpy as np\n'), (605, 'numpy.isnan', 'np.isnan', (['x'], {}), True, 'import numpy as np\n'), (662, 'onnx.helper.make_node', 'helper.make_node', (['"""LpNormalization"""', "['X']", "['Y']"], {'p': 'ordr'}), False, 'from onnx import helper\n'), (664, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (708, 'numpy.floor', 'np.floor', (['x'], {}), True, 'import numpy as np\n'), (722, 'numpy.log', 'np.log', (['x'], {}), True, 'import numpy as np\n'), (796, 'numpy.mod', 'np.mod', (['x', 'y'], {}), True, 'import numpy as np\n'), (799, 'numpy.fmod', 'np.fmod', (['x', 'y'], {}), True, 'import numpy as np\n'), (805, 'numpy.negative', 'np.negative', (['x'], {}), True, 'import numpy as np\n'), (813, 'numpy.nonzero', 'np.nonzero', (['x'], {}), True, 'import numpy as np\n'), (859, 'numpy.round', 'np.round', (['x'], {}), True, 'import numpy as np\n'), (865, 'numpy.maximum', 'np.maximum', (['x', '(0)'], {}), True, 'import numpy as np\n'), (873, 'numpy.lib.pad', 'np.lib.pad', (['x', '((1, 1), (1, 1))', '"""constant"""'], {'constant_values': '(2, 2)'}), True, 'import numpy as np\n'), (911, 'numpy.linalg.norm', 'np.linalg.norm', (['x', '(1)', '(1, 2)', '(True)'], {}), True, 'import numpy as np\n'), (927, 'numpy.max', 'np.max', (['x', '(1, 2)'], {'keepdims': '(True)'}), True, 'import numpy as np\n'), (934, 'numpy.mean', 'np.mean', (['x', '(1, 2)'], {'keepdims': '(True)'}), True, 'import numpy as np\n'), (941, 'numpy.min', 'np.min', (['x', '(1, 2)'], {'keepdims': '(True)'}), True, 'import numpy as np\n'), (948, 'numpy.prod', 'np.prod', (['x', '(1, 2)'], {'keepdims': '(True)'}), True, 'import numpy as np\n'), (955, 'numpy.sum', 'np.sum', (['x', '(1, 2)'], {'keepdims': '(True)'}), True, 'import numpy as np\n'), (969, 'numpy.power', 'np.power', (['x', 'y'], {}), True, 'import numpy as np\n'), (974, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (975, 'onnx.helper.make_node', 'helper.make_node', (['"""Reshape"""', "['X']", "['Z']"], {'shape': 'shape'}), False, 'from onnx import helper\n'), (976, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (978, 'onnx.helper.make_node', 'helper.make_node', (['"""Reshape"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (979, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, shape]'], {}), False, 'from onnx_tf.backend import run_node\n'), (986, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (987, 'onnx.helper.make_node', 'helper.make_node', (['"""Reshape"""', "['X']", "['Z']"], {'shape': 'shape'}), False, 'from onnx import helper\n'), (988, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (990, 'onnx.helper.make_node', 'helper.make_node', (['"""Reshape"""', "['X', 'Y']", "['Z']"], {}), False, 'from onnx import helper\n'), (991, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, shape]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1009, 'numpy.shape', 'np.shape', (['x'], {}), True, 'import numpy as np\n'), (1036, 'numpy.sign', 'np.sign', (['x'], {}), True, 'import numpy as np\n'), (1045, 'numpy.sinh', 'np.sinh', (['x'], {}), True, 'import numpy as np\n'), (1051, 'numpy.size', 'np.size', (['x'], {}), True, 'import numpy as np\n'), (1061, 'onnx.helper.make_node', 'helper.make_node', (['"""Slice"""', "['X']", "['S']"], {'axes': 'axes', 'starts': 'starts', 'ends': 'ends'}), False, 'from onnx import helper\n'), (1064, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1065, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['S']", 'x[0:2, 0:2, 0:2]'], {}), True, 'import numpy as np\n'), (1067, 'onnx.helper.make_node', 'helper.make_node', (['"""Slice"""', "['X', 'starts', 'ends', 'axes', 'steps']", "['S']"], {}), False, 'from onnx import helper\n'), (1070, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, starts, ends, axes, steps]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1071, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['S']", 'x[0:2, 0:2, 0:2]'], {}), True, 'import numpy as np\n'), (1079, 'onnx.helper.make_node', 'helper.make_node', (['"""Slice"""', "['X']", "['S']"], {'axes': 'axes', 'starts': 'starts', 'ends': 'ends'}), False, 'from onnx import helper\n'), (1082, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1083, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['S']", 'x[0:-8, :, -7:20]'], {}), True, 'import numpy as np\n'), (1085, 'onnx.helper.make_node', 'helper.make_node', (['"""Slice"""', "['X', 'starts', 'ends', 'axes']", "['S']"], {}), False, 'from onnx import helper\n'), (1088, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, starts, ends, axes]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1089, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['S']", 'x[0:-8, :, -7:20]'], {}), True, 'import numpy as np\n'), (1097, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(10)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1098, 'onnx.helper.make_node', 'helper.make_node', (['"""Slice"""', "['X', 'starts', 'ends', 'axes', 'steps']", "['S']"], {}), False, 'from onnx import helper\n'), (1101, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, starts, ends, axes, steps]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1102, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['S']", 'x[0:2:2, 0:2:-2, 0:2:-1]'], {}), True, 'import numpy as np\n'), (1137, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['a', 'b'], {}), True, 'import numpy as np\n'), (1143, 'numpy.sqrt', 'np.sqrt', (['x'], {}), True, 'import numpy as np\n'), (1149, 'numpy.squeeze', 'np.squeeze', (['x'], {'axis': '(2)'}), True, 'import numpy as np\n'), (1156, 'numpy.subtract', 'np.subtract', (['x', 'y'], {}), True, 'import numpy as np\n'), (1172, 'numpy.tanh', 'np.tanh', (['x'], {}), True, 'import numpy as np\n'), (1186, 'unittest.SkipTest', 'unittest.SkipTest', (['"""The current version of ONNX does not record correctly the opset of Tile."""'], {}), False, 'import unittest\n'), (1193, 'numpy.tile', 'np.tile', (['x', 'repeats'], {}), True, 'import numpy as np\n'), (1199, 'numpy.transpose', 'np.transpose', (['x', '(0, 2, 1)'], {}), True, 'import numpy as np\n'), (1206, 'onnx.helper.make_node', 'helper.make_node', (['"""TopK"""', "['x']", "['values', 'indices']"], {'k': '(2)'}), False, 'from onnx import helper\n'), (1207, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1208, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(11)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (1233, 'numpy.where', 'np.where', (['c', 'x', 'y'], {}), True, 'import numpy as np\n'), (90, 'numpy.argmax', 'np.argmax', (['data'], {'axis': 'axis'}), True, 'import numpy as np\n'), (101, 'numpy.argmin', 'np.argmin', (['data'], {'axis': 'axis'}), True, 'import numpy as np\n'), (200, 'onnx_tf.common.legacy.legacy_opset_pre_ver', 'legacy_opset_pre_ver', (['(9)'], {}), False, 'from onnx_tf.common.legacy import legacy_onnx_pre_ver, legacy_opset_pre_ver\n'), (214, 'onnx.helper.make_node', 'helper.make_node', (['"""Cast"""', "['input']", "['output']"], {'to': 'ty'}), False, 'from onnx import helper\n'), (216, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[vector]'], {}), False, 'from onnx_tf.backend import run_node\n'), (217, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['output'].dtype", 'tf_type'], {}), True, 'import numpy as np\n'), (245, 'numpy.concatenate', 'np.concatenate', (['(x1, x2)', 'axis'], {}), True, 'import numpy as np\n'), (407, 'numpy.int32', 'np.int32', (['(0)'], {}), True, 'import numpy as np\n'), (411, 'numpy.float32', 'np.float32', (['x'], {}), True, 'import numpy as np\n'), (411, 'numpy.float32', 'np.float32', (['x_zero_point'], {}), True, 'import numpy as np\n'), (459, 'numpy.reshape', 'np.reshape', (['y', '[1, 3, 3, 1]'], {}), True, 'import numpy as np\n'), (485, 'onnx.helper.make_node', 'helper.make_node', (['"""EyeLike"""', "['x']", "['y']"], {'dtype': '(1)', 'k': 'off_diagonal_offset'}), False, 'from onnx import helper\n'), (488, 'numpy.eye', 'np.eye', (['shape[0]', 'shape[1]'], {'k': 'off_diagonal_offset', 'dtype': 'np.float32'}), True, 'import numpy as np\n'), (489, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x]'], {}), False, 'from onnx_tf.backend import run_node\n'), (490, 'numpy.testing.assert_equal', 'np.testing.assert_equal', (["output['y']", 'y'], {}), True, 'import numpy as np\n'), (563, 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), True, 'import numpy as np\n'), (622, 'numpy.zeros', 'np.zeros', (['[2, 3]'], {}), True, 'import numpy as np\n'), (626, 'numpy.linalg.norm', 'np.linalg.norm', (['tmp'], {}), True, 'import numpy as np\n'), (657, 'numpy.reshape', 'np.reshape', (['y', '[1, 3, 3, 1]'], {}), True, 'import numpy as np\n'), (731, 'numpy.maximum', 'np.maximum', (['x1', 'x2'], {}), True, 'import numpy as np\n'), (777, 'numpy.minimum', 'np.minimum', (['x1', 'x2'], {}), True, 'import numpy as np\n'), (890, 'numpy.divide', 'np.divide', (['x', 'y_scale'], {}), True, 'import numpy as np\n'), (891, 'numpy.round', 'np.round', (['y'], {}), True, 'import numpy as np\n'), (892, 'numpy.add', 'np.add', (['y', 'y_zero_point'], {}), True, 'import numpy as np\n'), (897, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, y_scale, y_zero_point]'], {}), False, 'from onnx_tf.backend import run_node\n'), (898, 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["output['y']", 'y'], {}), True, 'import numpy as np\n'), (962, 'numpy.square', 'np.square', (['x'], {}), True, 'import numpy as np\n'), (1202, 'numpy.arange', 'np.arange', (['(15)'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1209, 'numpy.array', 'np.array', (['[2]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (1210, 'onnx.helper.make_node', 'helper.make_node', (['"""TopK"""', "['x', 'k']", "['values', 'indices']"], {}), False, 'from onnx import helper\n'), (1211, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, k]'], {}), False, 'from onnx_tf.backend import run_node\n'), (1213, 'numpy.array', 'np.array', (['[[3, 2, 5, 10, 7], [12, 15, 10, 7, 20], [21, 16, 5, 3, 6]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1215, 'numpy.array', 'np.array', (['[[3, 2], [10, 7], [5, 3]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (1216, 'numpy.array', 'np.array', (['[[0, 1], [2, 3], [2, 3]]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (1217, 'numpy.array', 'np.array', (['[2]'], {'dtype': 'np.int64'}), True, 'import numpy as np\n'), (1218, 'onnx.helper.make_node', 'helper.make_node', (['"""TopK"""', "['x', 'k']", "['values', 'indices']"], {'largest': '(0)', 'sorted': '(0)'}), False, 'from onnx import helper\n'), (1220, 'onnx_tf.backend.run_node', 'run_node', (['node_def', '[x, k]'], {}), False, 'from onnx_tf.backend import run_node\n'), (55, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (106, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (115, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (229, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (268, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (275, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (298, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (377, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (465, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (469, 'numpy.vectorize', 'np.vectorize', (['math.erf'], {}), True, 'import numpy as np\n'), (482, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (577, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (600, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (757, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (791, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (810, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (820, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (828, 'numpy.arange', 'np.arange', (['depth'], {}), True, 'import numpy as np\n'), (836, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (855, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (919, 'numpy.exp', 'np.exp', (['x'], {}), True, 'import numpy as np\n'), (1001, 'numpy.exp', 'np.exp', (['x[x <= 0]'], {}), True, 'import numpy as np\n'), (1014, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (1027, 'numpy.exp', 'np.exp', (['(-x)'], {}), True, 'import numpy as np\n'), (1032, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (1041, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (1108, 'numpy.exp', 'np.exp', (['x'], {}), True, 'import numpy as np\n'), (1114, 'numpy.abs', 'np.abs', (['x'], {}), True, 'import numpy as np\n'), (1136, 'numpy.cumsum', 'np.cumsum', (['split'], {}), True, 'import numpy as np\n'), (1227, 'onnx.defs.onnx_opset_version', 'defs.onnx_opset_version', ([], {}), False, 'from onnx import defs\n'), (250, 'numpy.random.randn', 'np.random.randn', (['*shape'], {}), True, 'import numpy as np\n'), (667, 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {'axis': '(-1)', 'ord': 'ordr'}), True, 'import numpy as np\n'), (261, 'numpy.array', 'np.array', (['[[0, 0], [1, 2]]'], {}), True, 'import numpy as np\n'), (894, 'numpy.clip', 'np.clip', (['y', '(-128)', '(127)'], {}), True, 'import numpy as np\n'), (896, 'numpy.clip', 'np.clip', (['y', '(0)', '(255)'], {}), True, 'import numpy as np\n')]
sereini/SpeechSeparationModel
ea44c845762112f3bc2e5e54c5530e6fd429464f
""" Exports the embeddings of a directory of images as numpy arrays. Following structure: D:\images: folder1: img_0 ... img_74 folder2: img_0 ... img_74 Output: embeddings.npy -- Embeddings as np array (with names "folder1", "folder2", etc.) Use --is_aligned False, if your images aren't already pre-aligned Use --image_batch to dictacte how many images to load in memory at a time. Started with export_embeddings.py from Charles Jekel, and modified the program to export the face embeddings for the audio-visual speech separation model. The pretrained model is from David Sandberg's facenet repository: https://github.com/davidsandberg/facenet export_embedding.py from same project: https://github.com/davidsandberg/facenet/tree/master/contributed Ensure you have set the PYTHONPATH for the pretrained facenet (3.): https://github.com/davidsandberg/facenet/wiki/Validate-on-LFW Execution: python export_FaceEmbedding.py models\20180402-114759\20180402-114759.pb D:\images --is_aligned False --image_size 160 --gpu_memory_fraction 0.5 --image_batch 75 Sereina Scherrer 2019 """ # MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from scipy import misc import tensorflow as tf import numpy as np import sys import os import argparse import facenet import align.detect_face import re import glob from six.moves import xrange 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 main(args): train_set = facenet.get_dataset(args.data_dir) image_list, label_list = facenet.get_image_paths_and_labels(train_set) # sort the image:s img_0 ... img_74 image_list.sort(key=natural_keys) # fetch the classes (labels as strings) exactly as it's done in get_dataset path_exp = os.path.expanduser(args.data_dir) classes = [path for path in os.listdir(path_exp) \ if os.path.isdir(os.path.join(path_exp, path))] classes.sort() # get the label strings label_strings = [name for name in classes if \ os.path.isdir(os.path.join(path_exp, name))] # define path to save the embeddings dirs = ["./emb/embeddings_AVspeech/"] for d in dirs: if not os.path.exists(d): os.makedirs(d) print("Folder created:", d) with tf.Graph().as_default(): with tf.Session() as sess: # Load the model facenet.load_model(args.model_dir) # Get input and output tensors images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0") embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0") phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0") # Run forward pass to calculate embeddings nrof_images = len(image_list) print('Number of images: ', nrof_images) batch_size = args.image_batch if nrof_images % batch_size == 0: nrof_batches = nrof_images // batch_size else: nrof_batches = (nrof_images // batch_size) + 1 print('Number of batches: ', nrof_batches) embedding_size = embeddings.get_shape()[1] emb_array = np.zeros((nrof_images, embedding_size)) start_time = time.time() for i in range(nrof_batches): if i == nrof_batches -1: n = nrof_images else: n = i*batch_size + batch_size # Get images for the batch if args.is_aligned is True: images = facenet.load_data(image_list[i*batch_size:n], False, False, args.image_size) else: images = load_and_align_data(image_list[i*batch_size:n], args.image_size, args.margin, args.gpu_memory_fraction) feed_dict = { images_placeholder: images, phase_train_placeholder:False } # Use the facenet model to calcualte embeddings embed = sess.run(embeddings, feed_dict=feed_dict) emb_array[i*batch_size:n, :] = embed # export the embedding s = dirs[0] + label_strings[i] + ".npy" np.save(s, embed) print('Completed batch', i+1, 'of', nrof_batches) run_time = time.time() - start_time print('Run time: ', run_time) print('Time per video: ',run_time/nrof_batches) def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction): print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None) nrof_samples = len(image_paths) img_list = [None] * nrof_samples for i in xrange(nrof_samples): print(image_paths[i]) img = misc.imread(os.path.expanduser(image_paths[i])) aligned = misc.imresize(img, (image_size, image_size), interp='bilinear') prewhitened = facenet.prewhiten(aligned) img_list[i] = prewhitened # uncomment if you want to save the aligned images '''f = os.path.basename(image_paths[i]) #print(f) tmp_folder = re.split(r'\\', image_paths[i]) tmp_f = tmp_folder[-2] d = "./aligned/" + tmp_f + "/" if not os.path.exists(d): os.makedirs(d) print("Folder created:", d) misc.imsave(d + f, aligned)''' images = np.stack(img_list) return images def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('model_dir', type=str, help='Directory containing the meta_file and ckpt_file') parser.add_argument('data_dir', type=str, help='Directory containing images. If images are not already aligned and cropped include --is_aligned False.') parser.add_argument('--is_aligned', type=str, help='Is the data directory already aligned and cropped?', default=True) parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=160) parser.add_argument('--margin', type=int, help='Margin for the crop around the bounding box (height, width) in pixels.', default=44) parser.add_argument('--gpu_memory_fraction', type=float, help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0) parser.add_argument('--image_batch', type=int, help='Number of images stored in memory at a time. Default 75.', default=75) return parser.parse_args(argv) if __name__ == '__main__': main(parse_arguments(sys.argv[1:]))
[ "scipy.misc.imresize", "tensorflow.Graph", "numpy.stack", "numpy.save", "tensorflow.ConfigProto", "tensorflow.GPUOptions", "tensorflow.Session", "tensorflow.get_default_graph", "numpy.zeros" ]
preprocessing/embedding/export_FaceEmbedding.py
[(85, 'facenet.get_dataset', 'facenet.get_dataset', (['args.data_dir'], {}), False, 'import facenet\n'), (86, 'facenet.get_image_paths_and_labels', 'facenet.get_image_paths_and_labels', (['train_set'], {}), False, 'import facenet\n'), (92, 'os.path.expanduser', 'os.path.expanduser', (['args.data_dir'], {}), False, 'import os\n'), (171, 'six.moves.xrange', 'xrange', (['nrof_samples'], {}), False, 'from six.moves import xrange\n'), (191, 'numpy.stack', 'np.stack', (['img_list'], {}), True, 'import numpy as np\n'), (195, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (164, 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'gpu_memory_fraction'}), True, 'import tensorflow as tf\n'), (175, 'scipy.misc.imresize', 'misc.imresize', (['img', '(image_size, image_size)'], {'interp': '"""bilinear"""'}), False, 'from scipy import misc\n'), (176, 'facenet.prewhiten', 'facenet.prewhiten', (['aligned'], {}), False, 'import facenet\n'), (82, 're.split', 're.split', (['"""(\\\\d+)"""', 'text'], {}), False, 'import re\n'), (93, 'os.listdir', 'os.listdir', (['path_exp'], {}), False, 'import os\n'), (103, 'os.path.exists', 'os.path.exists', (['d'], {}), False, 'import os\n'), (104, 'os.makedirs', 'os.makedirs', (['d'], {}), False, 'import os\n'), (109, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (112, 'facenet.load_model', 'facenet.load_model', (['args.model_dir'], {}), False, 'import facenet\n'), (129, 'numpy.zeros', 'np.zeros', (['(nrof_images, embedding_size)'], {}), True, 'import numpy as np\n'), (130, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (173, 'os.path.expanduser', 'os.path.expanduser', (['image_paths[i]'], {}), False, 'import os\n'), (94, 'os.path.join', 'os.path.join', (['path_exp', 'path'], {}), False, 'import os\n'), (98, 'os.path.join', 'os.path.join', (['path_exp', 'name'], {}), False, 'import os\n'), (107, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (149, 'numpy.save', 'np.save', (['s', 'embed'], {}), True, 'import numpy as np\n'), (153, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (163, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_options', 'log_device_placement': '(False)'}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (139, 'facenet.load_data', 'facenet.load_data', (['image_list[i * batch_size:n]', '(False)', '(False)', 'args.image_size'], {}), False, 'import facenet\n')]
clear-nus/BOIRL
cc872111fda3c7b8118e1a864831013c30f63948
import time from rllab.algos.base import RLAlgorithm import rllab.misc.logger as logger import rllab.plotter as plotter from sandbox.rocky.tf.policies.base import Policy import tensorflow as tf from sandbox.rocky.tf.samplers.batch_sampler import BatchSampler from sandbox.rocky.tf.samplers.vectorized_sampler import VectorizedSampler import numpy as np from collections import deque from inverse_rl.utils.hyperparametrized import Hyperparametrized class IRLBatchPolopt(RLAlgorithm, metaclass=Hyperparametrized): """ Base class for batch sampling-based policy optimization methods. This includes various policy gradient methods like vpg, npg, ppo, trpo, etc. """ def __init__( self, env, policy, baseline, scope=None, n_itr=500, start_itr=0, batch_size=5000, max_path_length=500, discount=0.99, gae_lambda=1, plot=False, pause_for_plot=False, center_adv=True, positive_adv=False, store_paths=True, whole_paths=True, fixed_horizon=False, sampler_cls=None, sampler_args=None, force_batch_sampler=False, init_pol_params = None, irl_model=None, irl_model_wt=1.0, discrim_train_itrs=10, zero_environment_reward=False, init_irl_params=None, train_irl=True, key='', **kwargs ): """ :param env: Environment :param policy: Policy :type policy: Policy :param baseline: Baseline :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms simultaneously, each using different environments and policies :param n_itr: Number of iterations. :param start_itr: Starting iteration. :param batch_size: Number of samples per iteration. :param max_path_length: Maximum length of a single rollout. :param discount: Discount. :param gae_lambda: Lambda used for generalized advantage estimation. :param plot: Plot evaluation run after each iteration. :param pause_for_plot: Whether to pause before contiuing when plotting. :param center_adv: Whether to rescale the advantages so that they have mean 0 and standard deviation 1. :param positive_adv: Whether to shift the advantages so that they are always positive. When used in conjunction with center_adv the advantages will be standardized before shifting. :param store_paths: Whether to save all paths data to the snapshot. :return: """ self.env = env self.policy = policy self.baseline = baseline self.scope = scope self.n_itr = n_itr self.start_itr = start_itr self.batch_size = batch_size self.max_path_length = max_path_length self.discount = discount self.gae_lambda = gae_lambda self.plot = plot self.pause_for_plot = pause_for_plot self.center_adv = center_adv self.positive_adv = positive_adv self.store_paths = store_paths self.whole_paths = whole_paths self.fixed_horizon = fixed_horizon self.init_pol_params = init_pol_params self.init_irl_params = init_irl_params self.irl_model = irl_model self.irl_model_wt = irl_model_wt self.no_reward = zero_environment_reward self.discrim_train_itrs = discrim_train_itrs self.train_irl = train_irl self.__irl_params = None self.myweights = [] if self.irl_model_wt > 0: assert self.irl_model is not None, "Need to specify a IRL model" if sampler_cls is None: if self.policy.vectorized and not force_batch_sampler: print('using vec sampler') sampler_cls = VectorizedSampler else: print('using batch sampler') sampler_cls = BatchSampler if sampler_args is None: sampler_args = dict() self.sampler = sampler_cls(self, **sampler_args) self.init_opt() def start_worker(self): self.sampler.start_worker() if self.plot: #plotter.init_worker() plotter.init_plot(self.env, self.policy) def shutdown_worker(self): self.sampler.shutdown_worker() def obtain_samples(self, itr): return self.sampler.obtain_samples(itr) def process_samples(self, itr, paths): #processed = self.sampler.process_samples(itr, paths) return self.sampler.process_samples(itr, paths) def log_avg_returns(self, paths): undiscounted_returns = [sum(path["rewards"]) for path in paths] avg_return = np.mean(undiscounted_returns) return avg_return def get_irl_params(self): return self.__irl_params def compute_irl(self, paths, itr=0): if self.no_reward: tot_rew = 0 for path in paths: tot_rew += np.sum(path['rewards']) path['rewards'] *= 0 logger.record_tabular('OriginalTaskAverageReturn', tot_rew/float(len(paths))) if self.irl_model_wt <=0: return paths if self.train_irl: max_itrs = self.discrim_train_itrs lr=1e-3 mean_loss = self.irl_model.fit(paths, policy=self.policy, itr=itr, max_itrs=max_itrs, lr=lr, logger=logger) logger.record_tabular('IRLLoss', mean_loss) self.__irl_params = self.irl_model.get_params() probs = self.irl_model.eval(paths, gamma=self.discount, itr=itr) logger.record_tabular('IRLRewardMean', np.mean(probs)) logger.record_tabular('IRLRewardMax', np.max(probs)) logger.record_tabular('IRLRewardMin', np.min(probs)) if self.irl_model.score_trajectories: # TODO: should I add to reward here or after advantage computation? for i, path in enumerate(paths): path['rewards'][-1] += self.irl_model_wt * probs[i] else: for i, path in enumerate(paths): path['rewards'] += self.irl_model_wt * probs[i] return paths def train(self,weightname): sess = tf.get_default_session() sess.run(tf.global_variables_initializer()) if self.init_pol_params is not None: self.policy.set_param_values(self.init_pol_params) if self.init_irl_params is not None: self.irl_model.set_params(self.init_irl_params) self.start_worker() start_time = time.time() returns = [] self.myweights.append(self.irl_model.get_weights()) np.save(weightname, np.array(self.myweights)) for itr in range(self.start_itr, self.n_itr): itr_start_time = time.time() with logger.prefix('itr #%d | ' % itr): logger.log("Obtaining samples...") paths = self.obtain_samples(itr) logger.log("Processing samples...") paths = self.compute_irl(paths, itr=itr) returns.append(self.log_avg_returns(paths)) samples_data = self.process_samples(itr, paths) logger.log("Logging diagnostics...") self.log_diagnostics(paths) logger.log("Optimizing policy...") self.optimize_policy(itr, samples_data) logger.log("Saving snapshot...") params = self.get_itr_snapshot(itr, samples_data) # , **kwargs) if self.store_paths: params["paths"] = samples_data["paths"] logger.save_itr_params(itr, params) logger.log("Saved") logger.record_tabular('Time', time.time() - start_time) logger.record_tabular('ItrTime', time.time() - itr_start_time) logger.dump_tabular(with_prefix=False) if self.plot: self.update_plot() if self.pause_for_plot: input("Plotting evaluation run: Press Enter to " "continue...") self.myweights.append(self.irl_model.get_weights()) if itr%20 == 0: np.save(weightname, np.array(self.myweights)) np.save(weightname, np.array(self.myweights)) self.shutdown_worker() return def log_diagnostics(self, paths): self.env.log_diagnostics(paths) self.policy.log_diagnostics(paths) self.baseline.log_diagnostics(paths) def init_opt(self): """ Initialize the optimization procedure. If using tensorflow, this may include declaring all the variables and compiling functions """ raise NotImplementedError def get_itr_snapshot(self, itr, samples_data): """ Returns all the data that should be saved in the snapshot for this iteration. """ raise NotImplementedError def optimize_policy(self, itr, samples_data): raise NotImplementedError def update_plot(self): if self.plot: plotter.update_plot(self.policy, self.max_path_length)
[ "tensorflow.get_default_session", "numpy.min", "numpy.max", "tensorflow.global_variables_initializer", "numpy.mean", "numpy.array", "numpy.sum" ]
inverse_rl/algos/irl_batch_polopt.py
[(135, 'numpy.mean', 'np.mean', (['undiscounted_returns'], {}), True, 'import numpy as np\n'), (178, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (185, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (121, 'rllab.plotter.init_plot', 'plotter.init_plot', (['self.env', 'self.policy'], {}), True, 'import rllab.plotter as plotter\n'), (158, 'rllab.misc.logger.record_tabular', 'logger.record_tabular', (['"""IRLLoss"""', 'mean_loss'], {}), True, 'import rllab.misc.logger as logger\n'), (163, 'numpy.mean', 'np.mean', (['probs'], {}), True, 'import numpy as np\n'), (164, 'numpy.max', 'np.max', (['probs'], {}), True, 'import numpy as np\n'), (165, 'numpy.min', 'np.min', (['probs'], {}), True, 'import numpy as np\n'), (179, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (189, 'numpy.array', 'np.array', (['self.myweights'], {}), True, 'import numpy as np\n'), (191, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (222, 'numpy.array', 'np.array', (['self.myweights'], {}), True, 'import numpy as np\n'), (250, 'rllab.plotter.update_plot', 'plotter.update_plot', (['self.policy', 'self.max_path_length'], {}), True, 'import rllab.plotter as plotter\n'), (145, 'numpy.sum', 'np.sum', (["path['rewards']"], {}), True, 'import numpy as np\n'), (192, 'rllab.misc.logger.prefix', 'logger.prefix', (["('itr #%d | ' % itr)"], {}), True, 'import rllab.misc.logger as logger\n'), (193, 'rllab.misc.logger.log', 'logger.log', (['"""Obtaining samples..."""'], {}), True, 'import rllab.misc.logger as logger\n'), (196, 'rllab.misc.logger.log', 'logger.log', (['"""Processing samples..."""'], {}), True, 'import rllab.misc.logger as logger\n'), (201, 'rllab.misc.logger.log', 'logger.log', (['"""Logging diagnostics..."""'], {}), True, 'import rllab.misc.logger as logger\n'), (203, 'rllab.misc.logger.log', 'logger.log', (['"""Optimizing policy..."""'], {}), True, 'import rllab.misc.logger as logger\n'), (205, 'rllab.misc.logger.log', 'logger.log', (['"""Saving snapshot..."""'], {}), True, 'import rllab.misc.logger as logger\n'), (209, 'rllab.misc.logger.save_itr_params', 'logger.save_itr_params', (['itr', 'params'], {}), True, 'import rllab.misc.logger as logger\n'), (210, 'rllab.misc.logger.log', 'logger.log', (['"""Saved"""'], {}), True, 'import rllab.misc.logger as logger\n'), (213, 'rllab.misc.logger.dump_tabular', 'logger.dump_tabular', ([], {'with_prefix': '(False)'}), True, 'import rllab.misc.logger as logger\n'), (221, 'numpy.array', 'np.array', (['self.myweights'], {}), True, 'import numpy as np\n'), (211, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (212, 'time.time', 'time.time', ([], {}), False, 'import time\n')]
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
# Copyright 2015 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. # ============================================================================== """Tests for py_func op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from tensorflow.python.framework import errors from tensorflow.python.ops import script_ops class PyOpTest(tf.test.TestCase): def testBasic(self): def my_func(x, y): return np.sinh(x) + np.cosh(y) # scalar with self.test_session(): x = tf.constant(1.0, tf.float32) y = tf.constant(2.0, tf.float32) z = tf.py_func(my_func, [x, y], [tf.float32]) self.assertEqual(z[0].eval(), my_func(1.0, 2.0).astype(np.float32)) # array with self.test_session(): x = tf.constant([1.0, 2.0], tf.float64) y = tf.constant([2.0, 3.0], tf.float64) z = tf.py_func(my_func, [x, y], [tf.float64]) self.assertAllEqual( z[0].eval(), my_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64)) # a bit exotic type (complex64) with self.test_session(): x = tf.constant(1+2j, tf.complex64) y = tf.constant(3+4j, tf.complex64) z, = tf.py_func(my_func, [x, y], [tf.complex64]) self.assertAllClose(z.eval(), my_func(1+2j, 3+4j)) # a bit excotic function (rfft) with self.test_session(): x = tf.constant([1., 2., 3., 4.], tf.float32) def rfft(x): return np.fft.rfft(x).astype(np.complex64) y, = tf.py_func(rfft, [x], [tf.complex64]) self.assertAllClose(y.eval(), np.fft.rfft([1., 2., 3., 4.])) # returns a python literal. with self.test_session(): def literal(x): return 1.0 if x == 0.0 else 0.0 x = tf.constant(0.0, tf.float64) y, = tf.py_func(literal, [x], [tf.float64]) self.assertAllClose(y.eval(), 1.0) def testStrings(self): def read_fixed_length_numpy_strings(): return np.array([b" there"]) def read_and_return_strings(x, y): return x + y with self.test_session(): x = tf.constant([b"hello", b"hi"], tf.string) y, = tf.py_func(read_fixed_length_numpy_strings, [], [tf.string]) z, = tf.py_func(read_and_return_strings, [x, y], [tf.string]) self.assertListEqual(list(z.eval()), [b"hello there", b"hi there"]) def testLarge(self): with self.test_session() as sess: x = tf.zeros([1000000], dtype=np.float32) y = tf.py_func(lambda x: x + 1, [x], [tf.float32]) z = tf.py_func(lambda x: x * 2, [x], [tf.float32]) for _ in xrange(100): sess.run([y[0].op, z[0].op]) def testNoInput(self): with self.test_session(): x, = tf.py_func(lambda: 42.0, [], [tf.float64]) self.assertAllClose(x.eval(), 42.0) def testCleanup(self): for _ in xrange(1000): g = tf.Graph() with g.as_default(): c = tf.constant([1.], tf.float32) _ = tf.py_func(lambda x: x + 1, [c], [tf.float32]) self.assertTrue(script_ops._py_funcs.size() < 100) def testError(self): with self.test_session(): def bad1(): # Structured numpy arrays aren't supported. return np.array([], dtype=[("foo", np.float32)]) def bad2(): # Non-string python objects aren't supported. return tf.float32 y, = tf.py_func(bad1, [], [tf.string]) z, = tf.py_func(bad2, [], [tf.float64]) with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported numpy type"): y.eval() with self.assertRaisesRegexp(errors.UnimplementedError, "Unsupported object type"): z.eval() if __name__ == "__main__": tf.test.main()
[ "tensorflow.Graph", "tensorflow.constant", "numpy.cosh", "numpy.fft.rfft", "tensorflow.zeros", "tensorflow.test.main", "numpy.sinh", "tensorflow.python.ops.script_ops._py_funcs.size", "numpy.array", "tensorflow.py_func" ]
tensorflow/python/kernel_tests/py_func_test.py
[(131, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (102, 'six.moves.xrange', 'xrange', (['(1000)'], {}), False, 'from six.moves import xrange\n'), (37, 'tensorflow.constant', 'tf.constant', (['(1.0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.constant', 'tf.constant', (['(2.0)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.py_func', 'tf.py_func', (['my_func', '[x, y]', '[tf.float32]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0]', 'tf.float64'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.constant', 'tf.constant', (['[2.0, 3.0]', 'tf.float64'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.py_func', 'tf.py_func', (['my_func', '[x, y]', '[tf.float64]'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.constant', 'tf.constant', (['(1 + 2.0j)', 'tf.complex64'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.constant', 'tf.constant', (['(3 + 4.0j)', 'tf.complex64'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.py_func', 'tf.py_func', (['my_func', '[x, y]', '[tf.complex64]'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0]', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.py_func', 'tf.py_func', (['rfft', '[x]', '[tf.complex64]'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.constant', 'tf.constant', (['(0.0)', 'tf.float64'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.py_func', 'tf.py_func', (['literal', '[x]', '[tf.float64]'], {}), True, 'import tensorflow as tf\n'), (77, 'numpy.array', 'np.array', (["[b' there']"], {}), True, 'import numpy as np\n'), (83, 'tensorflow.constant', 'tf.constant', (["[b'hello', b'hi']", 'tf.string'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.py_func', 'tf.py_func', (['read_fixed_length_numpy_strings', '[]', '[tf.string]'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.py_func', 'tf.py_func', (['read_and_return_strings', '[x, y]', '[tf.string]'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.zeros', 'tf.zeros', (['[1000000]'], {'dtype': 'np.float32'}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.py_func', 'tf.py_func', (['(lambda x: x + 1)', '[x]', '[tf.float32]'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.py_func', 'tf.py_func', (['(lambda x: x * 2)', '[x]', '[tf.float32]'], {}), True, 'import tensorflow as tf\n'), (93, 'six.moves.xrange', 'xrange', (['(100)'], {}), False, 'from six.moves import xrange\n'), (98, 'tensorflow.py_func', 'tf.py_func', (['(lambda : 42.0)', '[]', '[tf.float64]'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.py_func', 'tf.py_func', (['bad1', '[]', '[tf.string]'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.py_func', 'tf.py_func', (['bad2', '[]', '[tf.float64]'], {}), True, 'import tensorflow as tf\n'), (33, 'numpy.sinh', 'np.sinh', (['x'], {}), True, 'import numpy as np\n'), (33, 'numpy.cosh', 'np.cosh', (['y'], {}), True, 'import numpy as np\n'), (64, 'numpy.fft.rfft', 'np.fft.rfft', (['[1.0, 2.0, 3.0, 4.0]'], {}), True, 'import numpy as np\n'), (105, 'tensorflow.constant', 'tf.constant', (['[1.0]', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.py_func', 'tf.py_func', (['(lambda x: x + 1)', '[c]', '[tf.float32]'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.python.ops.script_ops._py_funcs.size', 'script_ops._py_funcs.size', ([], {}), False, 'from tensorflow.python.ops import script_ops\n'), (114, 'numpy.array', 'np.array', (['[]'], {'dtype': "[('foo', np.float32)]"}), True, 'import numpy as np\n'), (62, 'numpy.fft.rfft', 'np.fft.rfft', (['x'], {}), True, 'import numpy as np\n')]
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
# Copyright 2015 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. # ============================================================================== """Tests for state updating ops that may have benign race conditions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class AssignOpTest(tf.test.TestCase): # NOTE(mrry): We exclude thess tests from the TSAN TAP target, because they # contain benign and deliberate data races when multiple threads update # the same parameters without a lock. def testParallelUpdateWithoutLocking(self): with self.test_session() as sess: ones_t = tf.fill([1024, 1024], 1.0) p = tf.Variable(tf.zeros([1024, 1024])) adds = [tf.assign_add(p, ones_t, use_locking=False) for _ in range(20)] tf.initialize_all_variables().run() def run_add(add_op): sess.run(add_op) threads = [self.checkedThread(target=run_add, args=(add_op,)) for add_op in adds] for t in threads: t.start() for t in threads: t.join() vals = p.eval() ones = np.ones((1024, 1024)).astype(np.float32) self.assertTrue((vals >= ones).all()) self.assertTrue((vals <= ones * 20).all()) def testParallelAssignWithoutLocking(self): with self.test_session() as sess: ones_t = tf.fill([1024, 1024], float(1)) p = tf.Variable(tf.zeros([1024, 1024])) assigns = [tf.assign(p, tf.mul(ones_t, float(i)), False) for i in range(1, 21)] tf.initialize_all_variables().run() def run_assign(assign_op): sess.run(assign_op) threads = [self.checkedThread(target=run_assign, args=(assign_op,)) for assign_op in assigns] for t in threads: t.start() for t in threads: t.join() vals = p.eval() # Assert every element is taken from one of the assignments. self.assertTrue((vals > 0).all()) self.assertTrue((vals <= 20).all()) if __name__ == "__main__": tf.test.main()
[ "tensorflow.fill", "tensorflow.assign_add", "tensorflow.zeros", "tensorflow.test.main", "numpy.ones", "tensorflow.initialize_all_variables" ]
tensorflow/python/kernel_tests/dense_update_ops_no_tsan_test.py
[(77, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.zeros', 'tf.zeros', (['[1024, 1024]'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.assign_add', 'tf.assign_add', (['p', 'ones_t'], {'use_locking': '(False)'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.zeros', 'tf.zeros', (['[1024, 1024]'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n'), (48, 'numpy.ones', 'np.ones', (['(1024, 1024)'], {}), True, 'import numpy as np\n'), (58, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n')]
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
# Copyright 2015 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. # ============================================================================== """GradientDescent for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import constant_op # pylint: disable=unused-import from tensorflow.python.ops import math_ops # pylint: enable=unused-import from tensorflow.python.training import optimizer from tensorflow.python.training import training_ops class GradientDescentOptimizer(optimizer.Optimizer): """Optimizer that implements the gradient descent algorithm. @@__init__ """ def __init__(self, learning_rate, use_locking=False, name="GradientDescent"): """Construct a new gradient descent optimizer. Args: learning_rate: A Tensor or a floating point value. The learning rate to use. use_locking: If True use locks for update operations. name: Optional name prefix for the operations created when applying gradients. Defaults to "GradientDescent". """ super(GradientDescentOptimizer, self).__init__(use_locking, name) self._learning_rate = learning_rate def _apply_dense(self, grad, var): return training_ops.apply_gradient_descent( var, self._learning_rate_tensor, grad, use_locking=self._use_locking).op def _apply_sparse(self, grad, var): delta = ops.IndexedSlices(grad.values * self._learning_rate_tensor, grad.indices, grad.dense_shape) return var.scatter_sub(delta, use_locking=self._use_locking) def _prepare(self): self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate, name="learning_rate")
[ "tensorflow.python.framework.ops.IndexedSlices", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.training.training_ops.apply_gradient_descent" ]
tensorflow/python/training/gradient_descent.py
[(57, 'tensorflow.python.framework.ops.IndexedSlices', 'ops.IndexedSlices', (['(grad.values * self._learning_rate_tensor)', 'grad.indices', 'grad.dense_shape'], {}), False, 'from tensorflow.python.framework import ops\n'), (62, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['self._learning_rate'], {'name': '"""learning_rate"""'}), False, 'from tensorflow.python.framework import ops\n'), (50, 'tensorflow.python.training.training_ops.apply_gradient_descent', 'training_ops.apply_gradient_descent', (['var', 'self._learning_rate_tensor', 'grad'], {'use_locking': 'self._use_locking'}), False, 'from tensorflow.python.training import training_ops\n')]
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
# -*- coding: utf-8 -*- # Copyright 2015 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. # ============================================================================== """Tests for tensorflow.python.ops.io_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile import tensorflow as tf class IoOpsTest(tf.test.TestCase): def testReadFile(self): cases = ['', 'Some contents', 'Неки садржаји на српском'] for contents in cases: contents = tf.compat.as_bytes(contents) temp = tempfile.NamedTemporaryFile(prefix='ReadFileTest') open(temp.name, 'wb').write(contents) with self.test_session(): read = tf.read_file(temp.name) self.assertEqual([], read.get_shape()) self.assertEqual(read.eval(), contents) def _subset(self, files, indices): return set(tf.compat.as_bytes(files[i].name) for i in range(len(files)) if i in indices) def testMatchingFiles(self): cases = ['ABcDEF.GH', 'ABzDEF.GH', 'ABasdfjklDEF.GH', 'AB3DEF.GH', 'AB4DEF.GH', 'ABDEF.GH', 'XYZ'] files = [tempfile.NamedTemporaryFile(prefix=c) for c in cases] with self.test_session(): # Test exact match without wildcards. for f in files: self.assertEqual(tf.matching_files(f.name).eval(), tf.compat.as_bytes(f.name)) # We will look for files matching "ABxDEF.GH*" where "x" is some wildcard. pos = files[0].name.find(cases[0]) pattern = files[0].name[:pos] + 'AB%sDEF.GH*' self.assertEqual(set(tf.matching_files(pattern % 'z').eval()), self._subset(files, [1])) self.assertEqual(set(tf.matching_files(pattern % '?').eval()), self._subset(files, [0, 1, 3, 4])) self.assertEqual(set(tf.matching_files(pattern % '*').eval()), self._subset(files, [0, 1, 2, 3, 4, 5])) self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()), self._subset(files, [0, 1])) self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()), self._subset(files, [3, 4])) if __name__ == '__main__': tf.test.main()
[ "tensorflow.compat.as_bytes", "tensorflow.matching_files", "tensorflow.test.main", "tensorflow.read_file" ]
tensorflow/python/kernel_tests/io_ops_test.py
[(73, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.compat.as_bytes', 'tf.compat.as_bytes', (['contents'], {}), True, 'import tensorflow as tf\n'), (34, 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': '"""ReadFileTest"""'}), False, 'import tempfile\n'), (48, 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'prefix': 'c'}), False, 'import tempfile\n'), (37, 'tensorflow.read_file', 'tf.read_file', (['temp.name'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.compat.as_bytes', 'tf.compat.as_bytes', (['files[i].name'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.compat.as_bytes', 'tf.compat.as_bytes', (['f.name'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.matching_files', 'tf.matching_files', (['f.name'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.matching_files', 'tf.matching_files', (["(pattern % 'z')"], {}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.matching_files', 'tf.matching_files', (["(pattern % '?')"], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.matching_files', 'tf.matching_files', (["(pattern % '*')"], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.matching_files', 'tf.matching_files', (["(pattern % '[cxz]')"], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.matching_files', 'tf.matching_files', (["(pattern % '[0-9]')"], {}), True, 'import tensorflow as tf\n')]
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
# Copyright 2015 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. # ============================================================================== """Tests for tensorflow.ops.tf.Assign*.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class AssignOpTest(tf.test.TestCase): def _initAssignFetch(self, x, y, use_gpu=False): """Initialize a param to init and update it with y.""" super(AssignOpTest, self).setUp() with self.test_session(use_gpu=use_gpu): p = tf.Variable(x) assign = tf.assign(p, y) p.initializer.run() new_value = assign.eval() return p.eval(), new_value def _initAssignAddFetch(self, x, y, use_gpu=False): """Initialize a param to init, and compute param += y.""" with self.test_session(use_gpu=use_gpu): p = tf.Variable(x) add = tf.assign_add(p, y) p.initializer.run() new_value = add.eval() return p.eval(), new_value def _initAssignSubFetch(self, x, y, use_gpu=False): """Initialize a param to init, and compute param -= y.""" with self.test_session(use_gpu=use_gpu): p = tf.Variable(x) sub = tf.assign_sub(p, y) p.initializer.run() new_value = sub.eval() return p.eval(), new_value def _testTypes(self, vals): for dtype in [np.float32, np.float64, np.int32, np.int64]: x = np.zeros(vals.shape).astype(dtype) y = vals.astype(dtype) var_value, op_value = self._initAssignFetch(x, y, use_gpu=False) self.assertAllEqual(y, var_value) self.assertAllEqual(y, op_value) var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=False) self.assertAllEqual(x + y, var_value) self.assertAllEqual(x + y, op_value) var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False) self.assertAllEqual(x - y, var_value) self.assertAllEqual(x - y, op_value) if tf.test.is_built_with_cuda() and dtype in [np.float32, np.float64]: var_value, op_value = self._initAssignFetch(x, y, use_gpu=True) self.assertAllEqual(y, var_value) self.assertAllEqual(y, op_value) var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=True) self.assertAllEqual(x + y, var_value) self.assertAllEqual(x + y, op_value) var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False) self.assertAllEqual(x - y, var_value) self.assertAllEqual(x - y, op_value) def testBasic(self): self._testTypes(np.arange(0, 20).reshape([4, 5])) def testAssignNonStrictShapeChecking(self): with self.test_session(): data = tf.fill([1024, 1024], 0) p = tf.Variable([1]) a = tf.assign(p, data, validate_shape=False) a.op.run() self.assertAllEqual(p.eval(), data.eval()) # Assign to yet another shape data2 = tf.fill([10, 10], 1) a2 = tf.assign(p, data2, validate_shape=False) a2.op.run() self.assertAllEqual(p.eval(), data2.eval()) def testInitRequiredAssignAdd(self): with self.test_session(): p = tf.Variable(tf.fill([1024, 1024], 1), tf.int32) a = tf.assign_add(p, tf.fill([1024, 1024], 0)) with self.assertRaisesOpError("use uninitialized"): a.op.run() def testInitRequiredAssignSub(self): with self.test_session(): p = tf.Variable(tf.fill([1024, 1024], 1), tf.int32) a = tf.assign_sub(p, tf.fill([1024, 1024], 0)) with self.assertRaisesOpError("use uninitialized"): a.op.run() # NOTE(mrry): See also # dense_update_ops_no_tsan_test.AssignOpTest, which contains a benign # data race and must run without TSAN. def testParallelUpdateWithLocking(self): with self.test_session() as sess: zeros_t = tf.fill([1024, 1024], 0.0) ones_t = tf.fill([1024, 1024], 1.0) p = tf.Variable(zeros_t) adds = [tf.assign_add(p, ones_t, use_locking=True) for _ in range(20)] p.initializer.run() def run_add(add_op): sess.run(add_op) threads = [ self.checkedThread(target=run_add, args=(add_op,)) for add_op in adds] for t in threads: t.start() for t in threads: t.join() vals = p.eval() ones = np.ones((1024, 1024)).astype(np.float32) self.assertAllEqual(vals, ones * 20) # NOTE(mrry): See also # dense_update_ops_no_tsan_test.[...].testParallelAssignWithoutLocking, # which contains a benign data race and must run without TSAN. def testParallelAssignWithLocking(self): with self.test_session() as sess: zeros_t = tf.fill([1024, 1024], 0.0) ones_t = tf.fill([1024, 1024], 1.0) p = tf.Variable(zeros_t) assigns = [tf.assign(p, tf.mul(ones_t, float(i)), use_locking=True) for i in range(1, 21)] p.initializer.run() def run_assign(assign_op): sess.run(assign_op) threads = [self.checkedThread(target=run_assign, args=(assign_op,)) for assign_op in assigns] for t in threads: t.start() for t in threads: t.join() vals = p.eval() # Assert every element is the same, and taken from one of the assignments. self.assertTrue(vals[0, 0] > 0) self.assertTrue(vals[0, 0] <= 20) self.assertAllEqual(vals, np.ones([1024, 1024]) * vals[0, 0]) if __name__ == "__main__": tf.test.main()
[ "tensorflow.fill", "tensorflow.assign_add", "tensorflow.Variable", "numpy.arange", "tensorflow.test.is_built_with_cuda", "tensorflow.assign", "tensorflow.test.main", "numpy.ones", "tensorflow.assign_sub", "numpy.zeros" ]
tensorflow/python/kernel_tests/dense_update_ops_test.py
[(168, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.Variable', 'tf.Variable', (['x'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.assign', 'tf.assign', (['p', 'y'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.Variable', 'tf.Variable', (['x'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.assign_add', 'tf.assign_add', (['p', 'y'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.Variable', 'tf.Variable', (['x'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.assign_sub', 'tf.assign_sub', (['p', 'y'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(0)'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.Variable', 'tf.Variable', (['[1]'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.assign', 'tf.assign', (['p', 'data'], {'validate_shape': '(False)'}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.fill', 'tf.fill', (['[10, 10]', '(1)'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.assign', 'tf.assign', (['p', 'data2'], {'validate_shape': '(False)'}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(0.0)'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.Variable', 'tf.Variable', (['zeros_t'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(0.0)'], {}), True, 'import tensorflow as tf\n'), (143, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.Variable', 'tf.Variable', (['zeros_t'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.test.is_built_with_cuda', 'tf.test.is_built_with_cuda', ([], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(1)'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(0)'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(1)'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.fill', 'tf.fill', (['[1024, 1024]', '(0)'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.assign_add', 'tf.assign_add', (['p', 'ones_t'], {'use_locking': '(True)'}), True, 'import tensorflow as tf\n'), (57, 'numpy.zeros', 'np.zeros', (['vals.shape'], {}), True, 'import numpy as np\n'), (80, 'numpy.arange', 'np.arange', (['(0)', '(20)'], {}), True, 'import numpy as np\n'), (134, 'numpy.ones', 'np.ones', (['(1024, 1024)'], {}), True, 'import numpy as np\n'), (164, 'numpy.ones', 'np.ones', (['[1024, 1024]'], {}), True, 'import numpy as np\n')]
parachutel/garage
f4a6271edd0f9c280c306d1f0bbf4bc1591ab85e
import gc from dowel import logger import tensorflow as tf from garage.experiment import deterministic from tests.fixtures.logger import NullOutput class TfTestCase: def setup_method(self): self.sess = tf.compat.v1.Session() self.sess.__enter__() def teardown_method(self): self.sess.__exit__(None, None, None) self.sess.close() del self.sess gc.collect() class TfGraphTestCase: def setup_method(self): tf.reset_default_graph() self.graph = tf.Graph() for c in self.graph.collections: self.graph.clear_collection(c) self.graph_manager = self.graph.as_default() self.graph_manager.__enter__() self.sess = tf.Session(graph=self.graph) self.sess_manager = self.sess.as_default() self.sess_manager.__enter__() self.sess.__enter__() logger.add_output(NullOutput()) deterministic.set_seed(1) # initialize global singleton_pool for each test case from garage.sampler import singleton_pool singleton_pool.initialize(1) def teardown_method(self): logger.remove_all() self.sess.__exit__(None, None, None) self.sess_manager.__exit__(None, None, None) self.graph_manager.__exit__(None, None, None) self.sess.close() # These del are crucial to prevent ENOMEM in the CI # b/c TensorFlow does not release memory explicitly del self.graph del self.sess gc.collect()
[ "tensorflow.compat.v1.Session", "tensorflow.Graph", "tensorflow.reset_default_graph", "tensorflow.Session" ]
tests/fixtures/fixtures.py
[(12, 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), True, 'import tensorflow as tf\n'), (19, 'gc.collect', 'gc.collect', ([], {}), False, 'import gc\n'), (24, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.Session', 'tf.Session', ([], {'graph': 'self.graph'}), True, 'import tensorflow as tf\n'), (35, 'garage.experiment.deterministic.set_seed', 'deterministic.set_seed', (['(1)'], {}), False, 'from garage.experiment import deterministic\n'), (39, 'garage.sampler.singleton_pool.initialize', 'singleton_pool.initialize', (['(1)'], {}), False, 'from garage.sampler import singleton_pool\n'), (42, 'dowel.logger.remove_all', 'logger.remove_all', ([], {}), False, 'from dowel import logger\n'), (52, 'gc.collect', 'gc.collect', ([], {}), False, 'import gc\n'), (34, 'tests.fixtures.logger.NullOutput', 'NullOutput', ([], {}), False, 'from tests.fixtures.logger import NullOutput\n')]
Dongzhou-1996/tf_learning
fe764e78cc1a934707ae01d0847f901cb6fbb8b9
#!/usr/bin/env python # coding=utf-8 import tensorflow as tf import os import numpy as np import argparse import shutil from tensorflow.examples.tutorials.mnist import input_data parser = argparse.ArgumentParser('MNIST Softmax') parser.add_argument('--data_dir', type=str, default='/tmp/mnist-data', help='the directory of MNIST dataset') parser.add_argument('--lr', type=float, default=0.01, help='learning rate') parser.add_argument('--batch_size', type=int, default=32, help='batch size') parser.add_argument('--max_train_step', type=int, default=50000, help='the maximum training step') parser.add_argument('--model_path', type=str, default='', help='the path of checkpoint file') args = parser.parse_args() def model(): x = tf.placeholder(tf.float32, [None, 784], name='x') gt = tf.placeholder(tf.float32, [None, 10], name='groundtruth') with tf.variable_scope('layer1'): w1 = tf.get_variable('weight1', [784, 1024], initializer=tf.random_normal_initializer()) b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0)) h1 = tf.nn.relu(tf.matmul(x, w1) + b1) with tf.variable_scope('layer2'): w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer()) b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0)) h2 = tf.nn.relu(tf.matmul(h1, w2) + b2) with tf.variable_scope('layer3'): w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer()) b3 = tf.get_variable('bias3', [10], initializer=tf.constant_initializer(0.0)) y = tf.matmul(h2, w3) + b3 # losses cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=gt, logits=y)) # optimizer optimizer = tf.train.GradientDescentOptimizer(args.lr) # define one-step train ops train_op = optimizer.minimize(cross_entropy) return x, y, gt, train_op if __name__ == "__main__": max_train_step = args.max_train_step batch_size = args.batch_size mnist = input_data.read_data_sets(args.data_dir, one_hot=True) x, y, gt, train_op = model() # create saver saver = tf.train.Saver() if os.path.exists('./mnist'): print('=> directory is existed!') else: print('=> creating temporary directory ...') os.makedirs('./mnist') with tf.Session() as sess: if args.model_path == '': tf.global_variables_initializer().run() else: saver.restore(sess, args.model_path) for i in range(max_train_step): batch_x, batch_gt = mnist.train.next_batch(batch_size) sess.run(train_op, feed_dict={x: batch_x, gt: batch_gt}) if i % 100 == 0: correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(gt, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print('=> accuracy: {}'.format(sess.run(accuracy, feed_dict={x: mnist.test.images, gt: mnist.test.labels}))) saver.save(sess, 'mnist/mnist_{:02d}.ckpt'.format(int(i / 100) + 1))
[ "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.matmul", "tensorflow.cast", "tensorflow.placeholder", "tensorflow.constant_initializer", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.variable_scope", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.random_normal_initializer", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ]
tf_mnist.py
[(10, 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""MNIST Softmax"""'], {}), False, 'import argparse\n'), (20, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 784]'], {'name': '"""x"""'}), True, 'import tensorflow as tf\n'), (21, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 10]'], {'name': '"""groundtruth"""'}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['args.lr'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['args.data_dir'], {'one_hot': '(True)'}), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), (49, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (50, 'os.path.exists', 'os.path.exists', (['"""./mnist"""'], {}), False, 'import os\n'), (22, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer1"""'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer2"""'], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer3"""'], {}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'labels': 'gt', 'logits': 'y'}), True, 'import tensorflow as tf\n'), (54, 'os.makedirs', 'os.makedirs', (['"""./mnist"""'], {}), False, 'import os\n'), (56, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.matmul', 'tf.matmul', (['h2', 'w3'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.matmul', 'tf.matmul', (['x', 'w1'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.matmul', 'tf.matmul', (['h1', 'w2'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.argmax', 'tf.argmax', (['gt', '(1)'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), True, 'import tensorflow as tf\n')]
dolaameng/tensorflow_cookbook
ca9bcb892239e9276e9348689e06cd6d1edd19ef
# Operations on a Computational Graph import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.python.framework import ops ops.reset_default_graph() # Create graph sess = tf.Session() # Create tensors # Create data to feed in x_vals = np.array([1., 3., 5., 7., 9.]) x_data = tf.placeholder(tf.float32) m = tf.constant(3.) # Multiplication prod = tf.mul(x_data, m) for x_val in x_vals: print(sess.run(prod, feed_dict={x_data: x_val})) merged = tf.merge_all_summaries() if not os.path.exists('tensorboard_logs/'): os.makedirs('tensorboard_logs/') my_writer = tf.train.SummaryWriter('tensorboard_logs/', sess.graph)
[ "tensorflow.constant", "tensorflow.merge_all_summaries", "tensorflow.placeholder", "tensorflow.mul", "tensorflow.train.SummaryWriter", "tensorflow.Session", "numpy.array", "tensorflow.python.framework.ops.reset_default_graph" ]
02_TensorFlow_Way/01_Operations_as_a_Computational_Graph/01_operations_on_a_graph.py
[(6, 'tensorflow.python.framework.ops.reset_default_graph', 'ops.reset_default_graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (9, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (14, 'numpy.array', 'np.array', (['[1.0, 3.0, 5.0, 7.0, 9.0]'], {}), True, 'import numpy as np\n'), (15, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.constant', 'tf.constant', (['(3.0)'], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.mul', 'tf.mul', (['x_data', 'm'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.merge_all_summaries', 'tf.merge_all_summaries', ([], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.train.SummaryWriter', 'tf.train.SummaryWriter', (['"""tensorboard_logs/"""', 'sess.graph'], {}), True, 'import tensorflow as tf\n')]
dolaameng/tensorflow_cookbook
ca9bcb892239e9276e9348689e06cd6d1edd19ef
# -*- coding: utf-8 -*- # Using Multiple Devices #---------------------------------- # # This function gives us the ways to use # multiple devices (executors) in TensorFlow. import tensorflow as tf from tensorflow.python.framework import ops ops.reset_default_graph() # To find out where placement occurs, set 'log_device_placement' sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) # Runs the op. print(sess.run(c)) # If we load a graph and want device placement to be forgotten, # we set a parameter in our session: config = tf.ConfigProto() config.allow_soft_placement = True sess_soft = tf.Session(config=config) # GPUs #--------------------------------- # Note that the GPU must have a compute capability > 3.5 for TF to use. # http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capability # Careful with GPU memory allocation, TF never releases it. TF starts with almost # all of the GPU memory allocated. We can slowly grow to that limit with an # option setting: config.gpu_options.allow_growth = True sess_grow = tf.Session(config=config) # Also, we can limit the size of GPU memory used, with the following option config.gpu_options.per_process_gpu_memory_fraction = 0.4 sess_limited = tf.Session(config=config) # How to set placements on multiple devices. # Here, assume we have three devies CPU:0, GPU:0, and GPU:1 if tf.test.is_built_with_cuda(): with tf.device('/cpu:0'): a = tf.constant([1.0, 3.0, 5.0], shape=[1, 3]) b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1]) with tf.device('/gpu:1'): c = tf.matmul(a,b) c = tf.reshape(c, [-1]) with tf.device('/gpu:2'): d = tf.matmul(b,a) flat_d = tf.reshape(d, [-1]) combined = tf.mul(c, flat_d) print(sess.run(combined))
[ "tensorflow.matmul", "tensorflow.device", "tensorflow.constant", "tensorflow.test.is_built_with_cuda", "tensorflow.reshape", "tensorflow.mul", "tensorflow.ConfigProto", "tensorflow.Session", "tensorflow.python.framework.ops.reset_default_graph" ]
10_Taking_TensorFlow_to_Production/02_Using_Multiple_Devices/02_using_multiple_devices.py
[(10, 'tensorflow.python.framework.ops.reset_default_graph', 'ops.reset_default_graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (15, 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {'shape': '[2, 3]', 'name': '"""a"""'}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {'shape': '[3, 2]', 'name': '"""b"""'}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.matmul', 'tf.matmul', (['a', 'b'], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.test.is_built_with_cuda', 'tf.test.is_built_with_cuda', ([], {}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'log_device_placement': '(True)'}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.constant', 'tf.constant', (['[1.0, 3.0, 5.0]'], {'shape': '[1, 3]'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.constant', 'tf.constant', (['[2.0, 4.0, 6.0]'], {'shape': '[3, 1]'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.mul', 'tf.mul', (['c', 'flat_d'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.device', 'tf.device', (['"""/gpu:1"""'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.matmul', 'tf.matmul', (['a', 'b'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.reshape', 'tf.reshape', (['c', '[-1]'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.device', 'tf.device', (['"""/gpu:2"""'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.matmul', 'tf.matmul', (['b', 'a'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.reshape', 'tf.reshape', (['d', '[-1]'], {}), True, 'import tensorflow as tf\n')]
theendsofinvention/cartoonify
39ea84d96b3e93f0480e6d6158bea506d01278ca
# 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. # ============================================================================== """Box predictor for object detectors. Box predictors are classes that take a high level image feature map as input and produce two predictions, (1) a tensor encoding box locations, and (2) a tensor encoding classes for each box. These components are passed directly to loss functions in our detection models. These modules are separated from the main model since the same few box predictor architectures are shared across many models. """ from abc import abstractmethod import tensorflow as tf from app.object_detection.utils import ops from app.object_detection.utils import shape_utils from app.object_detection.utils import static_shape slim = tf.contrib.slim BOX_ENCODINGS = 'box_encodings' CLASS_PREDICTIONS_WITH_BACKGROUND = 'class_predictions_with_background' MASK_PREDICTIONS = 'mask_predictions' class BoxPredictor(object): """BoxPredictor.""" def __init__(self, is_training, num_classes): """Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned classification targets can range from {0,... K}). """ self._is_training = is_training self._num_classes = num_classes @property def num_classes(self): return self._num_classes def predict(self, image_features, num_predictions_per_location, scope, **params): """Computes encoded object locations and corresponding confidences. Takes a high level image feature map as input and produce two predictions, (1) a tensor encoding box locations, and (2) a tensor encoding class scores for each corresponding box. In this interface, we only assume that two tensors are returned as output and do not assume anything about their shapes. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. scope: Variable and Op scope name. **params: Additional keyword arguments for specific implementations of BoxPredictor. Returns: A dictionary containing at least the following tensors. box_encodings: A float tensor of shape [batch_size, num_anchors, q, code_size] representing the location of the objects, where q is 1 or the number of classes. class_predictions_with_background: A float tensor of shape [batch_size, num_anchors, num_classes + 1] representing the class predictions for the proposals. """ with tf.variable_scope(scope): return self._predict(image_features, num_predictions_per_location, **params) # TODO: num_predictions_per_location could be moved to constructor. # This is currently only used by ConvolutionalBoxPredictor. @abstractmethod def _predict(self, image_features, num_predictions_per_location, **params): """Implementations must override this method. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. **params: Additional keyword arguments for specific implementations of BoxPredictor. Returns: A dictionary containing at least the following tensors. box_encodings: A float tensor of shape [batch_size, num_anchors, q, code_size] representing the location of the objects, where q is 1 or the number of classes. class_predictions_with_background: A float tensor of shape [batch_size, num_anchors, num_classes + 1] representing the class predictions for the proposals. """ pass class RfcnBoxPredictor(BoxPredictor): """RFCN Box Predictor. Applies a position sensitve ROI pooling on position sensitive feature maps to predict classes and refined locations. See https://arxiv.org/abs/1605.06409 for details. This is used for the second stage of the RFCN meta architecture. Notice that locations are *not* shared across classes, thus for each anchor, a separate prediction is made for each class. """ def __init__(self, is_training, num_classes, conv_hyperparams, num_spatial_bins, depth, crop_size, box_code_size): """Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned classification targets can range from {0,... K}). conv_hyperparams: Slim arg_scope with hyperparameters for conolutional layers. num_spatial_bins: A list of two integers `[spatial_bins_y, spatial_bins_x]`. depth: Target depth to reduce the input feature maps to. crop_size: A list of two integers `[crop_height, crop_width]`. box_code_size: Size of encoding for each box. """ super(RfcnBoxPredictor, self).__init__(is_training, num_classes) self._conv_hyperparams = conv_hyperparams self._num_spatial_bins = num_spatial_bins self._depth = depth self._crop_size = crop_size self._box_code_size = box_code_size @property def num_classes(self): return self._num_classes def _predict(self, image_features, num_predictions_per_location, proposal_boxes): """Computes encoded object locations and corresponding confidences. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. Currently, this must be set to 1, or an error will be raised. proposal_boxes: A float tensor of shape [batch_size, num_proposals, box_code_size]. Returns: box_encodings: A float tensor of shape [batch_size, 1, num_classes, code_size] representing the location of the objects. class_predictions_with_background: A float tensor of shape [batch_size, 1, num_classes + 1] representing the class predictions for the proposals. Raises: ValueError: if num_predictions_per_location is not 1. """ if num_predictions_per_location != 1: raise ValueError('Currently RfcnBoxPredictor only supports ' 'predicting a single box per class per location.') batch_size = tf.shape(proposal_boxes)[0] num_boxes = tf.shape(proposal_boxes)[1] def get_box_indices(proposals): proposals_shape = proposals.get_shape().as_list() if any(dim is None for dim in proposals_shape): proposals_shape = tf.shape(proposals) ones_mat = tf.ones(proposals_shape[:2], dtype=tf.int32) multiplier = tf.expand_dims( tf.range(start=0, limit=proposals_shape[0]), 1) return tf.reshape(ones_mat * multiplier, [-1]) net = image_features with slim.arg_scope(self._conv_hyperparams): net = slim.conv2d(net, self._depth, [1, 1], scope='reduce_depth') # Location predictions. location_feature_map_depth = (self._num_spatial_bins[0] * self._num_spatial_bins[1] * self.num_classes * self._box_code_size) location_feature_map = slim.conv2d(net, location_feature_map_depth, [1, 1], activation_fn=None, scope='refined_locations') box_encodings = ops.position_sensitive_crop_regions( location_feature_map, boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]), box_ind=get_box_indices(proposal_boxes), crop_size=self._crop_size, num_spatial_bins=self._num_spatial_bins, global_pool=True) box_encodings = tf.squeeze(box_encodings, squeeze_dims=[1, 2]) box_encodings = tf.reshape(box_encodings, [batch_size * num_boxes, 1, self.num_classes, self._box_code_size]) # Class predictions. total_classes = self.num_classes + 1 # Account for background class. class_feature_map_depth = (self._num_spatial_bins[0] * self._num_spatial_bins[1] * total_classes) class_feature_map = slim.conv2d(net, class_feature_map_depth, [1, 1], activation_fn=None, scope='class_predictions') class_predictions_with_background = ops.position_sensitive_crop_regions( class_feature_map, boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]), box_ind=get_box_indices(proposal_boxes), crop_size=self._crop_size, num_spatial_bins=self._num_spatial_bins, global_pool=True) class_predictions_with_background = tf.squeeze( class_predictions_with_background, squeeze_dims=[1, 2]) class_predictions_with_background = tf.reshape( class_predictions_with_background, [batch_size * num_boxes, 1, total_classes]) return {BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background} class MaskRCNNBoxPredictor(BoxPredictor): """Mask R-CNN Box Predictor. See Mask R-CNN: He, K., Gkioxari, G., Dollar, P., & Girshick, R. (2017). Mask R-CNN. arXiv preprint arXiv:1703.06870. This is used for the second stage of the Mask R-CNN detector where proposals cropped from an image are arranged along the batch dimension of the input image_features tensor. Notice that locations are *not* shared across classes, thus for each anchor, a separate prediction is made for each class. In addition to predicting boxes and classes, optionally this class allows predicting masks and/or keypoints inside detection boxes. Currently this box predictor makes per-class predictions; that is, each anchor makes a separate box prediction for each class. """ def __init__(self, is_training, num_classes, fc_hyperparams, use_dropout, dropout_keep_prob, box_code_size, conv_hyperparams=None, predict_instance_masks=False, mask_height=14, mask_width=14, mask_prediction_conv_depth=256, predict_keypoints=False): """Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned classification targets can range from {0,... K}). fc_hyperparams: Slim arg_scope with hyperparameters for fully connected ops. use_dropout: Option to use dropout or not. Note that a single dropout op is applied here prior to both box and class predictions, which stands in contrast to the ConvolutionalBoxPredictor below. dropout_keep_prob: Keep probability for dropout. This is only used if use_dropout is True. box_code_size: Size of encoding for each box. conv_hyperparams: Slim arg_scope with hyperparameters for convolution ops. predict_instance_masks: Whether to predict object masks inside detection boxes. mask_height: Desired output mask height. The default value is 14. mask_width: Desired output mask width. The default value is 14. mask_prediction_conv_depth: The depth for the first conv2d_transpose op applied to the image_features in the mask prediciton branch. predict_keypoints: Whether to predict keypoints insde detection boxes. Raises: ValueError: If predict_instance_masks or predict_keypoints is true. """ super(MaskRCNNBoxPredictor, self).__init__(is_training, num_classes) self._fc_hyperparams = fc_hyperparams self._use_dropout = use_dropout self._box_code_size = box_code_size self._dropout_keep_prob = dropout_keep_prob self._conv_hyperparams = conv_hyperparams self._predict_instance_masks = predict_instance_masks self._mask_height = mask_height self._mask_width = mask_width self._mask_prediction_conv_depth = mask_prediction_conv_depth self._predict_keypoints = predict_keypoints if self._predict_keypoints: raise ValueError('Keypoint prediction is unimplemented.') if ((self._predict_instance_masks or self._predict_keypoints) and self._conv_hyperparams is None): raise ValueError('`conv_hyperparams` must be provided when predicting ' 'masks.') @property def num_classes(self): return self._num_classes def _predict(self, image_features, num_predictions_per_location): """Computes encoded object locations and corresponding confidences. Flattens image_features and applies fully connected ops (with no non-linearity) to predict box encodings and class predictions. In this setting, anchors are not spatially arranged in any way and are assumed to have been folded into the batch dimension. Thus we output 1 for the anchors dimension. Also optionally predicts instance masks. The mask prediction head is based on the Mask RCNN paper with the following modifications: We replace the deconvolution layer with a bilinear resize and a convolution. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. Currently, this must be set to 1, or an error will be raised. Returns: A dictionary containing the following tensors. box_encodings: A float tensor of shape [batch_size, 1, num_classes, code_size] representing the location of the objects. class_predictions_with_background: A float tensor of shape [batch_size, 1, num_classes + 1] representing the class predictions for the proposals. If predict_masks is True the dictionary also contains: instance_masks: A float tensor of shape [batch_size, 1, num_classes, image_height, image_width] If predict_keypoints is True the dictionary also contains: keypoints: [batch_size, 1, num_keypoints, 2] Raises: ValueError: if num_predictions_per_location is not 1. """ if num_predictions_per_location != 1: raise ValueError('Currently FullyConnectedBoxPredictor only supports ' 'predicting a single box per class per location.') spatial_averaged_image_features = tf.reduce_mean(image_features, [1, 2], keep_dims=True, name='AvgPool') flattened_image_features = slim.flatten(spatial_averaged_image_features) if self._use_dropout: flattened_image_features = slim.dropout(flattened_image_features, keep_prob=self._dropout_keep_prob, is_training=self._is_training) with slim.arg_scope(self._fc_hyperparams): box_encodings = slim.fully_connected( flattened_image_features, self._num_classes * self._box_code_size, activation_fn=None, scope='BoxEncodingPredictor') class_predictions_with_background = slim.fully_connected( flattened_image_features, self._num_classes + 1, activation_fn=None, scope='ClassPredictor') box_encodings = tf.reshape( box_encodings, [-1, 1, self._num_classes, self._box_code_size]) class_predictions_with_background = tf.reshape( class_predictions_with_background, [-1, 1, self._num_classes + 1]) predictions_dict = { BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background } if self._predict_instance_masks: with slim.arg_scope(self._conv_hyperparams): upsampled_features = tf.image.resize_bilinear( image_features, [self._mask_height, self._mask_width], align_corners=True) upsampled_features = slim.conv2d( upsampled_features, num_outputs=self._mask_prediction_conv_depth, kernel_size=[2, 2]) mask_predictions = slim.conv2d(upsampled_features, num_outputs=self.num_classes, activation_fn=None, kernel_size=[3, 3]) instance_masks = tf.expand_dims(tf.transpose(mask_predictions, perm=[0, 3, 1, 2]), axis=1, name='MaskPredictor') predictions_dict[MASK_PREDICTIONS] = instance_masks return predictions_dict class ConvolutionalBoxPredictor(BoxPredictor): """Convolutional Box Predictor. Optionally add an intermediate 1x1 convolutional layer after features and predict in parallel branches box_encodings and class_predictions_with_background. Currently this box predictor assumes that predictions are "shared" across classes --- that is each anchor makes box predictions which do not depend on class. """ def __init__(self, is_training, num_classes, conv_hyperparams, min_depth, max_depth, num_layers_before_predictor, use_dropout, dropout_keep_prob, kernel_size, box_code_size, apply_sigmoid_to_scores=False, class_prediction_bias_init=0.0): """Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned classification targets can range from {0,... K}). conv_hyperparams: Slim arg_scope with hyperparameters for convolution ops. min_depth: Minumum feature depth prior to predicting box encodings and class predictions. max_depth: Maximum feature depth prior to predicting box encodings and class predictions. If max_depth is set to 0, no additional feature map will be inserted before location and class predictions. num_layers_before_predictor: Number of the additional conv layers before the predictor. use_dropout: Option to use dropout for class prediction or not. dropout_keep_prob: Keep probability for dropout. This is only used if use_dropout is True. kernel_size: Size of final convolution kernel. If the spatial resolution of the feature map is smaller than the kernel size, then the kernel size is automatically set to be min(feature_width, feature_height). box_code_size: Size of encoding for each box. apply_sigmoid_to_scores: if True, apply the sigmoid on the output class_predictions. class_prediction_bias_init: constant value to initialize bias of the last conv2d layer before class prediction. Raises: ValueError: if min_depth > max_depth. """ super(ConvolutionalBoxPredictor, self).__init__(is_training, num_classes) if min_depth > max_depth: raise ValueError('min_depth should be less than or equal to max_depth') self._conv_hyperparams = conv_hyperparams self._min_depth = min_depth self._max_depth = max_depth self._num_layers_before_predictor = num_layers_before_predictor self._use_dropout = use_dropout self._kernel_size = kernel_size self._box_code_size = box_code_size self._dropout_keep_prob = dropout_keep_prob self._apply_sigmoid_to_scores = apply_sigmoid_to_scores self._class_prediction_bias_init = class_prediction_bias_init def _predict(self, image_features, num_predictions_per_location): """Computes encoded object locations and corresponding confidences. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. Returns: A dictionary containing the following tensors. box_encodings: A float tensor of shape [batch_size, num_anchors, 1, code_size] representing the location of the objects, where num_anchors = feat_height * feat_width * num_predictions_per_location class_predictions_with_background: A float tensor of shape [batch_size, num_anchors, num_classes + 1] representing the class predictions for the proposals. """ # Add a slot for the background class. num_class_slots = self.num_classes + 1 net = image_features with slim.arg_scope(self._conv_hyperparams), \ slim.arg_scope([slim.dropout], is_training=self._is_training): # Add additional conv layers before the class predictor. features_depth = static_shape.get_depth(image_features.get_shape()) depth = max(min(features_depth, self._max_depth), self._min_depth) tf.logging.info('depth of additional conv before box predictor: {}'. format(depth)) if depth > 0 and self._num_layers_before_predictor > 0: for i in range(self._num_layers_before_predictor): net = slim.conv2d( net, depth, [1, 1], scope='Conv2d_%d_1x1_%d' % (i, depth)) with slim.arg_scope([slim.conv2d], activation_fn=None, normalizer_fn=None, normalizer_params=None): box_encodings = slim.conv2d( net, num_predictions_per_location * self._box_code_size, [self._kernel_size, self._kernel_size], scope='BoxEncodingPredictor') if self._use_dropout: net = slim.dropout(net, keep_prob=self._dropout_keep_prob) class_predictions_with_background = slim.conv2d( net, num_predictions_per_location * num_class_slots, [self._kernel_size, self._kernel_size], scope='ClassPredictor', biases_initializer=tf.constant_initializer( self._class_prediction_bias_init)) if self._apply_sigmoid_to_scores: class_predictions_with_background = tf.sigmoid( class_predictions_with_background) combined_feature_map_shape = shape_utils.combined_static_and_dynamic_shape( image_features) box_encodings = tf.reshape( box_encodings, tf.stack([combined_feature_map_shape[0], combined_feature_map_shape[1] * combined_feature_map_shape[2] * num_predictions_per_location, 1, self._box_code_size])) class_predictions_with_background = tf.reshape( class_predictions_with_background, tf.stack([combined_feature_map_shape[0], combined_feature_map_shape[1] * combined_feature_map_shape[2] * num_predictions_per_location, num_class_slots])) return {BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background}
[ "tensorflow.image.resize_bilinear", "tensorflow.transpose", "tensorflow.range", "tensorflow.shape", "tensorflow.reduce_mean", "tensorflow.stack", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.ones", "tensorflow.squeeze", "tensorflow.constant_initializer", "tensorflow.variable_scope" ]
cartoonify/app/object_detection/core/box_predictor.py
[(378, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['image_features', '[1, 2]'], {'keep_dims': '(True)', 'name': '"""AvgPool"""'}), True, 'import tensorflow as tf\n'), (397, 'tensorflow.reshape', 'tf.reshape', (['box_encodings', '[-1, 1, self._num_classes, self._box_code_size]'], {}), True, 'import tensorflow as tf\n'), (399, 'tensorflow.reshape', 'tf.reshape', (['class_predictions_with_background', '[-1, 1, self._num_classes + 1]'], {}), True, 'import tensorflow as tf\n'), (549, 'app.object_detection.utils.shape_utils.combined_static_and_dynamic_shape', 'shape_utils.combined_static_and_dynamic_shape', (['image_features'], {}), False, 'from app.object_detection.utils import shape_utils\n'), (90, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.shape', 'tf.shape', (['proposal_boxes'], {}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.shape', 'tf.shape', (['proposal_boxes'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.ones', 'tf.ones', (['proposals_shape[:2]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.reshape', 'tf.reshape', (['(ones_mat * multiplier)', '[-1]'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.squeeze', 'tf.squeeze', (['box_encodings'], {'squeeze_dims': '[1, 2]'}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.reshape', 'tf.reshape', (['box_encodings', '[batch_size * num_boxes, 1, self.num_classes, self._box_code_size]'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.squeeze', 'tf.squeeze', (['class_predictions_with_background'], {'squeeze_dims': '[1, 2]'}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.reshape', 'tf.reshape', (['class_predictions_with_background', '[batch_size * num_boxes, 1, total_classes]'], {}), True, 'import tensorflow as tf\n'), (552, 'tensorflow.stack', 'tf.stack', (['[combined_feature_map_shape[0], combined_feature_map_shape[1] *\n combined_feature_map_shape[2] * num_predictions_per_location, 1, self.\n _box_code_size]'], {}), True, 'import tensorflow as tf\n'), (559, 'tensorflow.stack', 'tf.stack', (['[combined_feature_map_shape[0], combined_feature_map_shape[1] *\n combined_feature_map_shape[2] * num_predictions_per_location,\n num_class_slots]'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.shape', 'tf.shape', (['proposals'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.range', 'tf.range', ([], {'start': '(0)', 'limit': 'proposals_shape[0]'}), True, 'import tensorflow as tf\n'), (409, 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (['image_features', '[self._mask_height, self._mask_width]'], {'align_corners': '(True)'}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.reshape', 'tf.reshape', (['proposal_boxes', '[-1, self._box_code_size]'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.reshape', 'tf.reshape', (['proposal_boxes', '[-1, self._box_code_size]'], {}), True, 'import tensorflow as tf\n'), (421, 'tensorflow.transpose', 'tf.transpose', (['mask_predictions'], {'perm': '[0, 3, 1, 2]'}), True, 'import tensorflow as tf\n'), (546, 'tensorflow.sigmoid', 'tf.sigmoid', (['class_predictions_with_background'], {}), True, 'import tensorflow as tf\n'), (543, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['self._class_prediction_bias_init'], {}), True, 'import tensorflow as tf\n')]
levskaya/tensor2tensor
4643800137f802693f880a1fab9e10de7ba32e66
# 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. """Data generators for translation data-sets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import os import tarfile import zipfile from tensor2tensor.data_generators import cleaner_en_xx from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.data_generators import text_problems from tensor2tensor.utils import bleu_hook from tensor2tensor.utils import mlperf_log import tensorflow as tf FLAGS = tf.flags.FLAGS class TranslateProblem(text_problems.Text2TextProblem): """Base class for translation problems.""" @property def is_generate_per_split(self): return True @property def approx_vocab_size(self): return 2**15 @property def datatypes_to_clean(self): return None def source_data_files(self, dataset_split): """Files to be passed to compile_data.""" raise NotImplementedError() def vocab_data_files(self): """Files to be passed to get_or_generate_vocab.""" return self.source_data_files(problem.DatasetSplit.TRAIN) def generate_samples( self, data_dir, tmp_dir, dataset_split, custom_iterator=text_problems.text2text_txt_iterator): datasets = self.source_data_files(dataset_split) tag = "dev" datatypes_to_clean = None if dataset_split == problem.DatasetSplit.TRAIN: tag = "train" datatypes_to_clean = self.datatypes_to_clean data_path = compile_data( tmp_dir, datasets, "%s-compiled-%s" % (self.name, tag), datatypes_to_clean=datatypes_to_clean) return custom_iterator(data_path + ".lang1", data_path + ".lang2") def generate_text_for_vocab(self, data_dir, tmp_dir): return generator_utils.generate_lines_for_vocab(tmp_dir, self.vocab_data_files()) @property def decode_hooks(self): return [compute_bleu_summaries] def compute_bleu_summaries(hook_args): """Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file. """ decode_hparams = hook_args.decode_hparams if not (decode_hparams.decode_reference and decode_hparams.decode_to_file): return None values = [] bleu = 100 * bleu_hook.bleu_wrapper( decode_hparams.decode_reference, decode_hparams.decode_to_file) values.append(tf.Summary.Value(tag="BLEU", simple_value=bleu)) tf.logging.info("%s: BLEU = %6.2f" % (decode_hparams.decode_to_file, bleu)) if hook_args.hparams.mlperf_mode: current_step = decode_hparams.mlperf_decode_step mlperf_log.transformer_print( key=mlperf_log.EVAL_TARGET, value=decode_hparams.mlperf_threshold) mlperf_log.transformer_print( key=mlperf_log.EVAL_ACCURACY, value={ "epoch": max(current_step // decode_hparams.iterations_per_loop - 1, 0), "value": bleu }) mlperf_log.transformer_print(key=mlperf_log.EVAL_STOP) if bleu >= decode_hparams.mlperf_threshold: decode_hparams.set_hparam("mlperf_success", True) return values def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<doc") or line.startswith("</doc"): return "" if line.startswith("<p>") or line.startswith("</p>"): return "" # Strip <seg> tags. line = line.strip() if line.startswith("<seg") and line.endswith("</seg>"): i = line.index(">") return line[i + 1:-6] # Strip first <seg ...> and last </seg>. def _clean_sentences(sentence_pairs): res_pairs = [] for cleaned in cleaner_en_xx.clean_en_xx_pairs(sentence_pairs): res_pairs.append(cleaned) return res_pairs def _tmx_to_source_target(tmx_file, source_resfile, target_resfile, do_cleaning=False): source_target_pairs = cleaner_en_xx.paracrawl_v3_pairs(tmx_file) if do_cleaning: source_target_pairs = cleaner_en_xx.clean_en_xx_pairs(source_target_pairs) for source, target in source_target_pairs: source_resfile.write(source) source_resfile.write("\n") target_resfile.write(target) target_resfile.write("\n") def compile_data(tmp_dir, datasets, filename, datatypes_to_clean=None): """Concatenates all `datasets` and saves to `filename`.""" datatypes_to_clean = datatypes_to_clean or [] filename = os.path.join(tmp_dir, filename) lang1_fname = filename + ".lang1" lang2_fname = filename + ".lang2" if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname): tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname, lang2_fname) return filename with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile: with tf.gfile.GFile(lang2_fname, mode="w") as lang2_resfile: for dataset in datasets: url = dataset[0] compressed_filename = os.path.basename(url) compressed_filepath = os.path.join(tmp_dir, compressed_filename) if url.startswith("http"): generator_utils.maybe_download(tmp_dir, compressed_filename, url) if compressed_filename.endswith(".zip"): zipfile.ZipFile(os.path.join(compressed_filepath), "r").extractall(tmp_dir) if dataset[1][0] == "tmx": cleaning_requested = "tmx" in datatypes_to_clean tmx_filename = os.path.join(tmp_dir, dataset[1][1]) if tmx_filename.endswith(".gz"): with gzip.open(tmx_filename, "rb") as tmx_file: _tmx_to_source_target(tmx_file, lang1_resfile, lang2_resfile, do_cleaning=cleaning_requested) else: with tf.gfile.Open(tmx_filename) as tmx_file: _tmx_to_source_target(tmx_file, lang1_resfile, lang2_resfile, do_cleaning=cleaning_requested) elif dataset[1][0] == "tsv": _, src_column, trg_column, glob_pattern = dataset[1] filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern)) if not filenames: # Capture *.tgz and *.tar.gz too. mode = "r:gz" if compressed_filepath.endswith("gz") else "r" with tarfile.open(compressed_filepath, mode) as corpus_tar: corpus_tar.extractall(tmp_dir) filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern)) for tsv_filename in filenames: if tsv_filename.endswith(".gz"): new_filename = tsv_filename.strip(".gz") generator_utils.gunzip_file(tsv_filename, new_filename) tsv_filename = new_filename with tf.gfile.Open(tsv_filename) as tsv_file: for line in tsv_file: if line and "\t" in line: parts = line.split("\t") source, target = parts[src_column], parts[trg_column] source, target = source.strip(), target.strip() clean_pairs = [(source, target)] if "tsv" in datatypes_to_clean: clean_pairs = cleaner_en_xx.clean_en_xx_pairs(clean_pairs) for source, target in clean_pairs: if source and target: lang1_resfile.write(source) lang1_resfile.write("\n") lang2_resfile.write(target) lang2_resfile.write("\n") else: lang1_filename, lang2_filename = dataset[1] lang1_filepath = os.path.join(tmp_dir, lang1_filename) lang2_filepath = os.path.join(tmp_dir, lang2_filename) is_sgm = ( lang1_filename.endswith("sgm") and lang2_filename.endswith("sgm")) if not (tf.gfile.Exists(lang1_filepath) and tf.gfile.Exists(lang2_filepath)): # For .tar.gz and .tgz files, we read compressed. mode = "r:gz" if compressed_filepath.endswith("gz") else "r" with tarfile.open(compressed_filepath, mode) as corpus_tar: corpus_tar.extractall(tmp_dir) if lang1_filepath.endswith(".gz"): new_filepath = lang1_filepath.strip(".gz") generator_utils.gunzip_file(lang1_filepath, new_filepath) lang1_filepath = new_filepath if lang2_filepath.endswith(".gz"): new_filepath = lang2_filepath.strip(".gz") generator_utils.gunzip_file(lang2_filepath, new_filepath) lang2_filepath = new_filepath for example in text_problems.text2text_txt_iterator( lang1_filepath, lang2_filepath): line1res = _preprocess_sgm(example["inputs"], is_sgm) line2res = _preprocess_sgm(example["targets"], is_sgm) clean_pairs = [(line1res, line2res)] if "txt" in datatypes_to_clean: clean_pairs = cleaner_en_xx.clean_en_xx_pairs(clean_pairs) for line1res, line2res in clean_pairs: if line1res and line2res: lang1_resfile.write(line1res) lang1_resfile.write("\n") lang2_resfile.write(line2res) lang2_resfile.write("\n") return filename class TranslateDistillProblem(TranslateProblem): """Base class for translation problems.""" def is_generate_per_split(self): return True def example_reading_spec(self): data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)} if self.has_inputs: data_fields["inputs"] = tf.VarLenFeature(tf.int64) # hack: ignoring true targets and putting dist_targets in targets data_items_to_decoders = { "inputs": tf.contrib.slim.tfexample_decoder.Tensor("inputs"), "targets": tf.contrib.slim.tfexample_decoder.Tensor("dist_targets"), } return (data_fields, data_items_to_decoders) def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored. vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filepath) return encoder def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): generator = self.generate_samples(data_dir, tmp_dir, dataset_split) vocab = self.get_or_create_vocab(data_dir, tmp_dir) # For each example, encode the text and append EOS ID. for sample in generator: if self.has_inputs: sample["inputs"] = vocab.encode(sample["inputs"]) sample["inputs"].append(text_encoder.EOS_ID) sample["targets"] = vocab.encode(sample["targets"]) sample["targets"].append(text_encoder.EOS_ID) sample["dist_targets"] = vocab.encode(sample["dist_targets"]) sample["dist_targets"].append(text_encoder.EOS_ID) yield sample def generate_samples(self, data_dir, tmp_dir, dataset_split): data_path = self.source_data_files(dataset_split) assert tf.gfile.Exists(data_path) return text_problems.text2text_distill_iterator(data_path + "inputs", data_path + "gold", data_path + "prediction")
[ "tensorflow.gfile.Open", "tensorflow.gfile.Exists", "tensorflow.gfile.GFile", "tensorflow.Summary.Value", "tensorflow.logging.info", "tensorflow.contrib.slim.tfexample_decoder.Tensor", "tensorflow.VarLenFeature" ]
tensor2tensor/data_generators/translate.py
[(107, 'tensorflow.logging.info', 'tf.logging.info', (["('%s: BLEU = %6.2f' % (decode_hparams.decode_to_file, bleu))"], {}), True, 'import tensorflow as tf\n'), (147, 'tensor2tensor.data_generators.cleaner_en_xx.clean_en_xx_pairs', 'cleaner_en_xx.clean_en_xx_pairs', (['sentence_pairs'], {}), False, 'from tensor2tensor.data_generators import cleaner_en_xx\n'), (154, 'tensor2tensor.data_generators.cleaner_en_xx.paracrawl_v3_pairs', 'cleaner_en_xx.paracrawl_v3_pairs', (['tmx_file'], {}), False, 'from tensor2tensor.data_generators import cleaner_en_xx\n'), (167, 'os.path.join', 'os.path.join', (['tmp_dir', 'filename'], {}), False, 'import os\n'), (104, 'tensor2tensor.utils.bleu_hook.bleu_wrapper', 'bleu_hook.bleu_wrapper', (['decode_hparams.decode_reference', 'decode_hparams.decode_to_file'], {}), False, 'from tensor2tensor.utils import bleu_hook\n'), (106, 'tensorflow.Summary.Value', 'tf.Summary.Value', ([], {'tag': '"""BLEU"""', 'simple_value': 'bleu'}), True, 'import tensorflow as tf\n'), (110, 'tensor2tensor.utils.mlperf_log.transformer_print', 'mlperf_log.transformer_print', ([], {'key': 'mlperf_log.EVAL_TARGET', 'value': 'decode_hparams.mlperf_threshold'}), False, 'from tensor2tensor.utils import mlperf_log\n'), (119, 'tensor2tensor.utils.mlperf_log.transformer_print', 'mlperf_log.transformer_print', ([], {'key': 'mlperf_log.EVAL_STOP'}), False, 'from tensor2tensor.utils import mlperf_log\n'), (156, 'tensor2tensor.data_generators.cleaner_en_xx.clean_en_xx_pairs', 'cleaner_en_xx.clean_en_xx_pairs', (['source_target_pairs'], {}), False, 'from tensor2tensor.data_generators import cleaner_en_xx\n'), (170, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['lang1_fname'], {}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['lang2_fname'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.logging.info', 'tf.logging.info', (['"""Skipping compile data, found files:\n%s\n%s"""', 'lang1_fname', 'lang2_fname'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['lang1_fname'], {'mode': '"""w"""'}), True, 'import tensorflow as tf\n'), (291, 'os.path.join', 'os.path.join', (['data_dir', 'self.vocab_filename'], {}), False, 'import os\n'), (292, 'tensor2tensor.data_generators.text_encoder.SubwordTextEncoder', 'text_encoder.SubwordTextEncoder', (['vocab_filepath'], {}), False, 'from tensor2tensor.data_generators import text_encoder\n'), (311, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['data_path'], {}), True, 'import tensorflow as tf\n'), (312, 'tensor2tensor.data_generators.text_problems.text2text_distill_iterator', 'text_problems.text2text_distill_iterator', (["(data_path + 'inputs')", "(data_path + 'gold')", "(data_path + 'prediction')"], {}), False, 'from tensor2tensor.data_generators import text_problems\n'), (175, 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['lang2_fname'], {'mode': '"""w"""'}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.VarLenFeature', 'tf.VarLenFeature', (['tf.int64'], {}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.contrib.slim.tfexample_decoder.Tensor', 'tf.contrib.slim.tfexample_decoder.Tensor', (['"""inputs"""'], {}), True, 'import tensorflow as tf\n'), (282, 'tensorflow.contrib.slim.tfexample_decoder.Tensor', 'tf.contrib.slim.tfexample_decoder.Tensor', (['"""dist_targets"""'], {}), True, 'import tensorflow as tf\n'), (178, 'os.path.basename', 'os.path.basename', (['url'], {}), False, 'import os\n'), (179, 'os.path.join', 'os.path.join', (['tmp_dir', 'compressed_filename'], {}), False, 'import os\n'), (181, 'tensor2tensor.data_generators.generator_utils.maybe_download', 'generator_utils.maybe_download', (['tmp_dir', 'compressed_filename', 'url'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (188, 'os.path.join', 'os.path.join', (['tmp_dir', 'dataset[1][1]'], {}), False, 'import os\n'), (230, 'os.path.join', 'os.path.join', (['tmp_dir', 'lang1_filename'], {}), False, 'import os\n'), (231, 'os.path.join', 'os.path.join', (['tmp_dir', 'lang2_filename'], {}), False, 'import os\n'), (250, 'tensor2tensor.data_generators.text_problems.text2text_txt_iterator', 'text_problems.text2text_txt_iterator', (['lang1_filepath', 'lang2_filepath'], {}), False, 'from tensor2tensor.data_generators import text_problems\n'), (190, 'gzip.open', 'gzip.open', (['tmx_filename', '"""rb"""'], {}), False, 'import gzip\n'), (194, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['tmx_filename'], {}), True, 'import tensorflow as tf\n'), (200, 'os.path.join', 'os.path.join', (['tmp_dir', 'glob_pattern'], {}), False, 'import os\n'), (243, 'tensor2tensor.data_generators.generator_utils.gunzip_file', 'generator_utils.gunzip_file', (['lang1_filepath', 'new_filepath'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (247, 'tensor2tensor.data_generators.generator_utils.gunzip_file', 'generator_utils.gunzip_file', (['lang2_filepath', 'new_filepath'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (183, 'os.path.join', 'os.path.join', (['compressed_filepath'], {}), False, 'import os\n'), (204, 'tarfile.open', 'tarfile.open', (['compressed_filepath', 'mode'], {}), False, 'import tarfile\n'), (206, 'os.path.join', 'os.path.join', (['tmp_dir', 'glob_pattern'], {}), False, 'import os\n'), (210, 'tensor2tensor.data_generators.generator_utils.gunzip_file', 'generator_utils.gunzip_file', (['tsv_filename', 'new_filename'], {}), False, 'from tensor2tensor.data_generators import generator_utils\n'), (212, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['tsv_filename'], {}), True, 'import tensorflow as tf\n'), (235, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['lang1_filepath'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['lang2_filepath'], {}), True, 'import tensorflow as tf\n'), (239, 'tarfile.open', 'tarfile.open', (['compressed_filepath', 'mode'], {}), False, 'import tarfile\n'), (256, 'tensor2tensor.data_generators.cleaner_en_xx.clean_en_xx_pairs', 'cleaner_en_xx.clean_en_xx_pairs', (['clean_pairs'], {}), False, 'from tensor2tensor.data_generators import cleaner_en_xx\n'), (220, 'tensor2tensor.data_generators.cleaner_en_xx.clean_en_xx_pairs', 'cleaner_en_xx.clean_en_xx_pairs', (['clean_pairs'], {}), False, 'from tensor2tensor.data_generators import cleaner_en_xx\n')]
fangqyi/garage
ddafba385ef005f46f913ab352f9638760e5b412
"""First order optimizer.""" import time from dowel import logger import pyprind import tensorflow as tf from garage.np.optimizers import BatchDataset from garage.tf.misc import tensor_utils from garage.tf.optimizers.utils import LazyDict class FirstOrderOptimizer: """First order optimier. Performs (stochastic) gradient descent, possibly using fancier methods like ADAM etc. Args: tf_optimizer_cls (tf.Optimizer): Optimizer to be used. tf_optimizer_args (dict): Optimizer arguments. max_epochs (int): Maximum number of epochs for update. tolerance (float): Tolerance for difference in loss during update. batch_size (int): Batch size for optimization. callback (callable): Function to call during each epoch. Default is None. verbose (bool): If true, intermediate log message will be printed. name (str): Name scope of the optimizer. """ def __init__(self, tf_optimizer_cls=None, tf_optimizer_args=None, max_epochs=1000, tolerance=1e-6, batch_size=32, callback=None, verbose=False, name='FirstOrderOptimizer'): self._opt_fun = None self._target = None self._callback = callback if tf_optimizer_cls is None: tf_optimizer_cls = tf.compat.v1.train.AdamOptimizer if tf_optimizer_args is None: tf_optimizer_args = dict(learning_rate=1e-3) self._tf_optimizer = tf_optimizer_cls(**tf_optimizer_args) self._max_epochs = max_epochs self._tolerance = tolerance self._batch_size = batch_size self._verbose = verbose self._input_vars = None self._train_op = None self._name = name def update_opt(self, loss, target, inputs, extra_inputs=None, **kwargs): """Construct operation graph for the optimizer. Args: loss (tf.Tensor): Loss objective to minimize. target (object): Target object to optimize. The object should implemenet `get_params()` and `get_param_values`. inputs (list[tf.Tensor]): List of input placeholders. extra_inputs (list[tf.Tensor]): List of extra input placeholders. kwargs (dict): Extra unused keyword arguments. Some optimizers have extra input, e.g. KL constraint. """ del kwargs with tf.name_scope(self._name): self._target = target self._train_op = self._tf_optimizer.minimize( loss, var_list=target.get_params()) if extra_inputs is None: extra_inputs = list() self._input_vars = inputs + extra_inputs self._opt_fun = LazyDict( f_loss=lambda: tensor_utils.compile_function( inputs + extra_inputs, loss), ) def loss(self, inputs, extra_inputs=None): """The loss. Args: inputs (list[numpy.ndarray]): List of input values. extra_inputs (list[numpy.ndarray]): List of extra input values. Returns: float: Loss. Raises: Exception: If loss function is None, i.e. not defined. """ if self._opt_fun is None: raise Exception( 'Use update_opt() to setup the loss function first.') if extra_inputs is None: extra_inputs = tuple() return self._opt_fun['f_loss'](*(tuple(inputs) + extra_inputs)) # pylint: disable=too-many-branches def optimize(self, inputs, extra_inputs=None, callback=None): """Perform optimization. Args: inputs (list[numpy.ndarray]): List of input values. extra_inputs (list[numpy.ndarray]): List of extra input values. callback (callable): Function to call during each epoch. Default is None. Raises: NotImplementedError: If inputs are invalid. Exception: If loss function is None, i.e. not defined. """ if not inputs: # Assumes that we should always sample mini-batches raise NotImplementedError('No inputs are fed to optimizer.') if self._opt_fun is None: raise Exception( 'Use update_opt() to setup the loss function first.') f_loss = self._opt_fun['f_loss'] if extra_inputs is None: extra_inputs = tuple() last_loss = f_loss(*(tuple(inputs) + extra_inputs)) start_time = time.time() dataset = BatchDataset(inputs, self._batch_size, extra_inputs=extra_inputs) sess = tf.compat.v1.get_default_session() for epoch in range(self._max_epochs): if self._verbose: logger.log('Epoch {}'.format(epoch)) progbar = pyprind.ProgBar(len(inputs[0])) for batch in dataset.iterate(update=True): sess.run(self._train_op, dict(list(zip(self._input_vars, batch)))) if self._verbose: progbar.update(len(batch[0])) if self._verbose: if progbar.active: progbar.stop() new_loss = f_loss(*(tuple(inputs) + extra_inputs)) if self._verbose: logger.log('Epoch: {} | Loss: {}'.format(epoch, new_loss)) if self._callback or callback: elapsed = time.time() - start_time callback_args = dict( loss=new_loss, params=self._target.get_param_values() if self._target else None, itr=epoch, elapsed=elapsed, ) if self._callback: self._callback(callback_args) if callback: callback(**callback_args) if abs(last_loss - new_loss) < self._tolerance: break last_loss = new_loss def __getstate__(self): """Object.__getstate__. Returns: dict: The state to be pickled for the instance. """ new_dict = self.__dict__.copy() del new_dict['_opt_fun'] del new_dict['_tf_optimizer'] del new_dict['_train_op'] del new_dict['_input_vars'] return new_dict def __setstate__(self, state): """Object.__setstate__. Args: state (dict): Unpickled state. """ obj = type(self)() self.__dict__.update(obj.__dict__) self.__dict__.update(state)
[ "tensorflow.compat.v1.get_default_session", "tensorflow.name_scope" ]
src/garage/tf/optimizers/first_order_optimizer.py
[(134, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (136, 'garage.np.optimizers.BatchDataset', 'BatchDataset', (['inputs', 'self._batch_size'], {'extra_inputs': 'extra_inputs'}), False, 'from garage.np.optimizers import BatchDataset\n'), (140, 'tensorflow.compat.v1.get_default_session', 'tf.compat.v1.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.name_scope', 'tf.name_scope', (['self._name'], {}), True, 'import tensorflow as tf\n'), (162, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (81, 'garage.tf.misc.tensor_utils.compile_function', 'tensor_utils.compile_function', (['(inputs + extra_inputs)', 'loss'], {}), False, 'from garage.tf.misc import tensor_utils\n')]
utahnlp/therapist-observer
31eaf9a5c82c6d0f9a62427ac5df030d81547472
import numpy as np import tensorflow as tf import h5py import json import re from .data import UnicodeCharsVocabulary, Batcher DTYPE = 'float32' DTYPE_INT = 'int64' class BidirectionalLanguageModel(object): def __init__( self, options_file, weight_file, use_character_inputs=True, embedding_weight_file=None, max_batch_size=128, ): ''' Creates the language model computational graph and loads weights Two options for input type: (1) To use character inputs (paired with Batcher) pass use_character_inputs=True, and ids_placeholder of shape (None, None, max_characters_per_token) to __call__ (2) To use token ids as input (paired with TokenBatcher), pass use_character_inputs=False and ids_placeholder of shape (None, None) to __call__. In this case, embedding_weight_file is also required input options_file: location of the json formatted file with LM hyperparameters weight_file: location of the hdf5 file with LM weights use_character_inputs: if True, then use character ids as input, otherwise use token ids max_batch_size: the maximum allowable batch size ''' with open(options_file, 'r') as fin: options = json.load(fin) if not use_character_inputs: if embedding_weight_file is None: raise ValueError( "embedding_weight_file is required input with " "not use_character_inputs" ) self._options = options self._weight_file = weight_file self._embedding_weight_file = embedding_weight_file self._use_character_inputs = use_character_inputs self._max_batch_size = max_batch_size self._ops = {} self._graphs = {} def __call__(self, ids_placeholder): ''' Given the input character ids (or token ids), returns a dictionary with tensorflow ops: {'lm_embeddings': embedding_op, 'lengths': sequence_lengths_op, 'mask': op to compute mask} embedding_op computes the LM embeddings and is shape (None, 3, None, 1024) lengths_op computes the sequence lengths and is shape (None, ) mask computes the sequence mask and is shape (None, None) ids_placeholder: a tf.placeholder of type int32. If use_character_inputs=True, it is shape (None, None, max_characters_per_token) and holds the input character ids for a batch If use_character_input=False, it is shape (None, None) and holds the input token ids for a batch ''' if ids_placeholder in self._ops: # have already created ops for this placeholder, just return them ret = self._ops[ids_placeholder] else: # need to create the graph if len(self._ops) == 0: # first time creating the graph, don't reuse variables lm_graph = BidirectionalLanguageModelGraph( self._options, self._weight_file, ids_placeholder, embedding_weight_file=self._embedding_weight_file, use_character_inputs=self._use_character_inputs, max_batch_size=self._max_batch_size) else: with tf.variable_scope('', reuse=True): lm_graph = BidirectionalLanguageModelGraph( self._options, self._weight_file, ids_placeholder, embedding_weight_file=self._embedding_weight_file, use_character_inputs=self._use_character_inputs, max_batch_size=self._max_batch_size) ops = self._build_ops(lm_graph) self._ops[ids_placeholder] = ops self._graphs[ids_placeholder] = lm_graph ret = ops return ret def _build_ops(self, lm_graph): with tf.control_dependencies([lm_graph.update_state_op]): # get the LM embeddings token_embeddings = lm_graph.embedding layers = [ tf.concat([token_embeddings, token_embeddings], axis=2) ] n_lm_layers = len(lm_graph.lstm_outputs['forward']) for i in range(n_lm_layers): layers.append( tf.concat( [lm_graph.lstm_outputs['forward'][i], lm_graph.lstm_outputs['backward'][i]], axis=-1 ) ) # The layers include the BOS/EOS tokens. Remove them sequence_length_wo_bos_eos = lm_graph.sequence_lengths - 2 layers_without_bos_eos = [] for layer in layers: layer_wo_bos_eos = layer[:, 1:, :] layer_wo_bos_eos = tf.reverse_sequence( layer_wo_bos_eos, lm_graph.sequence_lengths - 1, seq_axis=1, batch_axis=0, ) layer_wo_bos_eos = layer_wo_bos_eos[:, 1:, :] layer_wo_bos_eos = tf.reverse_sequence( layer_wo_bos_eos, sequence_length_wo_bos_eos, seq_axis=1, batch_axis=0, ) layers_without_bos_eos.append(layer_wo_bos_eos) # concatenate the layers lm_embeddings = tf.concat( [tf.expand_dims(t, axis=1) for t in layers_without_bos_eos], axis=1 ) # get the mask op without bos/eos. # tf doesn't support reversing boolean tensors, so cast # to int then back mask_wo_bos_eos = tf.cast(lm_graph.mask[:, 1:], 'int32') mask_wo_bos_eos = tf.reverse_sequence( mask_wo_bos_eos, lm_graph.sequence_lengths - 1, seq_axis=1, batch_axis=0, ) mask_wo_bos_eos = mask_wo_bos_eos[:, 1:] mask_wo_bos_eos = tf.reverse_sequence( mask_wo_bos_eos, sequence_length_wo_bos_eos, seq_axis=1, batch_axis=0, ) mask_wo_bos_eos = tf.cast(mask_wo_bos_eos, 'bool') return { 'lm_embeddings': lm_embeddings, 'lengths': sequence_length_wo_bos_eos, 'token_embeddings': lm_graph.embedding, 'mask': mask_wo_bos_eos, } def _pretrained_initializer(varname, weight_file, embedding_weight_file=None): ''' We'll stub out all the initializers in the pretrained LM with a function that loads the weights from the file ''' weight_name_map = {} for i in range(2): for j in range(8): # if we decide to add more layers root = 'RNN_{}/RNN/MultiRNNCell/Cell{}'.format(i, j) weight_name_map[root + '/rnn/lstm_cell/kernel'] = \ root + '/LSTMCell/W_0' weight_name_map[root + '/rnn/lstm_cell/bias'] = \ root + '/LSTMCell/B' weight_name_map[root + '/rnn/lstm_cell/projection/kernel'] = \ root + '/LSTMCell/W_P_0' # convert the graph name to that in the checkpoint varname_in_file = varname[5:] if varname_in_file.startswith('RNN'): varname_in_file = weight_name_map[varname_in_file] if varname_in_file == 'embedding': with h5py.File(embedding_weight_file, 'r') as fin: # Have added a special 0 index for padding not present # in the original model. embed_weights = fin[varname_in_file][...] weights = np.zeros( (embed_weights.shape[0] + 1, embed_weights.shape[1]), dtype=DTYPE ) weights[1:, :] = embed_weights else: with h5py.File(weight_file, 'r') as fin: if varname_in_file == 'char_embed': # Have added a special 0 index for padding not present # in the original model. char_embed_weights = fin[varname_in_file][...] weights = np.zeros( (char_embed_weights.shape[0] + 1, char_embed_weights.shape[1]), dtype=DTYPE ) weights[1:, :] = char_embed_weights else: weights = fin[varname_in_file][...] # Tensorflow initializers are callables that accept a shape parameter # and some optional kwargs def ret(shape, **kwargs): if list(shape) != list(weights.shape): raise ValueError( "Invalid shape initializing {0}, got {1}, expected {2}".format( varname_in_file, shape, weights.shape) ) return weights return ret class BidirectionalLanguageModelGraph(object): ''' Creates the computational graph and holds the ops necessary for runnint a bidirectional language model ''' def __init__(self, options, weight_file, ids_placeholder, use_character_inputs=True, embedding_weight_file=None, max_batch_size=128): self.options = options self._max_batch_size = max_batch_size self.ids_placeholder = ids_placeholder self.use_character_inputs = use_character_inputs # this custom_getter will make all variables not trainable and # override the default initializer def custom_getter(getter, name, *args, **kwargs): kwargs['trainable'] = False kwargs['initializer'] = _pretrained_initializer( name, weight_file, embedding_weight_file ) return getter(name, *args, **kwargs) if embedding_weight_file is not None: # get the vocab size with h5py.File(embedding_weight_file, 'r') as fin: # +1 for padding self._n_tokens_vocab = fin['embedding'].shape[0] + 1 else: self._n_tokens_vocab = None with tf.variable_scope('bilm', custom_getter=custom_getter): self._build() def _build(self): if self.use_character_inputs: self._build_word_char_embeddings() else: self._build_word_embeddings() self._build_lstms() def _build_word_char_embeddings(self): ''' options contains key 'char_cnn': { 'n_characters': 262, # includes the start / end characters 'max_characters_per_token': 50, 'filters': [ [1, 32], [2, 32], [3, 64], [4, 128], [5, 256], [6, 512], [7, 512] ], 'activation': 'tanh', # for the character embedding 'embedding': {'dim': 16} # for highway layers # if omitted, then no highway layers 'n_highway': 2, } ''' projection_dim = self.options['lstm']['projection_dim'] cnn_options = self.options['char_cnn'] filters = cnn_options['filters'] n_filters = sum(f[1] for f in filters) max_chars = cnn_options['max_characters_per_token'] char_embed_dim = cnn_options['embedding']['dim'] n_chars = cnn_options['n_characters'] if n_chars != 262: raise InvalidNumberOfCharacters( "Set n_characters=262 after training see the README.md" ) if cnn_options['activation'] == 'tanh': activation = tf.nn.tanh elif cnn_options['activation'] == 'relu': activation = tf.nn.relu # the character embeddings with tf.device("/cpu:0"): self.embedding_weights = tf.get_variable( "char_embed", [n_chars, char_embed_dim], dtype=DTYPE, initializer=tf.random_uniform_initializer(-1.0, 1.0) ) # shape (batch_size, unroll_steps, max_chars, embed_dim) self.char_embedding = tf.nn.embedding_lookup(self.embedding_weights, self.ids_placeholder) # the convolutions def make_convolutions(inp): with tf.variable_scope('CNN') as scope: convolutions = [] for i, (width, num) in enumerate(filters): if cnn_options['activation'] == 'relu': # He initialization for ReLU activation # with char embeddings init between -1 and 1 #w_init = tf.random_normal_initializer( # mean=0.0, # stddev=np.sqrt(2.0 / (width * char_embed_dim)) #) # Kim et al 2015, +/- 0.05 w_init = tf.random_uniform_initializer( minval=-0.05, maxval=0.05) elif cnn_options['activation'] == 'tanh': # glorot init w_init = tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / (width * char_embed_dim)) ) w = tf.get_variable( "W_cnn_%s" % i, [1, width, char_embed_dim, num], initializer=w_init, dtype=DTYPE) b = tf.get_variable( "b_cnn_%s" % i, [num], dtype=DTYPE, initializer=tf.constant_initializer(0.0)) conv = tf.nn.conv2d( inp, w, strides=[1, 1, 1, 1], padding="VALID") + b # now max pool conv = tf.nn.max_pool( conv, [1, 1, max_chars-width+1, 1], [1, 1, 1, 1], 'VALID') # activation conv = activation(conv) conv = tf.squeeze(conv, squeeze_dims=[2]) convolutions.append(conv) return tf.concat(convolutions, 2) embedding = make_convolutions(self.char_embedding) # for highway and projection layers n_highway = cnn_options.get('n_highway') use_highway = n_highway is not None and n_highway > 0 use_proj = n_filters != projection_dim if use_highway or use_proj: # reshape from (batch_size, n_tokens, dim) to (-1, dim) batch_size_n_tokens = tf.shape(embedding)[0:2] embedding = tf.reshape(embedding, [-1, n_filters]) # set up weights for projection if use_proj: assert n_filters > projection_dim with tf.variable_scope('CNN_proj') as scope: W_proj_cnn = tf.get_variable( "W_proj", [n_filters, projection_dim], initializer=tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / n_filters)), dtype=DTYPE) b_proj_cnn = tf.get_variable( "b_proj", [projection_dim], initializer=tf.constant_initializer(0.0), dtype=DTYPE) # apply highways layers def high(x, ww_carry, bb_carry, ww_tr, bb_tr): carry_gate = tf.nn.sigmoid(tf.matmul(x, ww_carry) + bb_carry) transform_gate = tf.nn.relu(tf.matmul(x, ww_tr) + bb_tr) return carry_gate * transform_gate + (1.0 - carry_gate) * x if use_highway: highway_dim = n_filters for i in range(n_highway): with tf.variable_scope('CNN_high_%s' % i) as scope: W_carry = tf.get_variable( 'W_carry', [highway_dim, highway_dim], # glorit init initializer=tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / highway_dim)), dtype=DTYPE) b_carry = tf.get_variable( 'b_carry', [highway_dim], initializer=tf.constant_initializer(-2.0), dtype=DTYPE) W_transform = tf.get_variable( 'W_transform', [highway_dim, highway_dim], initializer=tf.random_normal_initializer( mean=0.0, stddev=np.sqrt(1.0 / highway_dim)), dtype=DTYPE) b_transform = tf.get_variable( 'b_transform', [highway_dim], initializer=tf.constant_initializer(0.0), dtype=DTYPE) embedding = high(embedding, W_carry, b_carry, W_transform, b_transform) # finally project down if needed if use_proj: embedding = tf.matmul(embedding, W_proj_cnn) + b_proj_cnn # reshape back to (batch_size, tokens, dim) if use_highway or use_proj: shp = tf.concat([batch_size_n_tokens, [projection_dim]], axis=0) embedding = tf.reshape(embedding, shp) # at last assign attributes for remainder of the model self.embedding = embedding def _build_word_embeddings(self): projection_dim = self.options['lstm']['projection_dim'] # the word embeddings with tf.device("/cpu:0"): self.embedding_weights = tf.get_variable( "embedding", [self._n_tokens_vocab, projection_dim], dtype=DTYPE, ) self.embedding = tf.nn.embedding_lookup(self.embedding_weights, self.ids_placeholder) def _build_lstms(self): # now the LSTMs # these will collect the initial states for the forward # (and reverse LSTMs if we are doing bidirectional) # parse the options lstm_dim = self.options['lstm']['dim'] projection_dim = self.options['lstm']['projection_dim'] n_lstm_layers = self.options['lstm'].get('n_layers', 1) cell_clip = self.options['lstm'].get('cell_clip') proj_clip = self.options['lstm'].get('proj_clip') use_skip_connections = self.options['lstm']['use_skip_connections'] if use_skip_connections: print("USING SKIP CONNECTIONS") else: print("NOT USING SKIP CONNECTIONS") # the sequence lengths from input mask if self.use_character_inputs: mask = tf.reduce_any(self.ids_placeholder > 0, axis=2) else: mask = self.ids_placeholder > 0 sequence_lengths = tf.reduce_sum(tf.cast(mask, tf.int32), axis=1) batch_size = tf.shape(sequence_lengths)[0] # for each direction, we'll store tensors for each layer self.lstm_outputs = {'forward': [], 'backward': []} self.lstm_state_sizes = {'forward': [], 'backward': []} self.lstm_init_states = {'forward': [], 'backward': []} self.lstm_final_states = {'forward': [], 'backward': []} update_ops = [] for direction in ['forward', 'backward']: if direction == 'forward': layer_input = self.embedding else: layer_input = tf.reverse_sequence( self.embedding, sequence_lengths, seq_axis=1, batch_axis=0 ) for i in range(n_lstm_layers): if projection_dim < lstm_dim: # are projecting down output lstm_cell = tf.nn.rnn_cell.LSTMCell( lstm_dim, num_proj=projection_dim, cell_clip=cell_clip, proj_clip=proj_clip) else: lstm_cell = tf.nn.rnn_cell.LSTMCell( lstm_dim, cell_clip=cell_clip, proj_clip=proj_clip) if use_skip_connections: # ResidualWrapper adds inputs to outputs if i == 0: # don't add skip connection from token embedding to # 1st layer output pass else: # add a skip connection lstm_cell = tf.nn.rnn_cell.ResidualWrapper(lstm_cell) # collect the input state, run the dynamic rnn, collect # the output state_size = lstm_cell.state_size # the LSTMs are stateful. To support multiple batch sizes, # we'll allocate size for states up to max_batch_size, # then use the first batch_size entries for each batch init_states = [ tf.Variable( tf.zeros([self._max_batch_size, dim]), trainable=False ) for dim in lstm_cell.state_size ] batch_init_states = [ state[:batch_size, :] for state in init_states ] if direction == 'forward': i_direction = 0 else: i_direction = 1 variable_scope_name = 'RNN_{0}/RNN/MultiRNNCell/Cell{1}'.format( i_direction, i) with tf.variable_scope(variable_scope_name): layer_output, final_state = tf.nn.dynamic_rnn( lstm_cell, layer_input, sequence_length=sequence_lengths, initial_state=tf.nn.rnn_cell.LSTMStateTuple( *batch_init_states), ) self.lstm_state_sizes[direction].append(lstm_cell.state_size) self.lstm_init_states[direction].append(init_states) self.lstm_final_states[direction].append(final_state) if direction == 'forward': self.lstm_outputs[direction].append(layer_output) else: self.lstm_outputs[direction].append( tf.reverse_sequence( layer_output, sequence_lengths, seq_axis=1, batch_axis=0 ) ) with tf.control_dependencies([layer_output]): # update the initial states for i in range(2): new_state = tf.concat( [final_state[i][:batch_size, :], init_states[i][batch_size:, :]], axis=0) state_update_op = tf.assign(init_states[i], new_state) update_ops.append(state_update_op) layer_input = layer_output self.mask = mask self.sequence_lengths = sequence_lengths self.update_state_op = tf.group(*update_ops) def dump_token_embeddings(vocab_file, options_file, weight_file, outfile): ''' Given an input vocabulary file, dump all the token embeddings to the outfile. The result can be used as the embedding_weight_file when constructing a BidirectionalLanguageModel. ''' with open(options_file, 'r') as fin: options = json.load(fin) max_word_length = options['char_cnn']['max_characters_per_token'] vocab = UnicodeCharsVocabulary(vocab_file, max_word_length) batcher = Batcher(vocab_file, max_word_length) ids_placeholder = tf.placeholder('int32', shape=(None, None, max_word_length) ) model = BidirectionalLanguageModel(options_file, weight_file) embedding_op = model(ids_placeholder)['token_embeddings'] n_tokens = vocab.size embed_dim = int(embedding_op.shape[2]) embeddings = np.zeros((n_tokens, embed_dim), dtype=DTYPE) config = tf.ConfigProto(allow_soft_placement=True) with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) for k in range(n_tokens): token = vocab.id_to_word(k) char_ids = batcher.batch_sentences([[token]])[0, 1, :].reshape( 1, 1, -1) embeddings[k, :] = sess.run( embedding_op, feed_dict={ids_placeholder: char_ids} ) with h5py.File(outfile, 'w') as fout: ds = fout.create_dataset( 'embedding', embeddings.shape, dtype='float32', data=embeddings ) def dump_bilm_embeddings(vocab_file, dataset_file, options_file, weight_file, outfile): with open(options_file, 'r') as fin: options = json.load(fin) max_word_length = options['char_cnn']['max_characters_per_token'] vocab = UnicodeCharsVocabulary(vocab_file, max_word_length) batcher = Batcher(vocab_file, max_word_length) ids_placeholder = tf.placeholder('int32', shape=(None, None, max_word_length) ) model = BidirectionalLanguageModel(options_file, weight_file) ops = model(ids_placeholder) config = tf.ConfigProto(allow_soft_placement=True) with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) sentence_id = 0 with open(dataset_file, 'r') as fin, h5py.File(outfile, 'w') as fout: for line in fin: sentence = line.strip().split() char_ids = batcher.batch_sentences([sentence]) embeddings = sess.run( ops['lm_embeddings'], feed_dict={ids_placeholder: char_ids} ) ds = fout.create_dataset( '{}'.format(sentence_id), embeddings.shape[1:], dtype='float32', data=embeddings[0, :, :, :] ) sentence_id += 1
[ "tensorflow.device", "tensorflow.get_variable", "tensorflow.concat", "numpy.sqrt", "tensorflow.control_dependencies", "tensorflow.nn.rnn_cell.ResidualWrapper", "tensorflow.nn.max_pool", "tensorflow.zeros", "tensorflow.nn.rnn_cell.LSTMStateTuple", "tensorflow.cast", "tensorflow.group", "tensorflow.nn.conv2d", "tensorflow.random_uniform_initializer", "tensorflow.squeeze", "tensorflow.ConfigProto", "tensorflow.Session", "numpy.zeros", "tensorflow.matmul", "tensorflow.shape", "tensorflow.reduce_any", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.reverse_sequence", "tensorflow.nn.embedding_lookup", "tensorflow.nn.rnn_cell.LSTMCell", "tensorflow.reshape", "tensorflow.assign", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.variable_scope" ]
tensorflow/classes/bilm/model.py
[(616, 'tensorflow.placeholder', 'tf.placeholder', (['"""int32"""'], {'shape': '(None, None, max_word_length)'}), True, 'import tensorflow as tf\n'), (625, 'numpy.zeros', 'np.zeros', (['(n_tokens, embed_dim)'], {'dtype': 'DTYPE'}), True, 'import numpy as np\n'), (627, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), True, 'import tensorflow as tf\n'), (652, 'tensorflow.placeholder', 'tf.placeholder', (['"""int32"""'], {'shape': '(None, None, max_word_length)'}), True, 'import tensorflow as tf\n'), (658, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), True, 'import tensorflow as tf\n'), (600, 'tensorflow.group', 'tf.group', (['*update_ops'], {}), True, 'import tensorflow as tf\n'), (610, 'json.load', 'json.load', (['fin'], {}), False, 'import json\n'), (628, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (638, 'h5py.File', 'h5py.File', (['outfile', '"""w"""'], {}), False, 'import h5py\n'), (646, 'json.load', 'json.load', (['fin'], {}), False, 'import json\n'), (659, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (44, 'json.load', 'json.load', (['fin'], {}), False, 'import json\n'), (116, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[lm_graph.update_state_op]'], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.cast', 'tf.cast', (['lm_graph.mask[:, 1:]', '"""int32"""'], {}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['mask_wo_bos_eos', '(lm_graph.sequence_lengths - 1)'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['mask_wo_bos_eos', 'sequence_length_wo_bos_eos'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.cast', 'tf.cast', (['mask_wo_bos_eos', '"""bool"""'], {}), True, 'import tensorflow as tf\n'), (208, 'h5py.File', 'h5py.File', (['embedding_weight_file', '"""r"""'], {}), False, 'import h5py\n'), (212, 'numpy.zeros', 'np.zeros', (['(embed_weights.shape[0] + 1, embed_weights.shape[1])'], {'dtype': 'DTYPE'}), True, 'import numpy as np\n'), (218, 'h5py.File', 'h5py.File', (['weight_file', '"""r"""'], {}), False, 'import h5py\n'), (276, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""bilm"""'], {'custom_getter': 'custom_getter'}), True, 'import tensorflow as tf\n'), (332, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embedding_weights', 'self.ids_placeholder'], {}), True, 'import tensorflow as tf\n'), (388, 'tensorflow.concat', 'tf.concat', (['convolutions', '(2)'], {}), True, 'import tensorflow as tf\n'), (400, 'tensorflow.reshape', 'tf.reshape', (['embedding', '[-1, n_filters]'], {}), True, 'import tensorflow as tf\n'), (456, 'tensorflow.concat', 'tf.concat', (['[batch_size_n_tokens, [projection_dim]]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (457, 'tensorflow.reshape', 'tf.reshape', (['embedding', 'shp'], {}), True, 'import tensorflow as tf\n'), (467, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (468, 'tensorflow.get_variable', 'tf.get_variable', (['"""embedding"""', '[self._n_tokens_vocab, projection_dim]'], {'dtype': 'DTYPE'}), True, 'import tensorflow as tf\n'), (472, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embedding_weights', 'self.ids_placeholder'], {}), True, 'import tensorflow as tf\n'), (495, 'tensorflow.reduce_any', 'tf.reduce_any', (['(self.ids_placeholder > 0)'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (498, 'tensorflow.cast', 'tf.cast', (['mask', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (499, 'tensorflow.shape', 'tf.shape', (['sequence_lengths'], {}), True, 'import tensorflow as tf\n'), (629, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (660, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (662, 'h5py.File', 'h5py.File', (['outfile', '"""w"""'], {}), False, 'import h5py\n'), (120, 'tensorflow.concat', 'tf.concat', (['[token_embeddings, token_embeddings]'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['layer_wo_bos_eos', '(lm_graph.sequence_lengths - 1)'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['layer_wo_bos_eos', 'sequence_length_wo_bos_eos'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (223, 'numpy.zeros', 'np.zeros', (['(char_embed_weights.shape[0] + 1, char_embed_weights.shape[1])'], {'dtype': 'DTYPE'}), True, 'import numpy as np\n'), (270, 'h5py.File', 'h5py.File', (['embedding_weight_file', '"""r"""'], {}), False, 'import h5py\n'), (344, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""CNN"""'], {}), True, 'import tensorflow as tf\n'), (399, 'tensorflow.shape', 'tf.shape', (['embedding'], {}), True, 'import tensorflow as tf\n'), (405, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""CNN_proj"""'], {}), True, 'import tensorflow as tf\n'), (452, 'tensorflow.matmul', 'tf.matmul', (['embedding', 'W_proj_cnn'], {}), True, 'import tensorflow as tf\n'), (512, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['self.embedding', 'sequence_lengths'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.variable_scope', 'tf.variable_scope', (['""""""'], {'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.concat', 'tf.concat', (["[lm_graph.lstm_outputs['forward'][i], lm_graph.lstm_outputs['backward'][i]]"], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.expand_dims', 'tf.expand_dims', (['t'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(-1.0)', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (364, 'tensorflow.get_variable', 'tf.get_variable', (["('W_cnn_%s' % i)", '[1, width, char_embed_dim, num]'], {'initializer': 'w_init', 'dtype': 'DTYPE'}), True, 'import tensorflow as tf\n'), (378, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['conv', '[1, 1, max_chars - width + 1, 1]', '[1, 1, 1, 1]', '"""VALID"""'], {}), True, 'import tensorflow as tf\n'), (384, 'tensorflow.squeeze', 'tf.squeeze', (['conv'], {'squeeze_dims': '[2]'}), True, 'import tensorflow as tf\n'), (418, 'tensorflow.matmul', 'tf.matmul', (['x', 'ww_carry'], {}), True, 'import tensorflow as tf\n'), (419, 'tensorflow.matmul', 'tf.matmul', (['x', 'ww_tr'], {}), True, 'import tensorflow as tf\n'), (426, 'tensorflow.variable_scope', 'tf.variable_scope', (["('CNN_high_%s' % i)"], {}), True, 'import tensorflow as tf\n'), (522, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', (['lstm_dim'], {'num_proj': 'projection_dim', 'cell_clip': 'cell_clip', 'proj_clip': 'proj_clip'}), True, 'import tensorflow as tf\n'), (526, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', (['lstm_dim'], {'cell_clip': 'cell_clip', 'proj_clip': 'proj_clip'}), True, 'import tensorflow as tf\n'), (563, 'tensorflow.variable_scope', 'tf.variable_scope', (['variable_scope_name'], {}), True, 'import tensorflow as tf\n'), (587, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[layer_output]'], {}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', ([], {'minval': '(-0.05)', 'maxval': '(0.05)'}), True, 'import tensorflow as tf\n'), (373, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['inp', 'w'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (413, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (538, 'tensorflow.nn.rnn_cell.ResidualWrapper', 'tf.nn.rnn_cell.ResidualWrapper', (['lstm_cell'], {}), True, 'import tensorflow as tf\n'), (548, 'tensorflow.zeros', 'tf.zeros', (['[self._max_batch_size, dim]'], {}), True, 'import tensorflow as tf\n'), (579, 'tensorflow.reverse_sequence', 'tf.reverse_sequence', (['layer_output', 'sequence_lengths'], {'seq_axis': '(1)', 'batch_axis': '(0)'}), True, 'import tensorflow as tf\n'), (590, 'tensorflow.concat', 'tf.concat', (['[final_state[i][:batch_size, :], init_states[i][batch_size:, :]]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (593, 'tensorflow.assign', 'tf.assign', (['init_states[i]', 'new_state'], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (435, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(-2.0)'], {}), True, 'import tensorflow as tf\n'), (444, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (568, 'tensorflow.nn.rnn_cell.LSTMStateTuple', 'tf.nn.rnn_cell.LSTMStateTuple', (['*batch_init_states'], {}), True, 'import tensorflow as tf\n'), (409, 'numpy.sqrt', 'np.sqrt', (['(1.0 / n_filters)'], {}), True, 'import numpy as np\n'), (362, 'numpy.sqrt', 'np.sqrt', (['(1.0 / (width * char_embed_dim))'], {}), True, 'import numpy as np\n'), (431, 'numpy.sqrt', 'np.sqrt', (['(1.0 / highway_dim)'], {}), True, 'import numpy as np\n'), (440, 'numpy.sqrt', 'np.sqrt', (['(1.0 / highway_dim)'], {}), True, 'import numpy as np\n')]
rist-ro/argo
a10c33346803239db8a64c104db7f22ec4e05bef
import os from abc import abstractmethod import numpy as np import tensorflow as tf from datasets.Dataset import Dataset, TRAIN_LOOP from .ArgoLauncher import ArgoLauncher from .DeepLearningModel import DeepLearningModel from .hooks.ArgoHook import STEPS, EPOCHS from .hooks.LoggingMeanTensorsHook import LoggingMeanTensorsHook from .hooks.CheckpointSaverHook import CheckpointSaverHook from .hooks.ImagesInputHook import ImagesInputHook from .hooks.FisherMatrixHook import FisherMatrixHook from .Regularizers import Regularizers from .optimizers.NaturalGradientOptimizer import NaturalGradientOptimizer from .argoLogging import get_logger from .utils.argo_utils import AC_REGULARIZATION, load_class, load_module, get_clipping_id, eval_method_from_tuple, \ NUMTOL, CUSTOM_REGULARIZATION from itertools import chain import importlib import pdb tf_logging = get_logger() from .optimizers.TFOptimizers import TFOptimizers def load_model(conf_file, global_step=None, dataset=None, gpu=0, seed=0, model_class_base_path='', monitorSession=True): """Load a TFDeepLearningModel and optionally save its network Args: conf_file (str): the conf file of the model where to find the experiment. dataset (datasets.Dataset): (optional) the argo Dataset of the model for the training. If not passed it will be reloaded. global_step (int): the global step to load the checkpoint (if None the last checkpoint present will be loaded). gpu (int) : the gpu on which the model will create the session seed (int) : the seed that the model will set model_class_base_path (str): the base path where to look for the model class Returns: TFDeepLearningModel: The loaded Argo TFDeepLearningModel. datasets.Dataset: the argo Dataset of the model for the training. """ dataset_conf, model_parameters, config = ArgoLauncher.process_conf_file(conf_file) if not dataset: dataset = Dataset.load_dataset(dataset_conf) ArgoTFDeepLearningModelClass = load_class(model_parameters["model"], base_path=model_class_base_path) update_model_params(model_parameters, dataset) # baseDir = config["dirName"]+"/"+dataset.id model_dir = os.path.split(os.path.dirname(conf_file))[0] model = ArgoTFDeepLearningModelClass(model_parameters, model_dir, gpu=gpu, seed=seed) model.init(dataset) # network = model._network # network.init_saver() model.create_session(model_parameters, config, monitorSession=monitorSession) #if global_step is None it will restore the last checkpoint in the folder model._checkpoint_dir, you can pass global_step to restore a particular chackpoint model.restore(global_step = global_step) # if save_net: # sess = model.get_raw_session() # # if network_dir: # path = network_dir+"/"+get_full_id(dataset, model)+'/'+network.name # else: # path = model.dirName+'/networks/'+network.name # # network.save(sess, path, global_step=global_step) return model, dataset def load_model_without_session(conf_file, global_step=None, dataset=None, gpu=0, seed=0, model_class_base_path=''): """Load a TFDeepLearningModel without session Args: conf_file (str): the conf file of the model where to find the experiment. dataset (datasets.Dataset): (optional) the argo Dataset of the model for the training. If not passed it will be reloaded. global_step (int): the global step to load the checkpoint (if None the last checkpoint present will be loaded). gpu (int) : the gpu on which the model will create the session seed (int) : the seed that the model will set model_class_base_path (str): the base path where to look for the model class Returns: TFDeepLearningModel: The loaded Argo TFDeepLearningModel. datasets.Dataset: the argo Dataset of the model for the training. """ dataset_conf, model_parameters, config = ArgoLauncher.process_conf_file(conf_file) if not dataset: dataset = Dataset.load_dataset(dataset_conf) ArgoTFDeepLearningModelClass = load_class(model_parameters["model"], base_path=model_class_base_path) update_model_params(model_parameters, dataset) # baseDir = config["dirName"]+"/"+dataset.id model_dir = os.path.split(os.path.dirname(conf_file))[0] model = ArgoTFDeepLearningModelClass(model_parameters, model_dir, gpu=gpu, seed=seed) model.init(dataset) # network = model._network # network.init_saver() checkpoint_name = model.checkpoint_name(global_step) return model, dataset, checkpoint_name def load_network(ArgoTFDeepLearningModelClass, conf_file, dataset, global_step=None): """Load the network of a specific model and the corresponding checkpoint. The Network needs to be applied (to generate the variables, that are instantiated in the _build of Sonnet) and then restored from the checkpoint. e.g. ``` network, checkpoint_name = load_network(ClassificationModel, model_dir, dataset, model_params, config) logits = network(x) network.restore(sess, checkpoint_name) ``` Args: ArgoTFDeepLearningModelClass (Class): the TFDeepLearningModel class to load. conf_file (str): the conf file of the model where to find the experiment. dataset (datasets.Dataset): (optional) the argo Dataset of the model for the training. If not passed it will be reloaded. global_step (int): (optional) the global step to load the checkpoint (if None the last checkpoint present will be loaded). Returns: ArgoAbstractNetwork: the Argo Network to load str: checkpoint_name """ dataset_conf, model_parameters, config = ArgoLauncher.process_conf_file(conf_file) # parallelism = 0 # 0 is equivalent to single # if dataset is not None: # print("load_network: `dataset` IS DEPRECATED, will be removed soon") # if model_class_base_path is not '': # print("load_network: `model_class_base_path` IS DEPRECATED, will be removed soon") # update_model_params(model_parameters, dataset) model_dir = os.path.split(os.path.dirname(conf_file))[0] model = ArgoTFDeepLearningModelClass(model_parameters, model_dir) network = model._network checkpoint_name = model.checkpoint_name(global_step) return network, checkpoint_name def update_model_params(model_parameters, dataset): try: output_shape = dataset.y_shape except ValueError: output_shape = None dataset_info = {"output_shape": output_shape, "input_shape": dataset.x_shape_train} model_parameters.update(dataset_info) class TFDeepLearningModel(DeepLearningModel): default_params= { **DeepLearningModel.default_params, "stochastic" : 1, # add Gaussian noise to the dataset "stochastic_noise_param" : 0, # variance of the noise added to the dataset #TODO never rescale # "rescale" : 0., # rescale inputs in [rescale, 1-rescale] (for numerical issues) "optimizer": ("AdamOptimizer", {"learning_rate" : 0.001, "beta1": 0.9, "beta2":0.999}), "regularizers" : {}, "grad_clipping" : (None, {}), #"natural_gradient" : [0], "batch_size_train" : 128, "batch_size_eval" : 512, } def create_id(self): _id = '-st' + str(self._opts["stochastic"]) +\ '-stp' + str(self._opts["stochastic_noise_param"]) + \ '-bs' + str(self._opts["batch_size_train"]) + \ '-tr' + TFOptimizers.create_id(self._opts["optimizer"]) + \ '-c' + get_clipping_id(self._opts["grad_clipping"]) if "note" in self._opts: _id += '-N' + self._opts["note"] if "pretrained_checkpoint" in self._opts: longname = os.path.abspath(self._opts["pretrained_checkpoint"]) shortname = "".join([i[0] for i in longname.split("/")[1:]]) _id += '-PC' + shortname super_id = super().create_id() _id += super_id return _id def __init__(self, opts, dirName, check_ops = False, gpu=-1, seed=0): # this needs to be called before the parent constructor #self._regularizers = opts.get("regularizers", {}) #pdb.set_trace() super().__init__(opts, dirName, seed) # moved up the hierarchy # self.dirName = dirName + "/" + self._id self._check_ops = check_ops self._numerics_ops = None self._gpu = gpu self.sess = None self._saver = None self.global_step = None tf.set_random_seed(seed) #restore checkpoint self._restore_chkptfile = (None if "pretrained_checkpoint" not in self._opts else self._opts["pretrained_checkpoint"]) #checkpoints self._checkpoint_dir = self.dirName + "/saved_models/" #tensorboard self._tensorboard_dir = self.dirName + "/tensorboard/" self.summary_keys = [tf.GraphKeys.SUMMARIES] self.summary_nodes = {ck:[] for ck in self.summary_keys} self.summary_writers = {ck:[] for ck in self.summary_keys} self.stochastic = self._opts["stochastic"] if self.stochastic==0: #no noise is added pass elif self.stochastic == 1: self._clip_after_noise = True elif self.stochastic== 2 : self._clip_after_noise = False else: raise ValueError("stochastic can be: 0 no noise, 1 noise and clip after," "2 noise and do not clip after. Found stochastic {}".format(self.stochastic)) self.stochastic_noise_param = self._opts["stochastic_noise_param"] # # TODO never rescale if "rescale" in self._opts: raise KeyError("the key `rescale` is not supported anymore. Rescaling is not allowed, remove it from the conf.") # self.rescale = opts["rescale"] # rescale the inputs if they are continuous self.batch_size = {} self.batch_size["train"] = self._opts["batch_size_train"] self.batch_size["eval"] = self._opts["batch_size_eval"] # important nodes self.x = None self.y = None self.x_shape = {} self.optimizer_tuple = self._opts["optimizer"] #self.compute_natural_gradient = opts["natural_gradient"] #self.learning_rate = opts["training_algorithm"]["learning_rate"] #self.training_algorithm = opts["training_algorithm"]["algorithm"] #self.learning_rate = opts["training_algorithm"]["learning_rate"] self._grad_clipping_tuple = self._opts["grad_clipping"] # important nodes self.loss = None self.regularizers = [] # create regularizers if ("regularizers" not in self._opts) or ("weights" in self._opts["regularizers"].keys() or "bias" in self._opts["regularizers"].keys() or "custom" in self._opts["regularizers"].keys()) or len(self._opts["regularizers"].keys())==0: self.custom_regularizers = [] else: self.custom_regularizers = {} for key in self._opts["regularizers"].keys(): self.custom_regularizers[key] = [] self.update_ops = [] # list of kl_losses on the weights in case of bayesian learning self.kl_losses = [] self.datasets_initializers = {} self.datasets_handles_nodes = {} self.datasets_handles = {} # passed to ChechpoitSaverHook self._pb_output_nodes = None # NB dataset can be none in certain contexts, # NB maybe there is a better way to do this (Luigi) # TODO YES, this function should take the input node # IF using a CNN, shape of input node Must be of len 4, both sonnet functions and tf.layers.conv2d require this convention and this makes the code uniform: input_shape = [None, size1, size2, channels] # TODO-ARGO2 this function should restore variables from the last checkpoint if it is present, not always initialize the variables def init(self, dataset): self.binary = dataset.binary_input #TODO these two are probably useless... if you need the input shape just do tf.shape(self.raw_x) for some networks the input could change from train to eval #TODO if there is a way to avoid using explicitly the input dimension it is probably better... self.x_shape["train"] = dataset.x_shape_train self.x_shape["eval"] = dataset.x_shape_eval self.dataset = dataset self.create_feedable_placeholders() # create global steps self.create_global_steps(dataset.n_samples_train) self.create_input_nodes(dataset) # set optimizer self.set_optimizer() #self.create_is_training_node() self.create_network() #TODO-ARGO2 create loss, regularizer, optimizer and global step are typical of a training algorithm #TODO-ARGO2 how do we handle other cases that do not have a train? I think we should define #TODO-ARGO2 TrainableTFDeepLearningModel and redefine init # define self.loss and check it is finite self.create_loss() self.create_custom_regularizers() # define self.regularizers and self.update_ops self.create_regularizers_and_updates() # set the training operation for self.loss + self.regularizers + self.custom_regularizers self.set_training_op() # not used at the moment, could be useful at a certain point # self.create_random_update_op() # there are case in which multiple losses exit if isinstance(self.loss, dict): for k, v in self.loss.items(): self.loss[k] = tf.check_numerics(v, "self.loss" + str(k) + " is not finite") else: self.loss = tf.check_numerics(self.loss, "self.loss is not finite") #session will be created after init def create_datasets_with_handles(self, dataset): datasets_nodes, handle, ds_initializers, ds_handles = dataset.get_dataset_with_handle(self.batch_size["train"], self.batch_size["eval"]) self.datasets_initializers = ds_initializers self.datasets_handles_nodes = ds_handles self.ds_handle = handle self.datasets_nodes = datasets_nodes # this is needed, since ds_raw_x may be modified in create_input_nodes to remove the mask self.ds_raw_x = datasets_nodes[0][0] self.ds_aug_x = datasets_nodes[0][1] self.ds_perturb_x = datasets_nodes[0][2] return datasets_nodes, handle, ds_initializers, ds_handles def create_feedable_placeholders(self): """ DO NOT USE FOR MODEL SPECIFIC PLACEHOLDERS (e.g. losses or samples..) Create feedables. This function is setting additional placeholder (it probably should never be used since placeholders should be set 3in the right places) Sets: feedable placeholders with general purpose """ self.is_training = tf.placeholder_with_default(False, shape=(), name="is_training") #def create_is_training_node(self): # self._is_training = tf.placeholder_with_default(False, shape=(), name="is_training") @abstractmethod def create_network(self): """ It gets the input nodes from the dataset and creates the network starting from the input nodes created by `create_input_nodes` Sets: network nodes depending on the specific child class """ pass @abstractmethod def create_input_nodes(self, dataset): """ create input nodes for the network starting from the dataset Sets: input nodes depending on the specific child class """ pass @abstractmethod def create_loss(self): """create loss nodes for the network based on the nodes that create_networks has created, this method will create the loss nodes Sets: self.loss other additional loss nodes to be monitored during train can be set """ pass # create custom regularizers def create_custom_regularizers(self): if isinstance(self.custom_regularizers, list): self._create_custom_regularizers() elif isinstance(self.custom_regularizers, dict): for key in self.custom_regularizers.keys(): # add regularizers for discriminator self._create_custom_regularizers(key) else: raise Exception("self.custom_regularizers should be a list or a dict") def _create_custom_regularizers(self, network=None): if network is None: regularizers = self._opts["regularizers"] custom_regularizers = self.custom_regularizers else: regularizers = self._opts["regularizers"][network] custom_regularizers = self.custom_regularizers[network] ''' if "custom" in regularizers.keys(): for regularizer_tuple in regularizers["custom"]: regularizer_name = regularizer_tuple[0] regularizer_tuple[1]["model"] = self custom_regularizer = Regularizers.instantiate_regularizer(regularizer_tuple, module_path = "") '' regularizer_name = regularizer_tuple[0] regularizer_kwargs = regularizer_tuple[1] regularizer_kwargs["model"] = self try: # load customized regularizers from core/Regularizers.py reg_module = importlib.import_module("core.Regularizers", '.'.join(__name__.split('.')[:-1])) custom_regularizer, _, _ = eval_method_from_tuple(reg_module, (regularizer_name, regularizer_kwargs)) except AttributeError as e: # try to load from argo try: # load customized regularizers from core/argo/core/Regularizers.py reg_module = importlib.import_module(".Regularizers", '.'.join(__name__.split('.')[:-1])) custom_regularizer, _, _ = eval_method_from_tuple(reg_module, (regularizer_name, regularizer_kwargs)) except AttributeError as e: raise AttributeError("regularizer %s not found" % regularizer_name) from e '' custom_regularizers.append(custom_regularizer) self.check_regularizers(regularizer_name, network) ''' if "custom" in regularizers.keys(): for regularizer_tuple in regularizers["custom"]: regularizer_name = regularizer_tuple[0] regularizer_tuple[1]["model"] = self custom_regularizer = Regularizers.instantiate_regularizer(regularizer_tuple, module_path = "") custom_regularizers.append(custom_regularizer) self.check_regularizers(regularizer_name, network) def check_regularizers(self, regularizer_name, network=None): pass ''' def create_custom_regularizers(self): # should not be an empty list return [0.] ''' # save in self.regularizers the regularizers of the model def create_regularizers_and_updates(self): wb_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # see keras_utils.py: activity_and_contractive_regularizers ac_regularizers = tf.get_collection(AC_REGULARIZATION) # if (not wb_regularizers) and (not ac_regularizers): # wb_regularizers = [tf.constant(0.)] #import pdb;pdb.set_trace() if len(wb_regularizers)>0: self.regularizers += wb_regularizers if len(ac_regularizers)>0: self.regularizers += ac_regularizers # self.regularizers += ([self.custom_regularizers[r] for r in self._opts["regularizers"].keys() if len(self.custom_regularizers[r])>0]) # we need to flatten the list if we have both custom regularizers and another type of regularizers # (weight/bias or contractive) self.regularizers += list(chain.from_iterable([self.custom_regularizers[r] for r in self._opts["regularizers"].keys() if len(self.custom_regularizers[r]) > 0])) self.update_ops += tf.get_collection(tf.GraphKeys.UPDATE_OPS) # ac_train_regularizers = tf.get_collection(get_ac_collection_name("train")) # ac_validation_regularizers = tf.get_collection(get_ac_collection_name("validation")) # ac_test_regularizers = tf.get_collection(get_ac_collection_name("test")) # self.regularizer["train"] = tf.add_n(wb_regularizers + ac_train_regularizers, name="regularization_train") # self.regularizer["validation"] = tf.add_n(wb_regularizers + ac_validation_regularizers, name="regularization_validation") # self.regularizer["test"] = tf.add_n(wb_regularizers + ac_test_regularizers, name="regularization_test") def create_global_steps(self, n_points_train_set): self.n_batches_per_epoch = np.ceil(n_points_train_set/self.batch_size["train"]) self.global_step = tf.train.get_or_create_global_step() self.global_epoch = tf.cast(tf.floor(tf.cast(self.global_step, tf.float32) / self.n_batches_per_epoch), tf.int64, "global_epoch") tf.add_to_collection("global_epoch", self.global_epoch) # this creates an operation to add to all trainable variables a white noise of param # std = tf.sqrt(variance)/10 def create_random_update_op(self): vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) update_opts = [] for var in vars: _, variance = tf.nn.moments(tf.reshape(var,[-1]),axes=[0]) normal = tf.distributions.Normal(loc=0.0, scale=tf.sqrt(variance)/10) white_noise = normal.sample(var.get_shape()) update_opts.append(var.assign(var + white_noise)) self.random_update_op = tf.group(update_opts) #apply clipping def _clip_gradients(self, grads_and_vars, grad_clipping_tuple): clipping_method, clipping_kwargs = grad_clipping_tuple grads_and_vars_not_none = [(g, v) for (g, v) in grads_and_vars if g is not None] grads = [g for (g, v) in grads_and_vars_not_none] variables = [v for (g, v) in grads_and_vars_not_none] #self.grad_norms = [tf.norm(g) for g in grads] #else: # self.new_logits = self.logits self.grads = grads self.grads_norm = tf.global_norm(grads) #see https://www.tensorflow.org/api_docs/python/tf/train/Optimizer#processing_gradients_before_applying_them #if clipping_method == "clip_by_global_norm": # # print_ops = [tf.print("global norm " + str(tf.norm(g))) for g in grads] # with tf.control_dependencies(print_ops): # clipped_grads, global_norm = tf.clip_by_global_norm(grads, clipping_kwargs["value"]) # self.clipped_grads_and_vars = [(clipped_grads[i], variables[i]) for i in range(len(grads))] #see https://www.tensorflow.org/api_docs/python/tf/train/Optimizer#processing_gradients_before_applying_them if clipping_method == "clip_by_global_norm": #clip_by_global_norm requires all the grads as argument, not only grad[i] grads_and_vars_not_none = [(g, v) for (g, v) in grads_and_vars if g is not None] grads = [g for (g, v) in grads_and_vars_not_none] variables = [v for (g, v) in grads_and_vars_not_none] #print_ops = [tf.print("loss=", self.loss)] + [tf.print("norms_g", tf.norm(g)) for g in grads] + [tf.print("g", g) for g in grads] + [tf.print("p", self.prob)] + [tf.print("invFisher", self.invFisher)] + [tf.print("invA", self.invA)] + [tf.print("invB", self.invB)] #print_ops = [tf.print("partA =", self.partA, summarize=-1), tf.print("partB =", self.partB, summarize=-1), tf.print("prob_sliced =", self.prob_sliced, summarize=-1), tf.print("natural_gradient_theta =", self.natural_gradient_loss_theta, summarize=-1), tf.print("euclidean gradient =", self.euclidean_gradient, summarize=-1), tf.print("TA =", self.TA, summarize=-1), tf.print("Tup =", self.Tup, summarize=-1) , tf.print("Tdown =", self.Tdown, summarize=-1) , tf.print("TB =", self.TB, summarize=-1)] + [tf.print("norms_g", tf.norm(g), summarize=-1) for g in grads] #with tf.control_dependencies(print_ops): clip_value = clipping_kwargs["value"] clipped_grads, global_norm = tf.clip_by_global_norm(grads, clip_value) clipped_grads_and_vars = [(clipped_grads[i], variables[i]) for i in range(len(grads))] elif clipping_method == "clip_by_norm": grads_and_vars_not_none = [(g, v) for (g, v) in grads_and_vars if g is not None] grads = [g for (g, v) in grads_and_vars_not_none] variables = [v for (g, v) in grads_and_vars_not_none] # How t handle numerical issues # 1) set nan/inf to zero # grads = [tf.where(tf.is_finite(g), g, tf.zeros_like(g)) for (g, v) in grads_and_vars_not_none] # 2) set nan/inf to noisy gradient, #grads = [tf.where(tf.is_finite(g), g, tfd.Normal(loc=0.0, scale=tf.sqrt(tf.nn.moments(tf.reshape(v,[-1]),axes=[0])[1])/10 + 0.01).sample(g.get_shape())) for (g, v) in grads_and_vars_not_none] clip_value = clipping_kwargs["value"] clipped_grads_and_vars = [(tf.clip_by_norm(g, clip_value), v) for (g, v) in zip(grads, variables)] elif clipping_method == "clip_by_value": clip_value = clipping_kwargs["value"] clipped_grads_and_vars = [(tf.clip_by_value(g, -clip_value, clip_value), v) for (g, v) in grads_and_vars if g is not None] elif not clipping_method: grads_and_vars_not_none = [(g, v) for (g, v) in grads_and_vars if g is not None] clipped_grads_and_vars = grads_and_vars_not_none else: raise Exception("clipping method not recognized: " + clipping_method) return clipped_grads_and_vars ''''not used, please don't delete (Luigi) def check_numerics_grad(grads): condition = tf.constant(True) for g in grads: condition = tf.math.logical_and(condition,tf.check_numerics(g, "check numerics for gradient failed")) return condition # the function above could be used in the following context self.clipped_grads_and_vars = tf.cond(check_numerics_grad(grads), self.clip_gradients(self.grads_and_vars, self._grad_clipping_tuple), grads_and_vars_not_none) #grads_and_vars_not_none) ''' def set_optimizer(self): with tf.variable_scope('optimizer'): self._optimizer, self._learning_rate = TFOptimizers.instantiate_optimizer(self, self.optimizer_tuple) def set_training_op(self): #def flatten_weights(weights_list): # weights_tensor = [] # for w in weights_list: # print(w) # a = tf.reshape(w, [-1, ]) # weights_tensor.append(a) # # return tf.concat(weights_tensor, axis=0) ''' ######################################### # Euclidean gradient computed in two steps, through the Jacobian ######################################### #self.probabilities = tf.nn.softmax(self.logits) loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels = tf.cast(self.y, tf.int32), logits = self.logits) + self.regularizer #middle_man = self.logits # self.natural_loss # #n = self.probabilities.get_shape().as_list()[1] self.euclidean_gradient = tf.gradients(loss, self.logits)[0] # from [g] to g trainable_vars = tf.trainable_variables() jacobians = jacobian(self.logits, trainable_vars) # [tf.reduce_sum(i, axis=0) for i in jacobian(self.logits, trainable_vars)] #self.nat_grad = [tf.reduce_mean(i, axis=0) for i in self.jacobian] # proper way to compute the contraction self.euclidean_gradient = [tf.reduce_mean(tf.einsum(get_contraction(i), i, self.euclidean_gradient), axis=0) for i in jacobians] # OLD self.nat_grad = [tf.reduce_mean(tf.tensordot(i, self.nat_grad_theta, [[1], [1]]), axis=[0, 1, -1]) for i in self.jacobian] self.euclidean_grad_norms = [tf.norm(g) for g in self.euclidean_gradient] ''' total_loss = self.loss # add regularizers in case there are any if len(self.regularizers)>0: total_loss += tf.add_n(self.regularizers, name="regularization") # 1st part of minimize: compute_gradient self.grads_and_vars = self._optimizer.compute_gradients(total_loss) # clip gradients clipped_grads_and_vars = self._clip_gradients(self.grads_and_vars, self._grad_clipping_tuple) # compute norms in case they need to be logged self.gradient_norms = [tf.norm(g) + NUMTOL for (g, v) in clipped_grads_and_vars] self.weight_norms = [tf.norm(v) + NUMTOL for (g, v) in clipped_grads_and_vars] # check that gradients are finite grads = [tf.check_numerics(g, "grads is not finite") for (g, v) in clipped_grads_and_vars] variables = [tf.check_numerics(v, "grads is not finite") for (g, v) in clipped_grads_and_vars] self.gradient_weight_global_norms = [tf.global_norm(grads), tf.global_norm(variables)] # 2nd part of minimize: apply_gradient optimizer_step = self._optimizer.apply_gradients(clipped_grads_and_vars, global_step=self.global_step) update_ops = tf.group(*self.update_ops) self.training_op = tf.group(update_ops, optimizer_step) def set_check_ops(self): self._check_ops = 1 # TODO argo2 This is not working anymore with the new session #with self.sess.graph.as_default(): self._numerics_ops = tf.add_check_numerics_ops() def release(self): super().release() self.sess.close() tf.reset_default_graph() def set_summaries(self): """This function sets summaries and summaryFileWriters, it needs to be invoked before training to keep track of the summaries. (cannot be invoked in create_and_init_network because the FileWriter will corrupt data in the logfolder at each initialization) """ # wb_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # ac_regularizers = tf.get_collection(AC_REGULARIZATION) # # reg_nodes = wb_regularizers + ac_regularizers # for rn in reg_nodes: # tf.summary.scalar(rn.name, rn, # collections=[tf.GraphKeys.SUMMARIES, 'regularization_summaries']) # for each key I get the collection of summary nodes # I set up a filewriter for each summary node self.summary_nodes = {sk: tf.get_collection(sk) for sk in self.summary_keys} for sk in self.summary_keys: self.summary_writers[sk] = [tf.compat.v1.summary.FileWriter(self._tensorboard_dir+sn.name) for sn in self.summary_nodes[sk]] def create_hooks(self, config): hooks=[] # get general arguments for the models hook self._time_reference_str = config["time_reference"] self._check_time_reference(self._time_reference_str) self._plot_offset = config.get("plot_offset", 0) self._default_model_hooks_kwargs = {"time_reference" : self._time_reference_str} self._plot_model_hooks_kwargs = {"time_reference" : self._time_reference_str, "plot_offset": self._plot_offset} self._n_steps_stats = self._get_steps(config["stats_period"], self._time_reference_str) # stop hook tot_steps = int(self._opts['epochs']+1)*self.n_batches_per_epoch hooks.append(tf.train.StopAtStepHook(last_step=tot_steps)) # general info hook (no average on validation but only on train loop) hooks.append(self._create_general_info_hook(config)) # regularizers hook (no average on validation but only on train loop) hooks.append(self._create_regularizers_hook(config)) # checkpoint hooks self._save_model = config["save_model"] if self._save_model: max_to_keep = config.get("save_max_to_keep", 5) self._init_session_saver(max_to_keep) self._checkpoint_basename = "model.ckpt" save_steps = self._get_steps(config["save_model_period"], self._time_reference_str) hooks.append(CheckpointSaverHook(self._checkpoint_dir, save_steps = save_steps, saver = self._saver, checkpoint_basename = self._checkpoint_basename, pb_output_nodes = self._pb_output_nodes, save_pb_at_end = config.get("save_pb", 0) )) # summary hook if config["save_summaries"]: save_steps_summaries = self._get_steps(config["save_summaries_period"], self._time_reference_str) self.set_summaries() summary_hooks = [tf.train.SummarySaverHook(save_steps=save_steps_summaries, output_dir=self._tensorboard_dir+sn.name, summary_op=sn, summary_writer=fw) for sk in self.summary_keys for sn,fw in zip(self.summary_nodes[sk], self.summary_writers[sk])] hooks += summary_hooks # images input hook kwargs = config.get("ImagesInputHook", None) if kwargs: kwargs = {**self._default_model_hooks_kwargs, **kwargs} hooks.append(ImagesInputHook(model = self, dirName = self.dirName, **kwargs) ) #gradient_hook = self._create_gradient_hook(config) #if gradient_hook is not None: # hooks.append(gradient_hook) kwargs = config.get("FisherMatrixHook", None) if kwargs and isinstance(self._optimizer, NaturalGradientOptimizer): kwargs = {**self._default_model_hooks_kwargs, #'datasets_keys' : [TRAIN_LOOP], **kwargs} hooks.append(FisherMatrixHook(model = self, dirName = self.dirName, **kwargs ) ) return hooks def _create_gradient_hook(self, config): # gradienthook tensors_to_average = [ [[self.gradient_weight_global_norms[0]], self.gradient_norms ], [[self.gradient_weight_global_norms[1]], self.weight_norms ], ] layer_names = np.array(list(range(len(self.gradient_norms)))) layer_names = np.floor(layer_names / 2) + 1 layer_names = ["L" + str(int(l)) for l in layer_names] tensors_to_average_names = [ [["gradient_global_norms"], layer_names ], [["weight_global_norms"], layer_names ], ] tensors_to_average_plots = [ [{"fileName": "gradient_global_norms", "logscale-y": 1, "compose-label": 0}, {"fileName": "gradient_norms", "logscale-y": 1, "compose-label": 0} ], [{"fileName": "weight_global_norms", "logscale-y": 1, "compose-label": 0}, {"fileName": "weight_norms", "logscale-y": 1, "compose-label": 0} ], ] kwargs = config.get("GradientsHook", None) if kwargs: gradient_period = config["GradientsHook"]["period"] gradient_steps = self._get_steps(gradient_period, self._time_reference_str) hook = LoggingMeanTensorsHook(model=self, fileName="gradient", dirName=self.dirName, tensors_to_average=tensors_to_average, tensors_to_average_names=tensors_to_average_names, tensors_to_average_plots=tensors_to_average_plots, average_steps=gradient_steps, tensorboard_dir=self._tensorboard_dir, trigger_summaries=config["save_summaries"], # trigger_plot=True, print_to_screen=False, plot_offset=self._plot_offset, # config.get("plot_start_epoch", 1), train_loop_key=TRAIN_LOOP, datasets_keys=[], time_reference=self._time_reference_str ) return hook else: return None # create custom regularizers id # passing the network equal to None support the possibility to use this function in presence # of multiple networks, used in gan and vae, not in hm def create_custom_regularizers_id(self, network=None): if network is None: regularizers = self._opts["regularizers"] else: regularizers = self._opts["regularizers"][network] ids = "" if "custom" in regularizers.keys(): #import pdb;pdb.set_trace() for regularizer_tuple in regularizers["custom"]: regularizer_name = regularizer_tuple[0] try: base_path = '.'.join(__name__.split('.')[:-3]) regularizer_module = load_module("Regularizers", base_path=base_path) id = regularizer_module.create_id(regularizer_tuple) except Exception as e: # try to load from argo try: id = Regularizers.create_id(regularizer_tuple) except Exception as e: raise Exception("regularizer %s not found" % regularizer_name) from e if ids == "": ids = id else: ids = ids + "_" + id return ids def _create_regularizers_hook(self, config): wb_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) # see keras_utils.py: activity_and_contractive_regularizers ac_regularizers = tf.get_collection(AC_REGULARIZATION) custom_regularizers = tf.get_collection(CUSTOM_REGULARIZATION) if wb_regularizers: wb_regularizers_names = [r.name for r in wb_regularizers] else: wb_regularizers = [tf.zeros([1])] wb_regularizers_names = ["none"] wb_regularizers_fileNames = {"fileName" : "wb_regularizers"} if ac_regularizers: ac_regularizers_names = [r.name for r in ac_regularizers] else: ac_regularizers = [tf.zeros([1])] ac_regularizers_names = ["none"] ac_regularizers_fileNames = {"fileName" : "ac_regularizers"} if custom_regularizers: custom_regularizers_names = [r.name for r in custom_regularizers] else: custom_regularizers = [tf.zeros([1])] custom_regularizers_names = ["none"] custom_regularizers_fileNames = {"fileName": "custom_regularizers"} # logging hooks tensors_to_average = [[wb_regularizers], [ac_regularizers, custom_regularizers]] tensors_to_average_names = [[wb_regularizers_names], [ac_regularizers_names, custom_regularizers_names]] tensors_to_average_plots = [[wb_regularizers_fileNames], [ac_regularizers_fileNames, custom_regularizers_fileNames]] hook = LoggingMeanTensorsHook(model=self, fileName="regularizers", dirName=self.dirName, tensors_to_average=tensors_to_average, tensors_to_average_names=tensors_to_average_names, tensors_to_average_plots=tensors_to_average_plots, average_steps=self._n_steps_stats, tensorboard_dir=self._tensorboard_dir, trigger_summaries=config["save_summaries"], print_to_screen=False, # trigger_plot = True, plot_offset=self._plot_offset, train_loop_key=TRAIN_LOOP, datasets_keys=[], time_reference=self._time_reference_str ) return hook def _create_general_info_hook(self, config): # logging hooks tensors_to_average = [ [[self._learning_rate]] ] tensors_to_average_names = [ [["learning_rate"]], ] tensors_to_average_plots = [ [{"fileName": "learning_rate"}] ] hook = LoggingMeanTensorsHook(model=self, fileName="info", dirName=self.dirName, tensors_to_average=tensors_to_average, tensors_to_average_names=tensors_to_average_names, tensors_to_average_plots=tensors_to_average_plots, average_steps=self._n_steps_stats, tensorboard_dir=self._tensorboard_dir, trigger_summaries=config["save_summaries"], print_to_screen=False, # trigger_plot = True, plot_offset = self._plot_offset, train_loop_key=TRAIN_LOOP, datasets_keys=[] ) return hook # why passing opt? def create_session(self, opts, config, monitorSession=True): # save to set the right behavior in self.get_raw_session() self.monitorSession = monitorSession # set some important options if self._gpu == -1: sess_config = tf.ConfigProto(device_count = {'GPU': 0}, allow_soft_placement=True) else: #config = tf.ConfigProto(log_device_placement=True) sess_config = tf.ConfigProto(allow_soft_placement=True) sess_config.gpu_options.allow_growth = True # self.sess = tf.Session(config=config) # self.sess = tf.InteractiveSession() # not needed anymore, moved in hooks... # self.set_summaries() if self._check_ops: self.set_check_ops() self.hooks = self.create_hooks(config) #TODO-ARGO2 if we would use a SingularMonitoredSession, it is possible to directly pass it to a saver for custom user saving.. #TODO-ARGO2 How to handle this with the more stable Monitored Session? Maybe a TFTrainableDeepLearningModel #TODO-ARGO2 by the way it is possible to define a custom Monitored session #TODO-ARGO2 (to handle only hooks without fancy session stuffs http://davideng.me/2017/10/11/designing-a-custom-monitored-training-session.html if monitorSession: # MonitoredSession # this will restore all the variables from the latest checkpoint if it exists self._fix_checkpoint_abs_to_rel(self._checkpoint_dir) # need to ensure checkpoint has relative path saved chiefsess_creator = tf.train.ChiefSessionCreator(config=sess_config, checkpoint_dir=self._checkpoint_dir) if self._restore_chkptfile is not None: self._network.init_saver() # this is restoring variables self.sess = tf.train.MonitoredSession(session_creator=chiefsess_creator, hooks=self.hooks) # Restore from some checkpoint if self._restore_chkptfile is not None: raw_sess = self.get_raw_session() if raw_sess.run(self.global_step) == 0: self._network.restore(raw_sess, self._restore_chkptfile) else: self.sess = tf.Session(config=sess_config) #all_variables = tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES) #self.sess.run(tf.variables_initializer(all_variables)) if self._save_model: self._save_graph() # SingularMonitoredSession # self.sess = tf.train.SingularMonitoredSession(checkpoint_dir=self._checkpoint_dir, # hooks=self.hooks, config=sess_config) #I do not want to trigger hooks for this!! self.datasets_handles = self.get_raw_session().run(self.datasets_handles_nodes) # to get the raw session in MonitoredSession see # https://github.com/tensorflow/tensorflow/issues/8425 # https://github.com/tensorflow/tensorflow/issues/11971 def get_raw_session(self): if self.sess is None: raise Exception("The session is None") if self.monitorSession: return self.sess._tf_sess() else: # suppose regular Session() return self.sess def train(self): # epoch = 0 # # start timer for TF # start_tf = timeit.default_timer() # INITIALIZATION OPERATIONS HERE # Also: I always perform a global_step evaluation to eventually "wake up" the # stop condition of StopAtStepHook if needed (otherwise it would do an extra step over its limit each time) # (possible bug in tf?) # initializer = self.dataset_initializers["train"] # args = [initializer] if initializer is not None else [] # args += [self.global_step] # self.get_raw_session().run(args) for hook in self.hooks: before_training = getattr(hook, 'before_training', None) if before_training is not None: before_training(self.get_raw_session()) #i = 0 # count of the nan / inf k = 0 # MAX nan / inf MAX_K = 100 print("Graph size: " + str(self.graph_size)) # loops over the batches while not self.sess.should_stop(): # import pdb;pdb.set_trace() try: #import pdb; pdb.set_trace() # sess = self.get_raw_session() # sess.run(self._network.get_all_variables()[6]) # g, g_norm, x, y, loss, grads_and_vars, _, global_epoch = self.sess.run([self.grads, self.grads_norm, self.x, self.y, self.loss, self.grads_and_vars , self.training_op, self.global_epoch], # loss must be evaluated and fetched to raise InvalidArgumentError if nan, see https://github.com/tensorflow/tensorflow/issues/11098 _, _, global_epoch = self.sess.run([self.training_op, self.loss, self.global_epoch], feed_dict = {self.ds_handle : self.datasets_handles[TRAIN_LOOP], self.is_training : True}) #pdb.set_trace() # self.sess.run([self.z],feed_dict = {self.ds_handle : self.datasets_handles[TRAIN_LOOP],self.is_training : True})[0].shape # pdb.set_trace() #self.invFisher, self.prob, #print(i, loss) #if i==180: # pdb.set_trace() #i = i + 1 except tf.errors.InvalidArgumentError: raise Exception("an error has occurred during training, check stack trace UP HERE") k = k+1 print("an error has occurred during training, this happened " + str(k) + " times over " + str(MAX_K)) if k == MAX_K: raise Exception("an error has occurred during training, check stack trace UP HERE") # here the are two possibilities we could try: # 1) ignore the current batch and proceed to the next, in case the error is a numerical error # 2) add noise the the weights, see self.random_update_op (so far it didn't help) # TODO not sure if I need to evaluate global_epoch or not in this case #_, global_epoch = self.sess.run([self.random_update_op, self.global_epoch], feed_dict = {self.ds_handle : self.datasets_handles[TRAIN_LOOP]}) # if global_epoch != epoch: # # end timer for TF # stop_tf = timeit.default_timer() # time = stop_tf - start_tf # # epoch = global_epoch # # print("global epoch: ", global_epoch, " time:", time) # # # start timer for TF # start_tf = timeit.default_timer() def _init_session_saver(self, max_to_keep, variables=None): """ A saver with all the variables for the session is instantiated and set in self._saver, with variables, by default variables is None, all variables in the graph will be saved. It is probably a good idea since the whole session must be later be restored by the ChiefSession """ os.makedirs(self._checkpoint_dir, exist_ok=True) #variables = tf.trainable_variables() self._saver = tf.train.Saver(variables, max_to_keep=max_to_keep, save_relative_paths=True) def _save_graph(self): writer = tf.summary.FileWriter(logdir=self._checkpoint_dir, # graph=self.sess.graph, graph=tf.get_default_graph(), filename_suffix="-graph" ) writer.flush() def _assemble_checkpoint_name(self, checkpoint_dir): path = os.path.join(checkpoint_dir, "model.ckpt") return path def _latest_checkpoint(self, checkpoint_dir): with open(checkpoint_dir + 'checkpoint') as fs: potentiallyabsolutepath = fs.readline().split()[1] potentiallyabsolutepath = os.path.basename(potentiallyabsolutepath.strip('"')) path = checkpoint_dir + os.path.basename(potentiallyabsolutepath) return path def _fix_checkpoint_abs_to_rel(self, checkpoint_dir): checkpointfilename = checkpoint_dir + 'checkpoint' exists = os.path.isfile(checkpointfilename) if exists: with open(checkpointfilename) as fs: lines = fs.readlines() fs = open(checkpointfilename, 'w') for line in lines: which_model, potentiallyabsolutepath = line.split() potentiallyabsolutepath = os.path.basename(potentiallyabsolutepath.strip('"')) rel_path = '\"'+os.path.basename(potentiallyabsolutepath)+'\"' fs.write(" ".join([which_model, rel_path]) + "\n") fs.close() def checkpoint_name(self, global_step): if global_step: path = self._assemble_checkpoint_name(self._checkpoint_dir) path += "-"+str(global_step) else: path = self._latest_checkpoint(self._checkpoint_dir) if not path: raise Exception("could not find saved checkpoints in %s"%self._checkpoint_dir) return path def save(self, global_step=None): if self._saver is None: raise Exception("saver must be initialized before attempt to save") else: session = self.get_raw_session() path = self._assemble_checkpoint_name() self._saver.save(session, path, global_step=global_step) def restore(self, global_step=None): """Restore the model variables. Args: global_step (type): the step from which to restore. By default it is None and the latest checkpoint in self.checkpoint_dir will be restored """ path = "" session = self.get_raw_session() if self._saver is None: raise Exception("saver must be initialized before attempt to restore") else: path = self.checkpoint_name(global_step) self._saver.restore(session, path) @property def graph_size(self): return len([n.name for n in self.sess.graph.as_graph_def().node]) def _check_time_reference(self, time_ref): time_choices = [EPOCHS, STEPS] if not time_ref in time_choices: raise ValueError("time_reference in the frequency tuple can only be in %s" % time_choices) def _get_steps(self, n, time_reference): # try: # n, time_ref = frequency # except: # raise Exception("cannot unpack tuple %s, expected a couple (n, time_ref)," # "where time_ref can either be `epochs` or `steps`" % frequency) self._check_time_reference(time_reference) n = float(n) if time_reference == EPOCHS: n = n * self.n_batches_per_epoch return int(n)
[ "tensorflow.zeros", "tensorflow.cast", "tensorflow.train.ChiefSessionCreator", "tensorflow.get_default_graph", "tensorflow.group", "tensorflow.add_n", "tensorflow.get_collection", "tensorflow.placeholder_with_default", "tensorflow.check_numerics", "tensorflow.train.get_or_create_global_step", "tensorflow.ConfigProto", "numpy.ceil", "tensorflow.clip_by_norm", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.norm", "tensorflow.train.StopAtStepHook", "tensorflow.train.MonitoredSession", "numpy.floor", "tensorflow.set_random_seed", "tensorflow.add_check_numerics_ops", "tensorflow.train.SummarySaverHook", "tensorflow.add_to_collection", "tensorflow.global_norm", "tensorflow.clip_by_value", "tensorflow.compat.v1.summary.FileWriter", "tensorflow.reshape", "tensorflow.clip_by_global_norm", "tensorflow.variable_scope", "tensorflow.sqrt" ]
argo/core/TFDeepLearningModel.py
[(54, 'datasets.Dataset.Dataset.load_dataset', 'Dataset.load_dataset', (['dataset_conf'], {}), False, 'from datasets.Dataset import Dataset, TRAIN_LOOP\n'), (105, 'datasets.Dataset.Dataset.load_dataset', 'Dataset.load_dataset', (['dataset_conf'], {}), False, 'from datasets.Dataset import Dataset, TRAIN_LOOP\n'), (241, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['seed'], {}), True, 'import tensorflow as tf\n'), (398, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(False)'], {'shape': '()', 'name': '"""is_training"""'}), True, 'import tensorflow as tf\n'), (515, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (517, 'tensorflow.get_collection', 'tf.get_collection', (['AC_REGULARIZATION'], {}), True, 'import tensorflow as tf\n'), (534, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.UPDATE_OPS'], {}), True, 'import tensorflow as tf\n'), (545, 'numpy.ceil', 'np.ceil', (["(n_points_train_set / self.batch_size['train'])"], {}), True, 'import numpy as np\n'), (547, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (552, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""global_epoch"""', 'self.global_epoch'], {}), True, 'import tensorflow as tf\n'), (558, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {}), True, 'import tensorflow as tf\n'), (570, 'tensorflow.group', 'tf.group', (['update_opts'], {}), True, 'import tensorflow as tf\n'), (587, 'tensorflow.global_norm', 'tf.global_norm', (['grads'], {}), True, 'import tensorflow as tf\n'), (724, 'tensorflow.group', 'tf.group', (['*self.update_ops'], {}), True, 'import tensorflow as tf\n'), (725, 'tensorflow.group', 'tf.group', (['update_ops', 'optimizer_step'], {}), True, 'import tensorflow as tf\n'), (733, 'tensorflow.add_check_numerics_ops', 'tf.add_check_numerics_ops', ([], {}), True, 'import tensorflow as tf\n'), (738, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (946, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (948, 'tensorflow.get_collection', 'tf.get_collection', (['AC_REGULARIZATION'], {}), True, 'import tensorflow as tf\n'), (949, 'tensorflow.get_collection', 'tf.get_collection', (['CUSTOM_REGULARIZATION'], {}), True, 'import tensorflow as tf\n'), (1200, 'os.makedirs', 'os.makedirs', (['self._checkpoint_dir'], {'exist_ok': '(True)'}), False, 'import os\n'), (1202, 'tensorflow.train.Saver', 'tf.train.Saver', (['variables'], {'max_to_keep': 'max_to_keep', 'save_relative_paths': '(True)'}), True, 'import tensorflow as tf\n'), (1213, 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model.ckpt"""'], {}), False, 'import os\n'), (1226, 'os.path.isfile', 'os.path.isfile', (['checkpointfilename'], {}), False, 'import os\n'), (61, 'os.path.dirname', 'os.path.dirname', (['conf_file'], {}), False, 'import os\n'), (112, 'os.path.dirname', 'os.path.dirname', (['conf_file'], {}), False, 'import os\n'), (159, 'os.path.dirname', 'os.path.dirname', (['conf_file'], {}), False, 'import os\n'), (214, 'os.path.abspath', 'os.path.abspath', (["self._opts['pretrained_checkpoint']"], {}), False, 'import os\n'), (369, 'tensorflow.check_numerics', 'tf.check_numerics', (['self.loss', '"""self.loss is not finite"""'], {}), True, 'import tensorflow as tf\n'), (611, 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['grads', 'clip_value'], {}), True, 'import tensorflow as tf\n'), (663, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""optimizer"""'], {}), True, 'import tensorflow as tf\n'), (705, 'tensorflow.add_n', 'tf.add_n', (['self.regularizers'], {'name': '"""regularization"""'}), True, 'import tensorflow as tf\n'), (717, 'tensorflow.check_numerics', 'tf.check_numerics', (['g', '"""grads is not finite"""'], {}), True, 'import tensorflow as tf\n'), (718, 'tensorflow.check_numerics', 'tf.check_numerics', (['v', '"""grads is not finite"""'], {}), True, 'import tensorflow as tf\n'), (719, 'tensorflow.global_norm', 'tf.global_norm', (['grads'], {}), True, 'import tensorflow as tf\n'), (719, 'tensorflow.global_norm', 'tf.global_norm', (['variables'], {}), True, 'import tensorflow as tf\n'), (758, 'tensorflow.get_collection', 'tf.get_collection', (['sk'], {}), True, 'import tensorflow as tf\n'), (782, 'tensorflow.train.StopAtStepHook', 'tf.train.StopAtStepHook', ([], {'last_step': 'tot_steps'}), True, 'import tensorflow as tf\n'), (862, 'numpy.floor', 'np.floor', (['(layer_names / 2)'], {}), True, 'import numpy as np\n'), (1036, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'GPU': 0}", 'allow_soft_placement': '(True)'}), True, 'import tensorflow as tf\n'), (1040, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), True, 'import tensorflow as tf\n'), (1066, 'tensorflow.train.ChiefSessionCreator', 'tf.train.ChiefSessionCreator', ([], {'config': 'sess_config', 'checkpoint_dir': 'self._checkpoint_dir'}), True, 'import tensorflow as tf\n'), (1071, 'tensorflow.train.MonitoredSession', 'tf.train.MonitoredSession', ([], {'session_creator': 'chiefsess_creator', 'hooks': 'self.hooks'}), True, 'import tensorflow as tf\n'), (1079, 'tensorflow.Session', 'tf.Session', ([], {'config': 'sess_config'}), True, 'import tensorflow as tf\n'), (1221, 'os.path.basename', 'os.path.basename', (['potentiallyabsolutepath'], {}), False, 'import os\n'), (563, 'tensorflow.reshape', 'tf.reshape', (['var', '[-1]'], {}), True, 'import tensorflow as tf\n'), (714, 'tensorflow.norm', 'tf.norm', (['g'], {}), True, 'import tensorflow as tf\n'), (715, 'tensorflow.norm', 'tf.norm', (['v'], {}), True, 'import tensorflow as tf\n'), (761, 'tensorflow.compat.v1.summary.FileWriter', 'tf.compat.v1.summary.FileWriter', (['(self._tensorboard_dir + sn.name)'], {}), True, 'import tensorflow as tf\n'), (812, 'tensorflow.train.SummarySaverHook', 'tf.train.SummarySaverHook', ([], {'save_steps': 'save_steps_summaries', 'output_dir': '(self._tensorboard_dir + sn.name)', 'summary_op': 'sn', 'summary_writer': 'fw'}), True, 'import tensorflow as tf\n'), (954, 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), True, 'import tensorflow as tf\n'), (961, 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), True, 'import tensorflow as tf\n'), (968, 'tensorflow.zeros', 'tf.zeros', (['[1]'], {}), True, 'import tensorflow as tf\n'), (1207, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (548, 'tensorflow.cast', 'tf.cast', (['self.global_step', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (565, 'tensorflow.sqrt', 'tf.sqrt', (['variance'], {}), True, 'import tensorflow as tf\n'), (628, 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['g', 'clip_value'], {}), True, 'import tensorflow as tf\n'), (1235, 'os.path.basename', 'os.path.basename', (['potentiallyabsolutepath'], {}), False, 'import os\n'), (633, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['g', '(-clip_value)', 'clip_value'], {}), True, 'import tensorflow as tf\n')]
aimalz/justice
2edcb471cd01d6659a498bcd0209cb5dae83375a
# -*- coding: utf-8 -*- """Extracts dense features with linear transformations.""" import enum import json import pathlib import typing import numpy as np import tensorflow as tf from justice import path_util from justice.align_model import graph_typecheck from justice.features import band_settings_params def _left_mask(before_padding, window_size): """Generates a mask for left-padded vectors. Mask elements are True if a valid element is present. e.g. suppose left features are [0, 0, 0, x], where the "0" values are padding, so before_padding = 3. This function will return a mask [False, False, False, True]. (in reality everything is vectorized by batch dimension. :param before_padding: [batch_size] tensor of before_padding values. :param window_size: scalar window size. :return: [batch_size, window_size] boolean tensor mask. """ return tf.logical_not(tf.sequence_mask(before_padding, maxlen=window_size)) def _right_mask(after_padding, window_size): """Same as above, but for right-padded vectors.""" return tf.sequence_mask(window_size - after_padding, maxlen=window_size) class WindowFeatures(object): """Helper for dealing with window-like raw features. In particular, this class generates concatenated "dflux_dt" values, and has a masking helper, which will probably be applied after doing some non-linear transformations to dflux_dt (or possibly raw self.dtime, self.dflux) values. """ def __init__( self, band_features: dict, batch_size: int, window_size: int, band_time_diff: float = 4.0 ): """Initializes a windowed feature extractor. :param band_features: Band features, generated by raw_value_features. :param batch_size: Outer batch size. :param window_size: Number of points in 'before' and 'after' windows. :param band_time_diff: Maximum difference between requested time and actual time in the window. """ def batch_shaped(t): return graph_typecheck.assert_shape(t, [batch_size]) def batch_win_shaped(t): return graph_typecheck.assert_shape(t, [batch_size, window_size]) def batch_2win_shaped(t): return graph_typecheck.assert_shape(t, [batch_size, 2 * window_size]) def tile_to_2win(t): return tf.tile(tf.expand_dims(t, 1), [1, 2 * window_size]) closest_time = batch_shaped(band_features['closest_time_in_band']) closest_flux = batch_shaped(band_features['closest_flux_in_band']) self.in_window = tf.less( batch_shaped(band_features["closest_time_diff"]), band_time_diff ) # Before and after flux. before_flux = batch_win_shaped(band_features["before_flux"]) after_flux = batch_win_shaped(band_features["after_flux"]) before_time = batch_win_shaped(band_features["before_time"]) after_time = batch_win_shaped(band_features["after_time"]) self.dtime = batch_2win_shaped( tf.concat([before_time, after_time], axis=1) - tile_to_2win(closest_time), ) self.dflux = batch_2win_shaped( tf.concat([before_flux, after_flux], axis=1) - tile_to_2win(closest_flux), ) # Masking tensor. left_mask = _left_mask( batch_shaped( band_features["before_padding"]), window_size) right_mask = _right_mask( batch_shaped(band_features["after_padding"]), window_size ) self.mask = batch_2win_shaped( tf.logical_and( tf.concat([left_mask, right_mask], axis=1), tile_to_2win(self.in_window) ) ) def dflux_dt(self, clip_magnitude: typing.Optional[float]) -> tf.Tensor: """Computes dflux/dt. :param clip_magnitude: Option for clipping the magnitude, if dt might be very small. :return: <float>[batch_size, 2 * window_size] dflux/dt tensor. """ result = self.dflux / self.dtime if clip_magnitude is not None: result = tf.clip_by_value( result, clip_value_min=-clip_magnitude, clip_value_max=clip_magnitude ) return result def masked( self, expanded_tensor: tf.Tensor, value_if_masked: float, expected_extra_dims: typing.List[int] ): """Masks a tensor which was calculated from dflux_dt. :param expanded_tensor: <float>[batch_size, window_size, ...] Tensor with first dimensions being batch_size and window_size. :param value_if_masked: Value to fill for masked positions. :param expected_extra_dims: Expected extra dimensions. :returns: Tensor of same shape as expanded_tensor, but with `value_if_masked` filled in masked dimensions. """ mask_shape = list(map(int, self.mask.shape)) graph_typecheck.assert_shape(expanded_tensor, mask_shape + expected_extra_dims) value_if_masked = expanded_tensor.dtype.as_numpy_dtype(value_if_masked) if_masked_tensor = tf.fill(expanded_tensor.shape, value_if_masked) mask = self.mask for i in range(2, 2 + len(expected_extra_dims)): mask = tf.expand_dims(mask, axis=i) mask = tf.tile(mask, [1, 1] + expected_extra_dims) return tf.where(mask, expanded_tensor, if_masked_tensor) def initial_layer( window_feature: WindowFeatures, *, clip_magnitude=10.0, include_flux_and_time=False ) -> tf.Tensor: features = tf.expand_dims(window_feature.dflux_dt(clip_magnitude=clip_magnitude), 2) if include_flux_and_time: dflux = tf.expand_dims(window_feature.dflux, 2) dtime = tf.expand_dims(window_feature.dtime, 2) features = tf.concat([features, dflux, dtime], axis=2, name="initial_layer_concat") return features class CutoffData: def __init__(self, config_json: dict): self.window_size: int = config_json["window_size"] self.band_time_diff: int = config_json["band_time_diff"] self.embedding_size: int = config_json["desired_num_cutoffs"] self.models_by_band = {} for solution in config_json["solutions"]: band = solution["band"] self.models_by_band.setdefault(band, {}) self.models_by_band[band][solution["column"]] = ( solution["median_scale"], solution["cutoffs"], ) def dflux_dt_dflux_dtime_scales(self, band: str, dtype=np.float32): """Generates a vector of scalar offsets. :param band: Band name. :param dtype: Data type of output array. :return: <dtype>[3] matrix of scales per channel. """ return np.array([ self.models_by_band[band]["dflux_dt"][0], self.models_by_band[band]["dflux"][0], self.models_by_band[band]["dtime"][0], ], dtype=dtype) def dflux_dt_dflux_dtime_cutoffs(self, band: str, dtype=np.float32): """Generates a matrix of [dflux_dt, dflux, dtime]. :param band: Band name. :param dtype: Data type of output array. :return: <dtype>[3, self.embedding_size] matrix of cutoffs. """ return np.array([ self.models_by_band[band]["dflux_dt"][1], self.models_by_band[band]["dflux"][1], self.models_by_band[band]["dtime"][1], ], dtype=dtype) @classmethod def from_file(cls, filename: pathlib.Path): if not filename.is_file(): raise EnvironmentError( "Please generate tf_align_model data using the tf_align_model_input_" "feature_percentiles.ipynb notebook or run `git clone https://github.com/" "gatoatigrado/plasticc-generated-data data/tf_align_model`.") with open(str(filename)) as f: return cls(json.load(f)) class Nonlinearity(enum.Enum): SIGMOID = 1 GAUSSIAN = 2 def nonlinearity_fcn(typ: Nonlinearity): if typ == Nonlinearity.SIGMOID: return tf.sigmoid else: assert typ == Nonlinearity.GAUSSIAN return lambda arg: tf.exp(-arg * arg) def initial_layer_binned( initial_layer_features: tf.Tensor, cutoff_data: CutoffData, band: str, soft_onehot: Nonlinearity = Nonlinearity.SIGMOID ): batch_size, twice_window_size, channels = map(int, initial_layer_features.shape) nonlinearity = nonlinearity_fcn(soft_onehot) if channels == 3: scales = cutoff_data.dflux_dt_dflux_dtime_scales(band) cutoffs = cutoff_data.dflux_dt_dflux_dtime_cutoffs(band) cutoffs_batch_window = tf.expand_dims(tf.expand_dims(cutoffs, 0), 0) scales_batch_window = tf.expand_dims( tf.expand_dims(tf.expand_dims(scales, 0), 0), -1 ) init_layer_per_cutoff = tf.expand_dims(initial_layer_features, -1) graph_typecheck.assert_shape( cutoffs_batch_window, [1, 1, channels, cutoff_data.embedding_size] ) graph_typecheck.assert_shape(scales_batch_window, [1, 1, channels, 1]) graph_typecheck.assert_shape( init_layer_per_cutoff, [batch_size, twice_window_size, channels, 1] ) result = nonlinearity( (init_layer_per_cutoff - cutoffs_batch_window) / scales_batch_window ) return graph_typecheck.assert_shape( result, [batch_size, twice_window_size, channels, cutoff_data.embedding_size] ) else: raise NotImplementedError(f"{channels}-size data not implemented.") def cutoff_data_for_window_size(window_size): if window_size == 10: cutoff_data = CutoffData.from_file( path_util.tf_align_data / 'feature_extraction' / 'cutoffs__window_sz-10__2018-11-23.json' ) else: raise ValueError("No supported cutoff data for window size") return cutoff_data def initial_layer_binned_defaults( band_features: dict, band: str, batch_size: int, window_size: int, value_if_masked: float = 0.0, soft_onehot: Nonlinearity = Nonlinearity.SIGMOID ): cutoff_data = cutoff_data_for_window_size(window_size) wf = WindowFeatures(band_features, batch_size=batch_size, window_size=window_size) init_layer = initial_layer(wf, include_flux_and_time=True) binned = initial_layer_binned( init_layer, cutoff_data=cutoff_data, band=band, soft_onehot=soft_onehot ) masked = wf.masked( binned, value_if_masked=value_if_masked, expected_extra_dims=[3, cutoff_data.embedding_size] ) return masked def per_band_model_fn( band_features, band_name, params, value_if_masked: float = 0.0, soft_onehot: Nonlinearity = Nonlinearity.SIGMOID ): batch_size = params["batch_size"] window_size = params["window_size"] return initial_layer_binned_defaults( band_features, band=band_name, batch_size=batch_size, window_size=window_size, value_if_masked=value_if_masked, soft_onehot=soft_onehot ) def feature_model_fn(features, params): band_settings = band_settings_params.BandSettings.from_params(params) per_band_data = band_settings.per_band_sub_model_fn_with_band_name( per_band_model_fn, features, params=params, value_if_masked=params.get("value_if_masked", 0.0), soft_onehot=Nonlinearity[params.get("input_soft_onehot", "sigmoid").upper()] ) return graph_typecheck.assert_shape( tf.stack(per_band_data, axis=4), [ params["batch_size"], 2 * params["window_size"], 3, cutoff_data_for_window_size(params["window_size"]).embedding_size, band_settings.nbands, ] )
[ "tensorflow.clip_by_value", "tensorflow.fill", "tensorflow.concat", "tensorflow.stack", "tensorflow.expand_dims", "tensorflow.exp", "tensorflow.where", "numpy.array", "tensorflow.sequence_mask", "tensorflow.tile" ]
justice/features/dense_extracted_features.py
[(34, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['(window_size - after_padding)'], {'maxlen': 'window_size'}), True, 'import tensorflow as tf\n'), (311, 'justice.features.band_settings_params.BandSettings.from_params', 'band_settings_params.BandSettings.from_params', (['params'], {}), False, 'from justice.features import band_settings_params\n'), (29, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['before_padding'], {'maxlen': 'window_size'}), True, 'import tensorflow as tf\n'), (134, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['expanded_tensor', '(mask_shape + expected_extra_dims)'], {}), False, 'from justice.align_model import graph_typecheck\n'), (137, 'tensorflow.fill', 'tf.fill', (['expanded_tensor.shape', 'value_if_masked'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.tile', 'tf.tile', (['mask', '([1, 1] + expected_extra_dims)'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.where', 'tf.where', (['mask', 'expanded_tensor', 'if_masked_tensor'], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.expand_dims', 'tf.expand_dims', (['window_feature.dflux', '(2)'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.expand_dims', 'tf.expand_dims', (['window_feature.dtime', '(2)'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.concat', 'tf.concat', (['[features, dflux, dtime]'], {'axis': '(2)', 'name': '"""initial_layer_concat"""'}), True, 'import tensorflow as tf\n'), (179, 'numpy.array', 'np.array', (["[self.models_by_band[band]['dflux_dt'][0], self.models_by_band[band][\n 'dflux'][0], self.models_by_band[band]['dtime'][0]]"], {'dtype': 'dtype'}), True, 'import numpy as np\n'), (193, 'numpy.array', 'np.array', (["[self.models_by_band[band]['dflux_dt'][1], self.models_by_band[band][\n 'dflux'][1], self.models_by_band[band]['dtime'][1]]"], {'dtype': 'dtype'}), True, 'import numpy as np\n'), (240, 'tensorflow.expand_dims', 'tf.expand_dims', (['initial_layer_features', '(-1)'], {}), True, 'import tensorflow as tf\n'), (241, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['cutoffs_batch_window', '[1, 1, channels, cutoff_data.embedding_size]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (244, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['scales_batch_window', '[1, 1, channels, 1]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (245, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['init_layer_per_cutoff', '[batch_size, twice_window_size, channels, 1]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (251, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['result', '[batch_size, twice_window_size, channels, cutoff_data.embedding_size]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (320, 'tensorflow.stack', 'tf.stack', (['per_band_data'], {'axis': '(4)'}), True, 'import tensorflow as tf\n'), (62, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['t', '[batch_size]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (65, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['t', '[batch_size, window_size]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (68, 'justice.align_model.graph_typecheck.assert_shape', 'graph_typecheck.assert_shape', (['t', '[batch_size, 2 * window_size]'], {}), False, 'from justice.align_model import graph_typecheck\n'), (115, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['result'], {'clip_value_min': '(-clip_magnitude)', 'clip_value_max': 'clip_magnitude'}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.expand_dims', 'tf.expand_dims', (['mask'], {'axis': 'i'}), True, 'import tensorflow as tf\n'), (221, 'tensorflow.exp', 'tf.exp', (['(-arg * arg)'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.expand_dims', 'tf.expand_dims', (['cutoffs', '(0)'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.expand_dims', 'tf.expand_dims', (['t', '(1)'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.concat', 'tf.concat', (['[before_time, after_time]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.concat', 'tf.concat', (['[before_flux, after_flux]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.concat', 'tf.concat', (['[left_mask, right_mask]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (208, 'json.load', 'json.load', (['f'], {}), False, 'import json\n'), (238, 'tensorflow.expand_dims', 'tf.expand_dims', (['scales', '(0)'], {}), True, 'import tensorflow as tf\n')]
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
# 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 slim.data.dataset_data_provider.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile from tensorflow.contrib.slim.python.slim import queues from tensorflow.contrib.slim.python.slim.data import dataset from tensorflow.contrib.slim.python.slim.data import dataset_data_provider from tensorflow.contrib.slim.python.slim.data import test_utils from tensorflow.contrib.slim.python.slim.data import tfexample_decoder from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import image_ops from tensorflow.python.ops import io_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.platform import gfile from tensorflow.python.platform import test def _resize_image(image, height, width): image = array_ops.expand_dims(image, 0) image = image_ops.resize_bilinear(image, [height, width]) return array_ops.squeeze(image, [0]) def _create_tfrecord_dataset(tmpdir): if not gfile.Exists(tmpdir): gfile.MakeDirs(tmpdir) data_sources = test_utils.create_tfrecord_files(tmpdir, num_files=1) keys_to_features = { 'image/encoded': parsing_ops.FixedLenFeature( shape=(), dtype=dtypes.string, default_value=''), 'image/format': parsing_ops.FixedLenFeature( shape=(), dtype=dtypes.string, default_value='jpeg'), 'image/class/label': parsing_ops.FixedLenFeature( shape=[1], dtype=dtypes.int64, default_value=array_ops.zeros( [1], dtype=dtypes.int64)) } items_to_handlers = { 'image': tfexample_decoder.Image(), 'label': tfexample_decoder.Tensor('image/class/label'), } decoder = tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers) return dataset.Dataset( data_sources=data_sources, reader=io_ops.TFRecordReader, decoder=decoder, num_samples=100, items_to_descriptions=None) class DatasetDataProviderTest(test.TestCase): def testTFRecordDataset(self): dataset_dir = tempfile.mkdtemp(prefix=os.path.join(self.get_temp_dir(), 'tfrecord_dataset')) height = 300 width = 280 with self.cached_session(): test_dataset = _create_tfrecord_dataset(dataset_dir) provider = dataset_data_provider.DatasetDataProvider(test_dataset) key, image, label = provider.get(['record_key', 'image', 'label']) image = _resize_image(image, height, width) with session.Session('') as sess: with queues.QueueRunners(sess): key, image, label = sess.run([key, image, label]) split_key = key.decode('utf-8').split(':') self.assertEqual(2, len(split_key)) self.assertEqual(test_dataset.data_sources[0], split_key[0]) self.assertTrue(split_key[1].isdigit()) self.assertListEqual([height, width, 3], list(image.shape)) self.assertListEqual([1], list(label.shape)) def testTFRecordSeparateGetDataset(self): dataset_dir = tempfile.mkdtemp(prefix=os.path.join(self.get_temp_dir(), 'tfrecord_separate_get')) height = 300 width = 280 with self.cached_session(): provider = dataset_data_provider.DatasetDataProvider( _create_tfrecord_dataset(dataset_dir)) [image] = provider.get(['image']) [label] = provider.get(['label']) image = _resize_image(image, height, width) with session.Session('') as sess: with queues.QueueRunners(sess): image, label = sess.run([image, label]) self.assertListEqual([height, width, 3], list(image.shape)) self.assertListEqual([1], list(label.shape)) def testConflictingRecordKeyItem(self): dataset_dir = tempfile.mkdtemp(prefix=os.path.join(self.get_temp_dir(), 'tfrecord_dataset')) with self.cached_session(): with self.assertRaises(ValueError): dataset_data_provider.DatasetDataProvider( _create_tfrecord_dataset(dataset_dir), record_key='image') if __name__ == '__main__': test.main()
[ "tensorflow.python.ops.parsing_ops.FixedLenFeature", "tensorflow.contrib.slim.python.slim.data.dataset.Dataset", "tensorflow.contrib.slim.python.slim.queues.QueueRunners", "tensorflow.contrib.slim.python.slim.data.tfexample_decoder.Tensor", "tensorflow.contrib.slim.python.slim.data.test_utils.create_tfrecord_files", "tensorflow.python.platform.gfile.MakeDirs", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.platform.gfile.Exists", "tensorflow.python.platform.test.main", "tensorflow.contrib.slim.python.slim.data.tfexample_decoder.Image", "tensorflow.contrib.slim.python.slim.data.dataset_data_provider.DatasetDataProvider", "tensorflow.contrib.slim.python.slim.data.tfexample_decoder.TFExampleDecoder", "tensorflow.python.ops.image_ops.resize_bilinear", "tensorflow.python.client.session.Session", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.array_ops.expand_dims" ]
tensorflow/contrib/slim/python/slim/data/dataset_data_provider_test.py
[(40, 'tensorflow.python.ops.array_ops.expand_dims', 'array_ops.expand_dims', (['image', '(0)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (41, 'tensorflow.python.ops.image_ops.resize_bilinear', 'image_ops.resize_bilinear', (['image', '[height, width]'], {}), False, 'from tensorflow.python.ops import image_ops\n'), (42, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['image', '[0]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (49, 'tensorflow.contrib.slim.python.slim.data.test_utils.create_tfrecord_files', 'test_utils.create_tfrecord_files', (['tmpdir'], {'num_files': '(1)'}), False, 'from tensorflow.contrib.slim.python.slim.data import test_utils\n'), (71, 'tensorflow.contrib.slim.python.slim.data.tfexample_decoder.TFExampleDecoder', 'tfexample_decoder.TFExampleDecoder', (['keys_to_features', 'items_to_handlers'], {}), False, 'from tensorflow.contrib.slim.python.slim.data import tfexample_decoder\n'), (74, 'tensorflow.contrib.slim.python.slim.data.dataset.Dataset', 'dataset.Dataset', ([], {'data_sources': 'data_sources', 'reader': 'io_ops.TFRecordReader', 'decoder': 'decoder', 'num_samples': '(100)', 'items_to_descriptions': 'None'}), False, 'from tensorflow.contrib.slim.python.slim.data import dataset\n'), (137, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (46, 'tensorflow.python.platform.gfile.Exists', 'gfile.Exists', (['tmpdir'], {}), False, 'from tensorflow.python.platform import gfile\n'), (47, 'tensorflow.python.platform.gfile.MakeDirs', 'gfile.MakeDirs', (['tmpdir'], {}), False, 'from tensorflow.python.platform import gfile\n'), (53, 'tensorflow.python.ops.parsing_ops.FixedLenFeature', 'parsing_ops.FixedLenFeature', ([], {'shape': '()', 'dtype': 'dtypes.string', 'default_value': '""""""'}), False, 'from tensorflow.python.ops import parsing_ops\n'), (56, 'tensorflow.python.ops.parsing_ops.FixedLenFeature', 'parsing_ops.FixedLenFeature', ([], {'shape': '()', 'dtype': 'dtypes.string', 'default_value': '"""jpeg"""'}), False, 'from tensorflow.python.ops import parsing_ops\n'), (67, 'tensorflow.contrib.slim.python.slim.data.tfexample_decoder.Image', 'tfexample_decoder.Image', ([], {}), False, 'from tensorflow.contrib.slim.python.slim.data import tfexample_decoder\n'), (68, 'tensorflow.contrib.slim.python.slim.data.tfexample_decoder.Tensor', 'tfexample_decoder.Tensor', (['"""image/class/label"""'], {}), False, 'from tensorflow.contrib.slim.python.slim.data import tfexample_decoder\n'), (93, 'tensorflow.contrib.slim.python.slim.data.dataset_data_provider.DatasetDataProvider', 'dataset_data_provider.DatasetDataProvider', (['test_dataset'], {}), False, 'from tensorflow.contrib.slim.python.slim.data import dataset_data_provider\n'), (121, 'tensorflow.python.client.session.Session', 'session.Session', (['""""""'], {}), False, 'from tensorflow.python.client import session\n'), (62, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[1]'], {'dtype': 'dtypes.int64'}), False, 'from tensorflow.python.ops import array_ops\n'), (97, 'tensorflow.python.client.session.Session', 'session.Session', (['""""""'], {}), False, 'from tensorflow.python.client import session\n'), (122, 'tensorflow.contrib.slim.python.slim.queues.QueueRunners', 'queues.QueueRunners', (['sess'], {}), False, 'from tensorflow.contrib.slim.python.slim import queues\n'), (98, 'tensorflow.contrib.slim.python.slim.queues.QueueRunners', 'queues.QueueRunners', (['sess'], {}), False, 'from tensorflow.contrib.slim.python.slim import queues\n')]
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
# 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 VariableClippingOptimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import socket import numpy as np from tensorflow.contrib.opt.python.training import variable_clipping_optimizer from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent from tensorflow.python.training import server_lib class VariableClippingOptimizerTest(test.TestCase): def _setupCluster(self): def get_open_port(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except IOError: s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.bind(("", 0)) port = s.getsockname()[1] s.close() return port port1 = get_open_port() port2 = get_open_port() cs = server_lib.ClusterSpec({ "worker": ["localhost:%s" % port1], "ps": ["localhost:%s" % port2] }) worker = server_lib.Server(cs, job_name="worker", start=True) ps = server_lib.Server(cs, job_name="ps", start=True) return worker, ps @contextlib.contextmanager def _maybeWithDevice(self, device): if device is not None: with ops.device(device): yield else: yield def _setupDense(self, is_distributed, dtype): with self._maybeWithDevice("/job:ps" if is_distributed else None): var0 = variables.Variable([[0.0, 1.0], [2.0, 3.0]], dtype=dtype) var1 = variables.Variable([4.0, 5.0], dtype=dtype) with self._maybeWithDevice("/job:worker" if is_distributed else None): grads0 = constant_op.constant([[0.1, 0.1], [0.1, 0.1]], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd = gradient_descent.GradientDescentOptimizer(3.0) clip_opt = variable_clipping_optimizer.VariableClippingOptimizer( sgd, {var0: [1]}, 2.0) update_op = clip_opt.apply_gradients( list(zip([grads0, grads1], [var0, var1]))) variables.global_variables_initializer().run() return var0, var1, update_op def _assertDenseCorrect(self, var0, var1, update_op): # Fetch params to validate initial values self.assertAllCloseAccordingToType([[0.0, 1.0], [2.0, 3.0]], var0.eval()) self.assertAllCloseAccordingToType([4.0, 5.0], var1.eval()) # Run 1 step of sgd, clipping each var0[i] to max L2-norm 2.0 update_op.run() # Validate updated params var0_out = var0.eval() # var0[0] has norm < 2.0, so it is not clipped. self.assertAllCloseAccordingToType([(0.0 - 3.0 * 0.1), (1.0 - 3.0 * 0.1)], var0_out[0]) # var0[1] has norm > 2.0, so it is clipped. expected_unclipped = np.array([(2.0 - 3.0 * 0.1), (3.0 - 3.0 * 0.1)]) self.assertAllCloseAccordingToType(2.0 * expected_unclipped / np.linalg.norm(expected_unclipped), var0_out[1]) # var1 is not in the var list, so it should not be clipped self.assertAllCloseAccordingToType([4.0 - 3.0 * 0.01, 5.0 - 3.0 * 0.01], var1.eval()) def _setupSparse(self, is_distributed, dtype): with self._maybeWithDevice("/job:ps" if is_distributed else None): var0 = variables.Variable( [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]], dtype=dtype) var1 = variables.Variable( [[0.0, 1.0], [0.0, 3.0], [0.0, 5.0]], dtype=dtype) with self._maybeWithDevice("/job:worker" if is_distributed else None): grads = ops.IndexedSlices( constant_op.constant( [[0.1, 0.1], [0.1, 0.1]], dtype=dtype), [0, 2], [3, 2]) sgd = gradient_descent.GradientDescentOptimizer(3.0) clip_opt = variable_clipping_optimizer.VariableClippingOptimizer( sgd, {var0: [1], var1: [0]}, 2.0) update_op = clip_opt.apply_gradients( list(zip([grads, grads], [var0, var1]))) variables.global_variables_initializer().run() return var0, var1, update_op def _assertSparseCorrect(self, var0, var1, update_op): # Fetch params to validate initial values self.assertAllCloseAccordingToType([[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]], var0.eval()) self.assertAllCloseAccordingToType([[0.0, 1.0], [0.0, 3.0], [0.0, 5.0]], var1.eval()) # Run 1 step of sgd update_op.run() # var1 is clipped along the sparse dimension, so defaults to using dense # calculations. There should be a warning logged, but the numerics # should still be correct. var1_out = var1.eval() # var1[:, 0] has norm < 2.0, so it is not clipped. self.assertAllCloseAccordingToType( [(0.0 - 3.0 * 0.1), 0.0, (0.0 - 3.0 * 0.1)], var1_out[:, 0]) # var1[:, 1] has norm > 2.0, so it is clipped. expected_unclipped = np.array([(1.0 - 3.0 * 0.1), 3.0, (5.0 - 3.0 * 0.1)]) self.assertAllCloseAccordingToType(2.0 * expected_unclipped / np.linalg.norm(expected_unclipped), var1_out[:, 1]) # Validate updated params var0_out = var0.eval() # var0[0] has norm < 2.0, so it is not clipped. self.assertAllCloseAccordingToType([(0.0 - 3.0 * 0.1), (1.0 - 3.0 * 0.1)], var0_out[0]) # var0[1] has no gradients, so it should remain unchanged. self.assertAllCloseAccordingToType([2.0, 3.0], var0_out[1]) # var0[2] has norm > 2.0, so it is clipped. expected_unclipped = np.array([(4.0 - 3.0 * 0.1), (5.0 - 3.0 * 0.1)]) self.assertAllCloseAccordingToType(2.0 * expected_unclipped / np.linalg.norm(expected_unclipped), var0_out[2]) def testDenseLocal(self): for dtype in [dtypes.float32, dtypes.float64, dtypes.half]: with self.cached_session(): var0, var1, update_op = self._setupDense(False, dtype) self._assertDenseCorrect(var0, var1, update_op) def testDenseDistributed(self): worker, unused_ps = self._setupCluster() for dtype in [dtypes.float64, dtypes.half, dtypes.float32]: with session.Session(worker.target): var0, var1, update_op = self._setupDense(True, dtype) self._assertDenseCorrect(var0, var1, update_op) def testSparseLocal(self): for dtype in [dtypes.float64, dtypes.float32, dtypes.half]: with self.cached_session(): var0, var1, update_op = self._setupSparse(False, dtype) self._assertSparseCorrect(var0, var1, update_op) def testSparseDistributed(self): worker, unused_ps = self._setupCluster() for dtype in [dtypes.half, dtypes.float32, dtypes.float64]: with session.Session(worker.target): var0, var1, update_op = self._setupSparse(True, dtype) self._assertSparseCorrect(var0, var1, update_op) if __name__ == "__main__": test.main()
[ "tensorflow.python.framework.ops.device", "numpy.linalg.norm", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.client.session.Session", "tensorflow.python.platform.test.main", "tensorflow.python.training.server_lib.Server", "tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer", "numpy.array", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "tensorflow.python.framework.constant_op.constant" ]
tensorflow/contrib/opt/python/training/variable_clipping_optimizer_test.py
[(187, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (49, 'tensorflow.python.training.server_lib.ClusterSpec', 'server_lib.ClusterSpec', (["{'worker': ['localhost:%s' % port1], 'ps': ['localhost:%s' % port2]}"], {}), False, 'from tensorflow.python.training import server_lib\n'), (54, 'tensorflow.python.training.server_lib.Server', 'server_lib.Server', (['cs'], {'job_name': '"""worker"""', 'start': '(True)'}), False, 'from tensorflow.python.training import server_lib\n'), (55, 'tensorflow.python.training.server_lib.Server', 'server_lib.Server', (['cs'], {'job_name': '"""ps"""', 'start': '(True)'}), False, 'from tensorflow.python.training import server_lib\n'), (96, 'numpy.array', 'np.array', (['[2.0 - 3.0 * 0.1, 3.0 - 3.0 * 0.1]'], {}), True, 'import numpy as np\n'), (141, 'numpy.array', 'np.array', (['[1.0 - 3.0 * 0.1, 3.0, 5.0 - 3.0 * 0.1]'], {}), True, 'import numpy as np\n'), (154, 'numpy.array', 'np.array', (['[4.0 - 3.0 * 0.1, 5.0 - 3.0 * 0.1]'], {}), True, 'import numpy as np\n'), (69, 'tensorflow.python.ops.variables.Variable', 'variables.Variable', (['[[0.0, 1.0], [2.0, 3.0]]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.ops import variables\n'), (70, 'tensorflow.python.ops.variables.Variable', 'variables.Variable', (['[4.0, 5.0]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.ops import variables\n'), (72, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0.1, 0.1], [0.1, 0.1]]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.framework import constant_op\n'), (73, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[0.01, 0.01]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.framework import constant_op\n'), (74, 'tensorflow.python.training.gradient_descent.GradientDescentOptimizer', 'gradient_descent.GradientDescentOptimizer', (['(3.0)'], {}), False, 'from tensorflow.python.training import gradient_descent\n'), (75, 'tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer', 'variable_clipping_optimizer.VariableClippingOptimizer', (['sgd', '{var0: [1]}', '(2.0)'], {}), False, 'from tensorflow.contrib.opt.python.training import variable_clipping_optimizer\n'), (106, 'tensorflow.python.ops.variables.Variable', 'variables.Variable', (['[[0.0, 1.0], [2.0, 3.0], [4.0, 5.0]]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.ops import variables\n'), (108, 'tensorflow.python.ops.variables.Variable', 'variables.Variable', (['[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0]]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.ops import variables\n'), (114, 'tensorflow.python.training.gradient_descent.GradientDescentOptimizer', 'gradient_descent.GradientDescentOptimizer', (['(3.0)'], {}), False, 'from tensorflow.python.training import gradient_descent\n'), (115, 'tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer', 'variable_clipping_optimizer.VariableClippingOptimizer', (['sgd', '{var0: [1], var1: [0]}', '(2.0)'], {}), False, 'from tensorflow.contrib.opt.python.training import variable_clipping_optimizer\n'), (39, 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), False, 'import socket\n'), (62, 'tensorflow.python.framework.ops.device', 'ops.device', (['device'], {}), False, 'from tensorflow.python.framework import ops\n'), (98, 'numpy.linalg.norm', 'np.linalg.norm', (['expected_unclipped'], {}), True, 'import numpy as np\n'), (112, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0.1, 0.1], [0.1, 0.1]]'], {'dtype': 'dtype'}), False, 'from tensorflow.python.framework import constant_op\n'), (143, 'numpy.linalg.norm', 'np.linalg.norm', (['expected_unclipped'], {}), True, 'import numpy as np\n'), (156, 'numpy.linalg.norm', 'np.linalg.norm', (['expected_unclipped'], {}), True, 'import numpy as np\n'), (168, 'tensorflow.python.client.session.Session', 'session.Session', (['worker.target'], {}), False, 'from tensorflow.python.client import session\n'), (181, 'tensorflow.python.client.session.Session', 'session.Session', (['worker.target'], {}), False, 'from tensorflow.python.client import session\n'), (41, 'socket.socket', 'socket.socket', (['socket.AF_INET6', 'socket.SOCK_STREAM'], {}), False, 'import socket\n'), (80, 'tensorflow.python.ops.variables.global_variables_initializer', 'variables.global_variables_initializer', ([], {}), False, 'from tensorflow.python.ops import variables\n'), (120, 'tensorflow.python.ops.variables.global_variables_initializer', 'variables.global_variables_initializer', ([], {}), False, 'from tensorflow.python.ops import variables\n')]
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
# 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. # ============================================================================== """Ops tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.learn.python.learn import ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import random_seed from tensorflow.python.ops import variables from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class OpsTest(test.TestCase): """Ops tests.""" def test_softmax_classifier(self): with self.cached_session() as session: features = array_ops.placeholder(dtypes.float32, [None, 3]) labels = array_ops.placeholder(dtypes.float32, [None, 2]) weights = constant_op.constant([[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]]) biases = constant_op.constant([0.2, 0.3]) class_weight = constant_op.constant([0.1, 0.9]) prediction, loss = ops.softmax_classifier(features, labels, weights, biases, class_weight) self.assertEqual(prediction.get_shape()[1], 2) self.assertEqual(loss.get_shape(), []) value = session.run(loss, {features: [[0.2, 0.3, 0.2]], labels: [[0, 1]]}) self.assertAllClose(value, 0.55180627) def test_embedding_lookup(self): d_embed = 5 n_embed = 10 ids_shape = (2, 3, 4) embeds = np.random.randn(n_embed, d_embed) ids = np.random.randint(0, n_embed, ids_shape) with self.cached_session(): embed_np = embeds[ids] embed_tf = ops.embedding_lookup(embeds, ids).eval() self.assertEqual(embed_np.shape, embed_tf.shape) self.assertAllClose(embed_np, embed_tf) def test_categorical_variable(self): random_seed.set_random_seed(42) with self.cached_session() as sess: cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2]) embeddings = ops.categorical_variable( cat_var_idx, n_classes=5, embedding_size=10, name="my_cat_var") sess.run(variables.global_variables_initializer()) emb1 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 1], [2, 3]]}) emb2 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 2], [1, 3]]}) self.assertEqual(emb1.shape, emb2.shape) self.assertAllEqual(np.transpose(emb2, axes=[1, 0, 2]), emb1) if __name__ == "__main__": test.main()
[ "tensorflow.contrib.learn.python.learn.ops.softmax_classifier", "tensorflow.contrib.learn.python.learn.ops.categorical_variable", "tensorflow.contrib.learn.python.learn.ops.embedding_lookup", "tensorflow.python.ops.array_ops.placeholder", "numpy.random.randn", "tensorflow.python.platform.test.main", "numpy.transpose", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.framework.random_seed.set_random_seed", "numpy.random.randint" ]
tensorflow/contrib/learn/python/learn/ops/ops_test.py
[(77, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (53, 'numpy.random.randn', 'np.random.randn', (['n_embed', 'd_embed'], {}), True, 'import numpy as np\n'), (54, 'numpy.random.randint', 'np.random.randint', (['(0)', 'n_embed', 'ids_shape'], {}), True, 'import numpy as np\n'), (62, 'tensorflow.python.framework.random_seed.set_random_seed', 'random_seed.set_random_seed', (['(42)'], {}), False, 'from tensorflow.python.framework import random_seed\n'), (37, 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float32', '[None, 3]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (38, 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.float32', '[None, 2]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (39, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (40, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[0.2, 0.3]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (41, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[0.1, 0.9]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (42, 'tensorflow.contrib.learn.python.learn.ops.softmax_classifier', 'ops.softmax_classifier', (['features', 'labels', 'weights', 'biases', 'class_weight'], {}), False, 'from tensorflow.contrib.learn.python.learn import ops\n'), (64, 'tensorflow.python.ops.array_ops.placeholder', 'array_ops.placeholder', (['dtypes.int64', '[2, 2]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (65, 'tensorflow.contrib.learn.python.learn.ops.categorical_variable', 'ops.categorical_variable', (['cat_var_idx'], {'n_classes': '(5)', 'embedding_size': '(10)', 'name': '"""my_cat_var"""'}), False, 'from tensorflow.contrib.learn.python.learn import ops\n'), (73, 'numpy.transpose', 'np.transpose', (['emb2'], {'axes': '[1, 0, 2]'}), True, 'import numpy as np\n'), (67, 'tensorflow.python.ops.variables.global_variables_initializer', 'variables.global_variables_initializer', ([], {}), False, 'from tensorflow.python.ops import variables\n'), (57, 'tensorflow.contrib.learn.python.learn.ops.embedding_lookup', 'ops.embedding_lookup', (['embeds', 'ids'], {}), False, 'from tensorflow.contrib.learn.python.learn import ops\n')]
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
# 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. # ============================================================================== r"""TensorFlow Eager Execution Example: RNN Colorbot. This example builds, trains, and evaluates a multi-layer RNN that can be run with eager execution enabled. The RNN is trained to map color names to their RGB values: it takes as input a one-hot encoded character sequence and outputs a three-tuple (R, G, B) (scaled by 1/255). For example, say we'd like the RNN Colorbot to generate the RGB values for the color white. To represent our query in a form that the Colorbot could understand, we would create a sequence of five 256-long vectors encoding the ASCII values of the characters in "white". The first vector in our sequence would be 0 everywhere except for the ord("w")-th position, where it would be 1, the second vector would be 0 everywhere except for the ord("h")-th position, where it would be 1, and similarly for the remaining three vectors. We refer to such indicator vectors as "one-hot encodings" of characters. After consuming these vectors, a well-trained Colorbot would output the three tuple (1, 1, 1), since the RGB values for white are (255, 255, 255). We are of course free to ask the colorbot to generate colors for any string we'd like, such as "steel gray," "tensorflow orange," or "green apple," though your mileage may vary as your queries increase in creativity. This example shows how to: 1. read, process, (one-hot) encode, and pad text data via the Datasets API; 2. build a trainable model; 3. implement a multi-layer RNN using Python control flow constructs (e.g., a for loop); 4. train a model using an iterative gradient-based method; and The data used in this example is licensed under the Creative Commons Attribution-ShareAlike License and is available at https://en.wikipedia.org/wiki/List_of_colors:_A-F https://en.wikipedia.org/wiki/List_of_colors:_G-M https://en.wikipedia.org/wiki/List_of_colors:_N-Z This example was adapted from https://github.com/random-forests/tensorflow-workshop/tree/master/extras/colorbot """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import functools import os import sys import time import urllib import six import tensorflow as tf from tensorflow.contrib.eager.python import tfe try: import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False layers = tf.keras.layers def parse(line): """Parse a line from the colors dataset.""" # Each line of the dataset is comma-separated and formatted as # color_name, r, g, b # so `items` is a list [color_name, r, g, b]. items = tf.string_split([line], ",").values rgb = tf.string_to_number(items[1:], out_type=tf.float32) / 255. # Represent the color name as a one-hot encoded character sequence. color_name = items[0] chars = tf.one_hot(tf.decode_raw(color_name, tf.uint8), depth=256) # The sequence length is needed by our RNN. length = tf.cast(tf.shape(chars)[0], dtype=tf.int64) return rgb, chars, length def maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not tf.gfile.Exists(work_directory): tf.gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not tf.gfile.Exists(filepath): temp_file_name, _ = urllib.request.urlretrieve(source_url) tf.gfile.Copy(temp_file_name, filepath) with tf.gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath def load_dataset(data_dir, url, batch_size): """Loads the colors data at path into a PaddedDataset.""" # Downloads data at url into data_dir/basename(url). The dataset has a header # row (color_name, r, g, b) followed by comma-separated lines. path = maybe_download(os.path.basename(url), data_dir, url) # This chain of commands loads our data by: # 1. skipping the header; (.skip(1)) # 2. parsing the subsequent lines; (.map(parse)) # 3. shuffling the data; (.shuffle(...)) # 3. grouping the data into padded batches (.padded_batch(...)). dataset = tf.data.TextLineDataset(path).skip(1).map(parse).shuffle( buffer_size=10000).padded_batch( batch_size, padded_shapes=([None], [None, None], [])) return dataset # pylint: disable=not-callable class RNNColorbot(tf.keras.Model): """Multi-layer (LSTM) RNN that regresses on real-valued vector labels. """ def __init__(self, rnn_cell_sizes, label_dimension, keep_prob): """Constructs an RNNColorbot. Args: rnn_cell_sizes: list of integers denoting the size of each LSTM cell in the RNN; rnn_cell_sizes[i] is the size of the i-th layer cell label_dimension: the length of the labels on which to regress keep_prob: (1 - dropout probability); dropout is applied to the outputs of each LSTM layer """ super(RNNColorbot, self).__init__(name="") self.label_dimension = label_dimension self.keep_prob = keep_prob self.cells = tf.contrib.checkpoint.List( [tf.nn.rnn_cell.BasicLSTMCell(size) for size in rnn_cell_sizes]) self.relu = layers.Dense( label_dimension, activation=tf.nn.relu, name="relu") def call(self, inputs, training=False): """Implements the RNN logic and prediction generation. Args: inputs: A tuple (chars, sequence_length), where chars is a batch of one-hot encoded color names represented as a Tensor with dimensions [batch_size, time_steps, 256] and sequence_length holds the length of each character sequence (color name) as a Tensor with dimension [batch_size]. training: whether the invocation is happening during training Returns: A tensor of dimension [batch_size, label_dimension] that is produced by passing chars through a multi-layer RNN and applying a ReLU to the final hidden state. """ (chars, sequence_length) = inputs # Transpose the first and second dimensions so that chars is of shape # [time_steps, batch_size, dimension]. chars = tf.transpose(chars, [1, 0, 2]) # The outer loop cycles through the layers of the RNN; the inner loop # executes the time steps for a particular layer. batch_size = int(chars.shape[1]) for l in range(len(self.cells)): cell = self.cells[l] outputs = [] state = cell.zero_state(batch_size, tf.float32) # Unstack the inputs to obtain a list of batches, one for each time step. chars = tf.unstack(chars, axis=0) for ch in chars: output, state = cell(ch, state) outputs.append(output) # The outputs of this layer are the inputs of the subsequent layer. chars = tf.stack(outputs, axis=0) if training: chars = tf.nn.dropout(chars, self.keep_prob) # Extract the correct output (i.e., hidden state) for each example. All the # character sequences in this batch were padded to the same fixed length so # that they could be easily fed through the above RNN loop. The # `sequence_length` vector tells us the true lengths of the character # sequences, letting us obtain for each sequence the hidden state that was # generated by its non-padding characters. batch_range = [i for i in range(batch_size)] indices = tf.stack([sequence_length - 1, batch_range], axis=1) hidden_states = tf.gather_nd(chars, indices) return self.relu(hidden_states) def loss(labels, predictions): """Computes mean squared loss.""" return tf.reduce_mean(tf.squared_difference(predictions, labels)) def test(model, eval_data): """Computes the average loss on eval_data, which should be a Dataset.""" avg_loss = tfe.metrics.Mean("loss") for (labels, chars, sequence_length) in tfe.Iterator(eval_data): predictions = model((chars, sequence_length), training=False) avg_loss(loss(labels, predictions)) print("eval/loss: %.6f\n" % avg_loss.result()) with tf.contrib.summary.always_record_summaries(): tf.contrib.summary.scalar("loss", avg_loss.result()) def train_one_epoch(model, optimizer, train_data, log_interval=10): """Trains model on train_data using optimizer.""" tf.train.get_or_create_global_step() def model_loss(labels, chars, sequence_length): predictions = model((chars, sequence_length), training=True) loss_value = loss(labels, predictions) tf.contrib.summary.scalar("loss", loss_value) return loss_value for (batch, (labels, chars, sequence_length)) in enumerate( tfe.Iterator(train_data)): with tf.contrib.summary.record_summaries_every_n_global_steps(log_interval): batch_model_loss = functools.partial(model_loss, labels, chars, sequence_length) optimizer.minimize( batch_model_loss, global_step=tf.train.get_global_step()) if log_interval and batch % log_interval == 0: print("train/batch #%d\tloss: %.6f" % (batch, batch_model_loss())) SOURCE_TRAIN_URL = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/archive/extras/colorbot/data/train.csv" SOURCE_TEST_URL = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/archive/extras/colorbot/data/test.csv" def main(_): data_dir = os.path.join(FLAGS.dir, "data") train_data = load_dataset( data_dir=data_dir, url=SOURCE_TRAIN_URL, batch_size=FLAGS.batch_size) eval_data = load_dataset( data_dir=data_dir, url=SOURCE_TEST_URL, batch_size=FLAGS.batch_size) model = RNNColorbot( rnn_cell_sizes=FLAGS.rnn_cell_sizes, label_dimension=3, keep_prob=FLAGS.keep_probability) optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) if FLAGS.no_gpu or tfe.num_gpus() <= 0: print(tfe.num_gpus()) device = "/cpu:0" else: device = "/gpu:0" print("Using device %s." % device) log_dir = os.path.join(FLAGS.dir, "summaries") tf.gfile.MakeDirs(log_dir) train_summary_writer = tf.contrib.summary.create_file_writer( os.path.join(log_dir, "train"), flush_millis=10000) test_summary_writer = tf.contrib.summary.create_file_writer( os.path.join(log_dir, "eval"), flush_millis=10000, name="eval") with tf.device(device): for epoch in range(FLAGS.num_epochs): start = time.time() with train_summary_writer.as_default(): train_one_epoch(model, optimizer, train_data, FLAGS.log_interval) end = time.time() print("train/time for epoch #%d: %.2f" % (epoch, end - start)) with test_summary_writer.as_default(): test(model, eval_data) print("Colorbot is ready to generate colors!") while True: try: color_name = six.moves.input( "Give me a color name (or press enter to exit): ") except EOFError: return if not color_name: return _, chars, length = parse(color_name) with tf.device(device): (chars, length) = (tf.identity(chars), tf.identity(length)) chars = tf.expand_dims(chars, 0) length = tf.expand_dims(length, 0) preds = tf.unstack(model((chars, length), training=False)[0]) # Predictions cannot be negative, as they are generated by a ReLU layer; # they may, however, be greater than 1. clipped_preds = tuple(min(float(p), 1.0) for p in preds) rgb = tuple(int(p * 255) for p in clipped_preds) print("rgb:", rgb) data = [[clipped_preds]] if HAS_MATPLOTLIB: plt.imshow(data) plt.title(color_name) plt.show() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--dir", type=str, default="/tmp/rnn_colorbot/", help="Directory to download data files and save logs.") parser.add_argument( "--log_interval", type=int, default=10, metavar="N", help="Log training loss every log_interval batches.") parser.add_argument( "--num_epochs", type=int, default=20, help="Number of epochs to train.") parser.add_argument( "--rnn_cell_sizes", type=int, nargs="+", default=[256, 128], help="List of sizes for each layer of the RNN.") parser.add_argument( "--batch_size", type=int, default=64, help="Batch size for training and eval.") parser.add_argument( "--keep_probability", type=float, default=0.5, help="Keep probability for dropout between layers.") parser.add_argument( "--learning_rate", type=float, default=0.01, help="Learning rate to be used during training.") parser.add_argument( "--no_gpu", action="store_true", default=False, help="Disables GPU usage even if a GPU is available.") FLAGS, unparsed = parser.parse_known_args() tfe.run(main=main, argv=[sys.argv[0]] + unparsed)
[ "tensorflow.device", "matplotlib.pyplot.imshow", "tensorflow.gfile.Exists", "tensorflow.stack", "tensorflow.gfile.GFile", "tensorflow.contrib.eager.python.tfe.run", "tensorflow.gfile.MakeDirs", "tensorflow.contrib.summary.always_record_summaries", "tensorflow.train.AdamOptimizer", "tensorflow.string_split", "tensorflow.string_to_number", "tensorflow.data.TextLineDataset", "tensorflow.contrib.eager.python.tfe.num_gpus", "tensorflow.contrib.eager.python.tfe.Iterator", "tensorflow.decode_raw", "tensorflow.train.get_or_create_global_step", "tensorflow.train.get_global_step", "tensorflow.nn.dropout", "tensorflow.contrib.eager.python.tfe.metrics.Mean", "tensorflow.nn.rnn_cell.BasicLSTMCell", "tensorflow.gather_nd", "tensorflow.unstack", "tensorflow.shape", "matplotlib.pyplot.title", "tensorflow.contrib.summary.record_summaries_every_n_global_steps", "tensorflow.identity", "matplotlib.pyplot.show", "tensorflow.transpose", "tensorflow.gfile.Copy", "tensorflow.expand_dims", "tensorflow.contrib.summary.scalar", "tensorflow.squared_difference" ]
tensorflow/contrib/eager/python/examples/rnn_colorbot/rnn_colorbot.py
[(108, 'os.path.join', 'os.path.join', (['work_directory', 'filename'], {}), False, 'import os\n'), (215, 'tensorflow.contrib.eager.python.tfe.metrics.Mean', 'tfe.metrics.Mean', (['"""loss"""'], {}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (216, 'tensorflow.contrib.eager.python.tfe.Iterator', 'tfe.Iterator', (['eval_data'], {}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (227, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (251, 'os.path.join', 'os.path.join', (['FLAGS.dir', '"""data"""'], {}), False, 'import os\n'), (261, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'FLAGS.learning_rate'}), True, 'import tensorflow as tf\n'), (270, 'os.path.join', 'os.path.join', (['FLAGS.dir', '"""summaries"""'], {}), False, 'import os\n'), (271, 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['log_dir'], {}), True, 'import tensorflow as tf\n'), (318, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (360, 'tensorflow.contrib.eager.python.tfe.run', 'tfe.run', ([], {'main': 'main', 'argv': '([sys.argv[0]] + unparsed)'}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (85, 'tensorflow.string_split', 'tf.string_split', (['[line]', '""","""'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.string_to_number', 'tf.string_to_number', (['items[1:]'], {'out_type': 'tf.float32'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.decode_raw', 'tf.decode_raw', (['color_name', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['work_directory'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['work_directory'], {}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['filepath'], {}), True, 'import tensorflow as tf\n'), (110, 'urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['source_url'], {}), False, 'import urllib\n'), (111, 'tensorflow.gfile.Copy', 'tf.gfile.Copy', (['temp_file_name', 'filepath'], {}), True, 'import tensorflow as tf\n'), (123, 'os.path.basename', 'os.path.basename', (['url'], {}), False, 'import os\n'), (179, 'tensorflow.transpose', 'tf.transpose', (['chars', '[1, 0, 2]'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.stack', 'tf.stack', (['[sequence_length - 1, batch_range]'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.gather_nd', 'tf.gather_nd', (['chars', 'indices'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.squared_difference', 'tf.squared_difference', (['predictions', 'labels'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.contrib.summary.always_record_summaries', 'tf.contrib.summary.always_record_summaries', ([], {}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.contrib.summary.scalar', 'tf.contrib.summary.scalar', (['"""loss"""', 'loss_value'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.contrib.eager.python.tfe.Iterator', 'tfe.Iterator', (['train_data'], {}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (273, 'os.path.join', 'os.path.join', (['log_dir', '"""train"""'], {}), False, 'import os\n'), (275, 'os.path.join', 'os.path.join', (['log_dir', '"""eval"""'], {}), False, 'import os\n'), (277, 'tensorflow.device', 'tf.device', (['device'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.shape', 'tf.shape', (['chars'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['filepath'], {}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.unstack', 'tf.unstack', (['chars'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.stack', 'tf.stack', (['outputs'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.contrib.summary.record_summaries_every_n_global_steps', 'tf.contrib.summary.record_summaries_every_n_global_steps', (['log_interval'], {}), True, 'import tensorflow as tf\n'), (238, 'functools.partial', 'functools.partial', (['model_loss', 'labels', 'chars', 'sequence_length'], {}), False, 'import functools\n'), (263, 'tensorflow.contrib.eager.python.tfe.num_gpus', 'tfe.num_gpus', ([], {}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (264, 'tensorflow.contrib.eager.python.tfe.num_gpus', 'tfe.num_gpus', ([], {}), False, 'from tensorflow.contrib.eager.python import tfe\n'), (279, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (282, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (290, 'six.moves.input', 'six.moves.input', (['"""Give me a color name (or press enter to exit): """'], {}), False, 'import six\n'), (299, 'tensorflow.device', 'tf.device', (['device'], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.expand_dims', 'tf.expand_dims', (['chars', '(0)'], {}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.expand_dims', 'tf.expand_dims', (['length', '(0)'], {}), True, 'import tensorflow as tf\n'), (312, 'matplotlib.pyplot.imshow', 'plt.imshow', (['data'], {}), True, 'import matplotlib.pyplot as plt\n'), (313, 'matplotlib.pyplot.title', 'plt.title', (['color_name'], {}), True, 'import matplotlib.pyplot as plt\n'), (314, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (156, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['size'], {}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['chars', 'self.keep_prob'], {}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.identity', 'tf.identity', (['chars'], {}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.identity', 'tf.identity', (['length'], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.data.TextLineDataset', 'tf.data.TextLineDataset', (['path'], {}), True, 'import tensorflow as tf\n')]
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
# 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 l2hmc fit to 2D strongly correlated Gaussian executed eagerly.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy.random as npr import tensorflow as tf import tensorflow.contrib.eager as tfe from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc def get_default_hparams(): return tf.contrib.training.HParams( x_dim=2, n_samples=200, n_steps=10, eps=.1, n_iters=10, learning_rate=.0003, n_warmup_iters=3) def step(dynamics, optimizer, samples): loss, grads, samples, _ = l2hmc.loss_and_grads( dynamics, samples, loss_fn=l2hmc.compute_loss) optimizer.apply_gradients(zip(grads, dynamics.variables)) return loss, samples # To be defunnable, the function cannot return an Operation, so the above # function is used for defun or eager, and this function is used in graph to be # able to run the gradient updates. def graph_step(dynamics, optimizer, samples): loss, grads, samples, _ = l2hmc.loss_and_grads( dynamics, samples, loss_fn=l2hmc.compute_loss) train_op = optimizer.apply_gradients(zip(grads, dynamics.variables)) return train_op, loss, samples def warmup(dynamics, optimizer, n_iters=1, n_samples=200, step_fn=step): """Warmup optimization to reduce overhead.""" samples = tf.random_normal( shape=[n_samples, dynamics.x_dim], dtype=tf.float32) for _ in range(n_iters): _, samples = step_fn(dynamics, optimizer, samples) def fit(dynamics, samples, optimizer, step_fn=step, n_iters=5000, verbose=True, logdir=None): """Fit L2HMC sampler with given log-likelihood function.""" if logdir: summary_writer = tf.contrib.summary.create_file_writer(logdir) for i in range(n_iters): loss, samples = step_fn(dynamics, optimizer, samples) if verbose: print("Iteration %d: loss %.4f" % (i, loss)) if logdir: with summary_writer.as_default(): with tf.contrib.summary.always_record_summaries(): tf.contrib.summary.scalar("loss", loss) class L2hmcTest(tf.test.TestCase): """Unit tests for l2hmc in both eager and graph mode.""" def test_apply_transition(self): """Testing function `Dynamics.apply_transition` in graph and eager mode.""" # Eager mode testing hparams = get_default_hparams() energy_fn, _, _ = l2hmc.get_scg_energy_fn() dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim, minus_loglikelihood_fn=energy_fn, n_steps=hparams.n_steps, eps=hparams.eps) samples = tf.random_normal(shape=[hparams.n_samples, hparams.x_dim]) x_, v_, x_accept_prob, x_out = dynamics.apply_transition(samples) self.assertEqual(x_.shape, v_.shape) self.assertEqual(x_out.shape, samples.shape) self.assertEqual(x_.shape, x_out.shape) self.assertEqual(x_accept_prob.shape, (hparams.n_samples,)) # Graph mode testing with tf.Graph().as_default(): energy_fn, _, _ = l2hmc.get_scg_energy_fn() dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim, minus_loglikelihood_fn=energy_fn, n_steps=hparams.n_steps, eps=hparams.eps) x = tf.placeholder(tf.float32, shape=[None, hparams.x_dim]) x_, v_, x_accept_prob, x_out = dynamics.apply_transition(x) samples = npr.normal(size=[hparams.n_samples, hparams.x_dim]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) np_x_, np_v_, np_x_accept_prob, np_x_out = sess.run( [x_, v_, x_accept_prob, x_out], feed_dict={x: samples}) self.assertEqual(np_x_.shape, np_v_.shape) self.assertEqual(samples.shape, np_x_out.shape) self.assertEqual(np_x_.shape, np_x_out.shape) self.assertEqual(np_x_accept_prob.shape, (hparams.n_samples,)) class L2hmcBenchmark(tf.test.Benchmark): """Eager and graph benchmarks for l2hmc.""" def benchmark_graph(self): """Benchmark Graph performance.""" hparams = get_default_hparams() tf.enable_resource_variables() for sample_size in [10, 25, 50, 100, 200]: hparams.n_samples = sample_size tf.reset_default_graph() with tf.Graph().as_default(): energy_fn, _, _ = l2hmc.get_scg_energy_fn() x = tf.random_normal([hparams.n_samples, hparams.x_dim], dtype=tf.float32) dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim, minus_loglikelihood_fn=energy_fn, n_steps=hparams.n_steps, eps=hparams.eps) loss, _, _ = l2hmc.compute_loss(dynamics, x) optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate) train_op, loss, _ = graph_step(dynamics, optimizer, x) # Single thread; fairer comparison against eager session_conf = tf.ConfigProto(inter_op_parallelism_threads=1) with tf.Session(config=session_conf) as sess: sess.run(tf.global_variables_initializer()) # Warmup to reduce initialization effect when timing for _ in range(hparams.n_warmup_iters): _, _ = sess.run([train_op, loss]) # Training start_time = time.time() for i in range(hparams.n_iters): _, loss_np = sess.run([train_op, loss]) print("Iteration %d: loss %.4f" % (i, loss_np)) wall_time = (time.time() - start_time) / hparams.n_iters examples_per_sec = hparams.n_samples / wall_time self.report_benchmark( name="graph_train_%s_%d" % ("gpu" if tf.test.is_gpu_available() else "cpu", sample_size), iters=hparams.n_iters, extras={"examples_per_sec": examples_per_sec}, wall_time=wall_time) def benchmark_eager(self): self._benchmark_eager() def benchmark_eager_defun(self): self._benchmark_eager(defun=True) def _benchmark_eager(self, defun=False): """Benchmark Eager performance.""" hparams = get_default_hparams() for sample_size in [10, 25, 50, 100, 200]: hparams.n_samples = sample_size energy_fn, _, _ = l2hmc.get_scg_energy_fn() dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim, minus_loglikelihood_fn=energy_fn, n_steps=hparams.n_steps, eps=hparams.eps) optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate) step_fn = tfe.defun(step) if defun else step # Warmup to reduce initialization effect when timing warmup( dynamics, optimizer, n_iters=hparams.n_warmup_iters, n_samples=hparams.n_samples, step_fn=step_fn) # Training samples = tf.random_normal( shape=[hparams.n_samples, hparams.x_dim], dtype=tf.float32) start_time = time.time() fit(dynamics, samples, optimizer, step_fn=step_fn, n_iters=hparams.n_iters) wall_time = (time.time() - start_time) / hparams.n_iters examples_per_sec = hparams.n_samples / wall_time self.report_benchmark( name="eager_train_%s%s_%d" % ("gpu" if tf.test.is_gpu_available() else "cpu", "_defun" if defun else "", sample_size), iters=hparams.n_iters, extras={"examples_per_sec": examples_per_sec}, wall_time=wall_time) del dynamics if __name__ == "__main__": tf.enable_eager_execution() tf.test.main()
[ "tensorflow.enable_eager_execution", "tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.compute_loss", "tensorflow.contrib.summary.always_record_summaries", "tensorflow.train.AdamOptimizer", "tensorflow.Graph", "tensorflow.test.main", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.enable_resource_variables", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.loss_and_grads", "tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics", "tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn", "tensorflow.contrib.eager.defun", "tensorflow.contrib.training.HParams", "tensorflow.contrib.summary.create_file_writer", "numpy.random.normal", "tensorflow.contrib.summary.scalar", "tensorflow.test.is_gpu_available", "tensorflow.random_normal" ]
tensorflow/contrib/eager/python/examples/l2hmc/l2hmc_test.py
[(30, 'tensorflow.contrib.training.HParams', 'tf.contrib.training.HParams', ([], {'x_dim': '(2)', 'n_samples': '(200)', 'n_steps': '(10)', 'eps': '(0.1)', 'n_iters': '(10)', 'learning_rate': '(0.0003)', 'n_warmup_iters': '(3)'}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.loss_and_grads', 'l2hmc.loss_and_grads', (['dynamics', 'samples'], {'loss_fn': 'l2hmc.compute_loss'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (52, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.loss_and_grads', 'l2hmc.loss_and_grads', (['dynamics', 'samples'], {'loss_fn': 'l2hmc.compute_loss'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (66, 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[n_samples, dynamics.x_dim]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.contrib.summary.create_file_writer', 'tf.contrib.summary.create_file_writer', (['logdir'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn', 'l2hmc.get_scg_energy_fn', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (105, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics', 'l2hmc.Dynamics', ([], {'x_dim': 'hparams.x_dim', 'minus_loglikelihood_fn': 'energy_fn', 'n_steps': 'hparams.n_steps', 'eps': 'hparams.eps'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (110, 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[hparams.n_samples, hparams.x_dim]'}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.enable_resource_variables', 'tf.enable_resource_variables', ([], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn', 'l2hmc.get_scg_energy_fn', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (121, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics', 'l2hmc.Dynamics', ([], {'x_dim': 'hparams.x_dim', 'minus_loglikelihood_fn': 'energy_fn', 'n_steps': 'hparams.n_steps', 'eps': 'hparams.eps'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (126, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, hparams.x_dim]'}), True, 'import tensorflow as tf\n'), (128, 'numpy.random.normal', 'npr.normal', ([], {'size': '[hparams.n_samples, hparams.x_dim]'}), True, 'import numpy.random as npr\n'), (151, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn', 'l2hmc.get_scg_energy_fn', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (204, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics', 'l2hmc.Dynamics', ([], {'x_dim': 'hparams.x_dim', 'minus_loglikelihood_fn': 'energy_fn', 'n_steps': 'hparams.n_steps', 'eps': 'hparams.eps'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (209, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'hparams.learning_rate'}), True, 'import tensorflow as tf\n'), (221, 'tensorflow.random_normal', 'tf.random_normal', ([], {'shape': '[hparams.n_samples, hparams.x_dim]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (223, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (130, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.get_scg_energy_fn', 'l2hmc.get_scg_energy_fn', ([], {}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (154, 'tensorflow.random_normal', 'tf.random_normal', (['[hparams.n_samples, hparams.x_dim]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics', 'l2hmc.Dynamics', ([], {'x_dim': 'hparams.x_dim', 'minus_loglikelihood_fn': 'energy_fn', 'n_steps': 'hparams.n_steps', 'eps': 'hparams.eps'}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (161, 'tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.compute_loss', 'l2hmc.compute_loss', (['dynamics', 'x'], {}), False, 'from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc\n'), (163, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'hparams.learning_rate'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'inter_op_parallelism_threads': '(1)'}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.contrib.eager.defun', 'tfe.defun', (['step'], {}), True, 'import tensorflow.contrib.eager as tfe\n'), (92, 'tensorflow.contrib.summary.always_record_summaries', 'tf.contrib.summary.always_record_summaries', ([], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.summary.scalar', 'tf.contrib.summary.scalar', (['"""loss"""', 'loss'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), True, 'import tensorflow as tf\n'), (177, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (229, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (152, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (181, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (234, 'tensorflow.test.is_gpu_available', 'tf.test.is_gpu_available', ([], {}), True, 'import tensorflow as tf\n'), (186, 'tensorflow.test.is_gpu_available', 'tf.test.is_gpu_available', ([], {}), True, 'import tensorflow as tf\n')]
dpton/tensorflow-attention-rnn
a1b8884640ca49d6fdebc7df2167e4353364a243
# _*_ coding:utf-8 _*_ # !/usr/bin/env python from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import logging import nltk from nltk.corpus import stopwords from gensim.models.wrappers import FastText from gensim.models import Word2Vec import random import threading import tensorflow as tf import re import unicodedata from ftfy import fix_text from unidecode import unidecode from textacy.compat import unicode_ from textacy.constants import (CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES) UNK = u'_UNK' GO = u'_GO' EOS = u'_EOS' PAD = u'_PAD' PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 SPECIAL_WORDS = [PAD, GO, EOS, UNK] decode_max_length = 25 def fix_bad_unicode(text, normalization='NFC'): """ Fix unicode text that's "broken" using `ftfy <http://ftfy.readthedocs.org/>`_; this includes mojibake, HTML entities and other code cruft, and non-standard forms for display purposes. Args: text (str): raw text normalization ({'NFC', 'NFKC', 'NFD', 'NFKD'}): if 'NFC', combines characters and diacritics written using separate code points, e.g. converting "e" plus an acute accent modifier into "é"; unicode can be converted to NFC form without any change in its meaning! if 'NFKC', additional normalizations are applied that can change the meanings of characters, e.g. ellipsis characters will be replaced with three periods Returns: str """ return fix_text(text, normalization=normalization) def transliterate_unicode(text): """ Try to represent unicode data in ascii characters similar to what a human with a US keyboard would choose using unidecode <https://pypi.python.org/pypi/Unidecode> """ return unidecode(text) def normalize_whitespace(text): """ Given ``text`` str, replace one or more spacings with a single space, and one or more linebreaks with a single newline. Also strip leading/trailing whitespace. """ return NONBREAKING_SPACE_REGEX.sub(' ', LINEBREAK_REGEX.sub(r'\n', text)).strip() def unpack_contractions(text): """ Replace *English* contractions in ``text`` str with their unshortened forms. N.B. The "'d" and "'s" forms are ambiguous (had/would, is/has/possessive), so are left as-is. """ # standard text = re.sub( r"(\b)([Aa]re|[Cc]ould|[Dd]id|[Dd]oes|[Dd]o|[Hh]ad|[Hh]as|[Hh]ave|[Ii]s|[Mm]ight|[Mm]ust|[Ss]hould|[Ww]ere|[Ww]ould)n't", r"\1\2 not", text) text = re.sub( r"(\b)([Hh]e|[Ii]|[Ss]he|[Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Yy]ou)'ll", r"\1\2 will", text) text = re.sub( r"(\b)([Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Yy]ou)'re", r"\1\2 are", text) text = re.sub( r"(\b)([Ii]|[Ss]hould|[Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Ww]ould|[Yy]ou)'ve", r"\1\2 have", text) # non-standard text = re.sub(r"(\b)([Cc]a)n't", r"\1\2n not", text) text = re.sub(r"(\b)([Ii])'m", r"\1\2 am", text) text = re.sub(r"(\b)([Ll]et)'s", r"\1\2 us", text) text = re.sub(r"(\b)([Ww])on't", r"\1\2ill not", text) text = re.sub(r"(\b)([Ss])han't", r"\1\2hall not", text) text = re.sub(r"(\b)([Yy])(?:'all|a'll)", r"\1\2ou all", text) return text def replace_urls(text, replace_with='<url>'): """Replace all URLs in ``text`` str with ``replace_with`` str.""" return URL_REGEX.sub(replace_with, SHORT_URL_REGEX.sub(replace_with, text)) def replace_emails(text, replace_with='<email>'): """Replace all emails in ``text`` str with ``replace_with`` str.""" return EMAIL_REGEX.sub(replace_with, text) def replace_phone_numbers(text, replace_with='<phone>'): """Replace all phone numbers in ``text`` str with ``replace_with`` str.""" return PHONE_REGEX.sub(replace_with, text) def replace_numbers(text, replace_with='<number>'): """Replace all numbers in ``text`` str with ``replace_with`` str.""" return NUMBERS_REGEX.sub(replace_with, text) def replace_currency_symbols(text, replace_with='<currency>'): """ Replace all currency symbols in ``text`` str with string specified by ``replace_with`` str. Args: text (str): raw text replace_with (str): if None (default), replace symbols with their standard 3-letter abbreviations (e.g. '$' with 'USD', '£' with 'GBP'); otherwise, pass in a string with which to replace all symbols (e.g. "*CURRENCY*") Returns: str """ if replace_with is None: for k, v in CURRENCIES.items(): text = text.replace(k, v) return text else: return CURRENCY_REGEX.sub(replace_with, text) def remove_punct(text, marks=None): """ Remove punctuation from ``text`` by replacing all instances of ``marks`` with an empty string. Args: text (str): raw text marks (str): If specified, remove only the characters in this string, e.g. ``marks=',;:'`` removes commas, semi-colons, and colons. Otherwise, all punctuation marks are removed. Returns: str .. note:: When ``marks=None``, Python's built-in :meth:`str.translate()` is used to remove punctuation; otherwise,, a regular expression is used instead. The former's performance is about 5-10x faster. """ if marks: return re.sub('[{}]+'.format(re.escape(marks)), '', text, flags=re.UNICODE) else: if isinstance(text, unicode_): return text.translate(PUNCT_TRANSLATE_UNICODE) else: return text.translate(None, PUNCT_TRANSLATE_BYTES) def remove_accents(text, method='unicode'): """ Remove accents from any accented unicode characters in ``text`` str, either by transforming them into ascii equivalents or removing them entirely. Args: text (str): raw text method ({'unicode', 'ascii'}): if 'unicode', remove accented char for any unicode symbol with a direct ASCII equivalent; if 'ascii', remove accented char for any unicode symbol NB: the 'ascii' method is notably faster than 'unicode', but less good Returns: str Raises: ValueError: if ``method`` is not in {'unicode', 'ascii'} """ if method == 'unicode': return ''.join(c for c in unicodedata.normalize('NFKD', text) if not unicodedata.combining(c)) elif method == 'ascii': return unicodedata.normalize('NFKD', text).encode('ascii', errors='ignore').decode('ascii') else: msg = '`method` must be either "unicode" and "ascii", not {}'.format( method) raise ValueError(msg) def replace_hashtag(text, replace_with_hashtag='<hashtag>'): text = ' '.join( re.sub("(#[A-Za-z0-9]+)", replace_with_hashtag, text).split()) return text def replace_nametag(text, replace_with_nametag='<nametag>'): text = ' '.join( re.sub("(@[A-Za-z0-9]+)", replace_with_nametag, text).split()) return text def preprocess_text(text, fix_unicode=False, lowercase=False, transliterate=False, no_urls=False, no_emails=False, no_phone_numbers=False, no_numbers=False, no_currency_symbols=False, no_punct=False, no_contractions=False, no_accents=False, no_hashtag=False, no_nametag=False): """ This is a modified version of the function "textacy.preprocess_text". Normalize various aspects of a raw text doc before parsing it with Spacy. A convenience function for applying all other preprocessing functions in one go. Args: text (str): raw text to preprocess fix_unicode (bool): if True, fix "broken" unicode such as mojibake and garbled HTML entities lowercase (bool): if True, all text is lower-cased transliterate (bool): if True, convert non-ascii characters into their closest ascii equivalents no_urls (bool): if True, replace all URL strings with '*URL*' no_emails (bool): if True, replace all email strings with '*EMAIL*' no_phone_numbers (bool): if True, replace all phone number strings with '<phone>' no_numbers (bool): if True, replace all number-like strings with '<number>' no_currency_symbols (bool): if True, replace all currency symbols with their standard 3-letter abbreviations no_punct (bool): if True, remove all punctuation (replace with empty string) no_contractions (bool): if True, replace *English* contractions with their unshortened forms no_accents (bool): if True, replace all accented characters with unaccented versions; NB: if `transliterate` is True, this option is redundant not_hashtag (bool): if True, replace all hashtag (twitter, facebook) Returns: str: input ``text`` processed according to function args .. warning:: These changes may negatively affect subsequent NLP analysis performed on the text, so choose carefully, and preprocess at your own risk! """ if fix_unicode is True: text = fix_bad_unicode(text, normalization='NFC') if transliterate is True: text = transliterate_unicode(text) if no_urls is True: text = replace_urls(text) if no_emails is True: text = replace_emails(text) if no_phone_numbers is True: text = replace_phone_numbers(text) if no_numbers is True: text = replace_numbers(text) if no_currency_symbols is True: text = replace_currency_symbols(text) if no_contractions is True: text = unpack_contractions(text) if no_accents is True: text = remove_accents(text, method='unicode') if no_punct is True: text = remove_punct(text) if lowercase is True: text = text.lower() if no_hashtag is True: text = replace_hashtag(text) if no_nametag is True: text = replace_nametag(text) # always normalize whitespace; treat linebreaks separately from spacing text = normalize_whitespace(text) return text def text_normalize(string, convert2digit=True): text = preprocess_text(text=string, fix_unicode=False, lowercase=True, transliterate=False, no_urls=True, no_emails=True, no_phone_numbers=True, no_numbers=True, no_currency_symbols=True, no_punct=False, no_contractions=True, no_accents=True, not_hashtag=True) if convert2digit: return text2num(text) else: return text def remove_stopwords(word_list): filtered_words = [ word for word in word_list if word not in stopwords.words('english')] return filtered_words def tokenize(string): text = text_normalize(string) return nltk.word_tokenize(text, language='english') class wordEmbedding(object): ''' This class wraps the two popular models using for word embedding, FastText and Word2Vec ''' def __init__(self, model_path, model_type='fasttext', **kwarg): if model_type == "fasttext": self._model = FastText.load_fasttext_format(model_path) elif model_type == "word2vec": self._model = Word2Vec.load_word2vec_format(model_path) else: raise NotImplementedError("other model is not supported") def sentence_to_index(self, sentence): list_of_index = [self._model.wv.vocab[ word].index for word in tokenize(sentence)] return list_of_index def get_embedding_matrix(self): return self._model.syn0 def create_queue(sess = None, coord = None, encode_data = None, decode_data = None, capacity = 1024, batch_size = 32, scope = None): encode = tf.placeholder(tf.int32, shape=[None], name="encode") decode = tf.placeholder(tf.int32, shape=[decode_max_length + 2], name="decode") weight = tf.placeholder(tf.float32, shape=[decode_max_length + 1], name="weight") queue = tf.PaddingFIFOQueue(capacity = capacity, dtypes = [tf.int32, tf.int32, tf.float32], shapes = [[None], [decode_max_length + 2], [decode_max_length + 1]], name = 'FIFOQueue') enqueue_op = queue.enqueue([encode, decode, weight]) def _iterator(): assert len(encode_data) == len(decode_data) data = list(zip(encode_data, decode_data)) random.shuffle(data) encode, decode = [list(t) for t in zip(*data)] for i in range(len(data)): # if len(encode[i]) > encode_max_length - 1 or len(decode[i]) > decode_max_length - 1: # raise 'the sentence is longer than max_length' #_encode = encode[i][:encode_max_length] #_encode = _encode + [PAD_ID] * (encode_max_length - len(_encode)) _encode = encode[i] _decode = decode[i][:decode_max_length] _decode_padding_size = decode_max_length - len(_decode) _weight = [1.0] * (len(_decode) + 1) + [0.0] * _decode_padding_size _decode = [GO_ID] + _decode + [EOS_ID] + [PAD_ID] * _decode_padding_size yield _encode, _decode, _weight#, _encode_length, _decode_length def basic_enqueue(sess, encode_input, decode_input = None): # if len(encode_input) > encode_max_length: # encode_input = encode_input[:encode_max_length] # _encode = encode_input + [PAD_ID] * (encode_max_length - len(encode_input)) _encode = encode_input if decode_input is None: _decode = [GO_ID] + [PAD_ID] * (decode_max_length + 1) _weight = [1.0] * (decode_max_length + 1) else: _decode_padding_size = decode_max_length - len(decode_input) _decode = [GO_ID] + decode_input + [EOS_ID] + [PAD_ID] * _decode_padding_size _weight = [1.0] * (len(decode_input) + 1) + [0.0] * _decode_padding_size feed_dict = { encode: _encode, decode: _decode, weight: _weight } # Push all the training examples to the queue sess.run(enqueue_op, feed_dict=feed_dict) def _enqueue(sess, coord): try: while not coord.should_stop(): for _encode, _decode, _weight in _iterator(): feed_dict = { encode: _encode, decode: _decode, weight: _weight, } # Push all the training examples to the queue sess.run(enqueue_op, feed_dict=feed_dict) except tf.errors.CancelledError: coord.request_stop() #Start thread enqueue data # if encode_data is None or decode_data is None: # return queue, None, basic_enqueue enqueue_threads = [] ## enqueue asynchronously for i in range(num_threads): enqueue_thread = threading.Thread(target=_enqueue, args=(sess, coord)) enqueue_thread.setDaemon(True) enqueue_threads.append(enqueue_thread) return queue, enqueue_threads, basic_enqueue if __name__ == '__main__': print(tokenize("http://google.com.vn I love the cat @Peter with 69USD"))
[ "tensorflow.placeholder", "tensorflow.PaddingFIFOQueue" ]
utils/reprocessing.py
[(60, 'ftfy.fix_text', 'fix_text', (['text'], {'normalization': 'normalization'}), False, 'from ftfy import fix_text\n'), (68, 'unidecode.unidecode', 'unidecode', (['text'], {}), False, 'from unidecode import unidecode\n'), (86, 're.sub', 're.sub', (['"""(\\\\b)([Aa]re|[Cc]ould|[Dd]id|[Dd]oes|[Dd]o|[Hh]ad|[Hh]as|[Hh]ave|[Ii]s|[Mm]ight|[Mm]ust|[Ss]hould|[Ww]ere|[Ww]ould)n\'t"""', '"""\\\\1\\\\2 not"""', 'text'], {}), False, 'import re\n'), (88, 're.sub', 're.sub', (['"""(\\\\b)([Hh]e|[Ii]|[Ss]he|[Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Yy]ou)\'ll"""', '"""\\\\1\\\\2 will"""', 'text'], {}), False, 'import re\n'), (90, 're.sub', 're.sub', (['"""(\\\\b)([Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Yy]ou)\'re"""', '"""\\\\1\\\\2 are"""', 'text'], {}), False, 'import re\n'), (92, 're.sub', 're.sub', (['"""(\\\\b)([Ii]|[Ss]hould|[Tt]hey|[Ww]e|[Ww]hat|[Ww]ho|[Ww]ould|[Yy]ou)\'ve"""', '"""\\\\1\\\\2 have"""', 'text'], {}), False, 'import re\n'), (95, 're.sub', 're.sub', (['"""(\\\\b)([Cc]a)n\'t"""', '"""\\\\1\\\\2n not"""', 'text'], {}), False, 'import re\n'), (96, 're.sub', 're.sub', (['"""(\\\\b)([Ii])\'m"""', '"""\\\\1\\\\2 am"""', 'text'], {}), False, 'import re\n'), (97, 're.sub', 're.sub', (['"""(\\\\b)([Ll]et)\'s"""', '"""\\\\1\\\\2 us"""', 'text'], {}), False, 'import re\n'), (98, 're.sub', 're.sub', (['"""(\\\\b)([Ww])on\'t"""', '"""\\\\1\\\\2ill not"""', 'text'], {}), False, 'import re\n'), (99, 're.sub', 're.sub', (['"""(\\\\b)([Ss])han\'t"""', '"""\\\\1\\\\2hall not"""', 'text'], {}), False, 'import re\n'), (100, 're.sub', 're.sub', (['"""(\\\\b)([Yy])(?:\'all|a\'ll)"""', '"""\\\\1\\\\2ou all"""', 'text'], {}), False, 'import re\n'), (111, 'textacy.constants.EMAIL_REGEX.sub', 'EMAIL_REGEX.sub', (['replace_with', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (116, 'textacy.constants.PHONE_REGEX.sub', 'PHONE_REGEX.sub', (['replace_with', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (121, 'textacy.constants.NUMBERS_REGEX.sub', 'NUMBERS_REGEX.sub', (['replace_with', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (306, 'nltk.word_tokenize', 'nltk.word_tokenize', (['text'], {'language': '"""english"""'}), False, 'import nltk\n'), (333, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]', 'name': '"""encode"""'}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[decode_max_length + 2]', 'name': '"""decode"""'}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[decode_max_length + 1]', 'name': '"""weight"""'}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.PaddingFIFOQueue', 'tf.PaddingFIFOQueue', ([], {'capacity': 'capacity', 'dtypes': '[tf.int32, tf.int32, tf.float32]', 'shapes': '[[None], [decode_max_length + 2], [decode_max_length + 1]]', 'name': '"""FIFOQueue"""'}), True, 'import tensorflow as tf\n'), (106, 'textacy.constants.SHORT_URL_REGEX.sub', 'SHORT_URL_REGEX.sub', (['replace_with', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (139, 'textacy.constants.CURRENCIES.items', 'CURRENCIES.items', ([], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (143, 'textacy.constants.CURRENCY_REGEX.sub', 'CURRENCY_REGEX.sub', (['replace_with', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (346, 'random.shuffle', 'random.shuffle', (['data'], {}), False, 'import random\n'), (402, 'threading.Thread', 'threading.Thread', ([], {'target': '_enqueue', 'args': '(sess, coord)'}), False, 'import threading\n'), (316, 'gensim.models.wrappers.FastText.load_fasttext_format', 'FastText.load_fasttext_format', (['model_path'], {}), False, 'from gensim.models.wrappers import FastText\n'), (76, 'textacy.constants.LINEBREAK_REGEX.sub', 'LINEBREAK_REGEX.sub', (['"""\\\\n"""', 'text'], {}), False, 'from textacy.constants import CURRENCIES, URL_REGEX, SHORT_URL_REGEX, EMAIL_REGEX, PHONE_REGEX, NUMBERS_REGEX, CURRENCY_REGEX, LINEBREAK_REGEX, NONBREAKING_SPACE_REGEX, PUNCT_TRANSLATE_UNICODE, PUNCT_TRANSLATE_BYTES\n'), (165, 're.escape', 're.escape', (['marks'], {}), False, 'import re\n'), (205, 're.sub', 're.sub', (['"""(#[A-Za-z0-9]+)"""', 'replace_with_hashtag', 'text'], {}), False, 'import re\n'), (211, 're.sub', 're.sub', (['"""(@[A-Za-z0-9]+)"""', 'replace_with_nametag', 'text'], {}), False, 'import re\n'), (300, 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), False, 'from nltk.corpus import stopwords\n'), (318, 'gensim.models.Word2Vec.load_word2vec_format', 'Word2Vec.load_word2vec_format', (['model_path'], {}), False, 'from gensim.models import Word2Vec\n'), (193, 'unicodedata.normalize', 'unicodedata.normalize', (['"""NFKD"""', 'text'], {}), False, 'import unicodedata\n'), (194, 'unicodedata.combining', 'unicodedata.combining', (['c'], {}), False, 'import unicodedata\n'), (196, 'unicodedata.normalize', 'unicodedata.normalize', (['"""NFKD"""', 'text'], {}), False, 'import unicodedata\n')]
JiByungKyu/ludwig
3e2f276459f976054b5c2ab8c55be994170345da
# coding=utf-8 # Copyright (c) 2019 Uber Technologies, 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. # ============================================================================== import logging from abc import ABC, abstractmethod from typing import Dict import tensorflow as tf from ludwig.constants import * from ludwig.modules.fully_connected_modules import FCStack from ludwig.modules.reduction_modules import SequenceReducer from ludwig.utils.misc_utils import merge_dict, get_from_registry from ludwig.utils.tf_utils import sequence_length_3D logger = logging.getLogger(__name__) class BaseFeature(object): """Base class for all features. Note that this class is not-cooperative (does not forward kwargs), so when constructing feature class hierarchies, there should be only one parent class that derives from base feature. Other functionality should be put into mixin classes to avoid the diamond pattern. """ def __init__(self, feature, *args, **kwargs): super().__init__() if 'name' not in feature: raise ValueError('Missing feature name') self.feature_name = feature['name'] self.type = None def overwrite_defaults(self, feature): attributes = set(self.__dict__.keys()) attributes.update(self.__class__.__dict__.keys()) for k in feature.keys(): if k in attributes: if (isinstance(feature[k], dict) and hasattr(self, k) and isinstance(getattr(self, k), dict)): setattr(self, k, merge_dict(getattr(self, k), feature[k])) else: setattr(self, k, feature[k]) class InputFeature(BaseFeature, tf.keras.Model, ABC): """Parent class for all input features.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def create_input(self): return tf.keras.Input(shape=self.get_input_shape(), dtype=self.get_input_dtype(), name=self.name + '_input') @abstractmethod def get_input_dtype(self): """Returns the Tensor data type this input accepts.""" pass @abstractmethod def get_input_shape(self): """Returns a tuple representing the Tensor shape this input accepts.""" pass @staticmethod @abstractmethod def update_model_definition_with_metadata( input_feature, feature_metadata, *args, **kwargs ): pass @staticmethod @abstractmethod def populate_defaults(input_feature): pass @property @abstractmethod def encoder_registry(self): pass def initialize_encoder(self, encoder_parameters): return get_from_registry(self.encoder, self.encoder_registry)( **encoder_parameters ) class OutputFeature(BaseFeature, tf.keras.Model, ABC): """Parent class for all output features.""" train_loss_function = None eval_loss_function = None def __init__(self, feature, *args, **kwargs): super().__init__(*args, feature=feature, **kwargs) self.reduce_input = None self.reduce_dependencies = None self.dependencies = [] self.fc_layers = None self.num_fc_layers = 0 self.fc_size = 256 self.use_bias = True self.weights_initializer = 'glorot_uniform' self.bias_initializer = 'zeros' self.weights_regularizer = None self.bias_regularizer = None self.activity_regularizer = None # self.weights_constraint=None # self.bias_constraint=None self.norm = None self.norm_params = None self.activation = 'relu' self.dropout = 0 self.overwrite_defaults(feature) logger.debug(' output feature fully connected layers') logger.debug(' FCStack') self.fc_stack = FCStack( layers=self.fc_layers, num_layers=self.num_fc_layers, default_fc_size=self.fc_size, default_use_bias=self.use_bias, default_weights_initializer=self.weights_initializer, default_bias_initializer=self.bias_initializer, default_weights_regularizer=self.weights_regularizer, default_bias_regularizer=self.bias_regularizer, default_activity_regularizer=self.activity_regularizer, # default_weights_constraint=self.weights_constraint, # default_bias_constraint=self.bias_constraint, default_norm=self.norm, default_norm_params=self.norm_params, default_activation=self.activation, default_dropout=self.dropout, ) # set up two sequence reducers, one for inputs and other for dependencies self.reduce_sequence_input = SequenceReducer( reduce_mode=self.reduce_input ) if self.dependencies: self.dependency_reducers = {} for dependency in self.dependencies: self.dependency_reducers[dependency] = SequenceReducer( reduce_mode=self.reduce_dependencies ) def create_input(self): return tf.keras.Input(shape=self.get_output_shape(), dtype=self.get_output_dtype(), name=self.name + '_input') @abstractmethod def get_output_dtype(self): """Returns the Tensor data type feature outputs.""" pass @abstractmethod def get_output_shape(self): """Returns a tuple representing the Tensor shape this feature outputs.""" pass @property @abstractmethod def metric_functions(self) -> Dict: pass @property @abstractmethod def decoder_registry(self): pass def initialize_decoder(self, decoder_parameters): return get_from_registry(self.decoder, self.decoder_registry)( **decoder_parameters ) def train_loss(self, targets, predictions): return self.train_loss_function(targets, predictions) def eval_loss(self, targets, predictions): return self.eval_loss_function(targets, predictions) def update_metrics(self, targets, predictions): for metric, metric_fn in self.metric_functions.items(): if metric == LOSS or metric == HITS_AT_K: metric_fn.update_state(targets, predictions) else: metric_fn.update_state(targets, predictions[PREDICTIONS]) def get_metrics(self): metric_vals = {} for metric_name, metric_onj in self.metric_functions.items(): metric_vals[metric_name] = metric_onj.result().numpy() return metric_vals def reset_metrics(self): for of_name, metric_fn in self.metric_functions.items(): if metric_fn is not None: metric_fn.reset_states() def call( self, inputs, # ((hidden, other_output_hidden), target) training=None, mask=None ): # account for output feature target if isinstance(inputs, tuple): local_inputs, target = inputs else: local_inputs = inputs target = None combiner_outputs, other_output_hidden = local_inputs # extract the combined hidden layer combiner_output = combiner_outputs['combiner_output'] hidden = self.prepare_decoder_inputs( combiner_output, other_output_hidden, training=training, mask=mask ) # ================ Predictions ================ logits_input = { HIDDEN: hidden } if 'encoder_output_state' in combiner_outputs: logits_input['encoder_output_state'] = \ combiner_outputs['encoder_output_state'] logits = self.logits(logits_input, target=target, training=training) # most of the cases the output of self.logits is a tensor # in some cases like for sequence features, it can be tuple of # logits, predictions, scores # The first element will be the logits tensor if isinstance(logits, tuple): logits = logits[0] return logits, hidden @property @abstractmethod def default_validation_metric(self): pass @staticmethod @abstractmethod def update_model_definition_with_metadata( output_feature, feature_metadata, *args, **kwargs ): pass @staticmethod @abstractmethod def calculate_overall_stats( test_stats, output_feature, dataset, train_set_metadata ): pass @staticmethod @abstractmethod def postprocess_results( output_feature, result, metadata, experiment_dir_name, skip_save_unprocessed_output=False, ): pass @staticmethod @abstractmethod def populate_defaults(input_feature): pass def concat_dependencies(self, hidden, other_features_hidden): if len(self.dependencies) > 0: dependencies_hidden = [] for dependency in self.dependencies: # the dependent feature is ensured to be present in final_hidden # because we did the topological sort of the features before dependency_final_hidden = other_features_hidden[dependency] if len(hidden.shape) > 2: if len(dependency_final_hidden.shape) > 2: # matrix matrix -> concat assert hidden.shape[1] == \ dependency_final_hidden.shape[1] dependencies_hidden.append(dependency_final_hidden) else: # matrix vector -> tile concat sequence_max_length = hidden.shape[1] multipliers = tf.concat( [[1], [sequence_max_length], [1]], 0 ) tiled_representation = tf.tile( tf.expand_dims(dependency_final_hidden, 1), multipliers ) # todo future: maybe modify this with TF2 mask mechanics sequence_length = sequence_length_3D(hidden) mask = tf.sequence_mask( sequence_length, sequence_max_length ) tiled_representation = tf.multiply( tiled_representation, tf.cast(mask[:, :, tf.newaxis], dtype=tf.float32) ) dependencies_hidden.append(tiled_representation) else: if len(dependency_final_hidden.shape) > 2: # vector matrix -> reduce concat reducer = self.dependency_reducers[dependency] dependencies_hidden.append( reducer(dependency_final_hidden) ) else: # vector vector -> concat dependencies_hidden.append(dependency_final_hidden) try: hidden = tf.concat([hidden] + dependencies_hidden, -1) except: raise ValueError( 'Shape mismatch while concatenating dependent features of ' '{}: {}. Concatenating the feature activations tensor {} ' 'with activation tensors of dependencies: {}. The error is ' 'likely due to a mismatch of the second dimension (sequence' ' length) or a difference in ranks. Likely solutions are ' 'setting the maximum_sequence_length of all sequential ' 'features to be the same, or reduce the output of some ' 'features, or disabling the bucketing setting ' 'bucketing_field to None / null, as activating it will ' 'reduce the length of the field the bucketing is performed ' 'on.'.format( self.feature_name, self.dependencies, hidden, dependencies_hidden ) ) return hidden def output_specific_fully_connected( self, inputs, # feature_hidden training=None, mask=None ): feature_hidden = inputs original_feature_hidden = inputs # flatten inputs if len(original_feature_hidden.shape) > 2: feature_hidden = tf.reshape( feature_hidden, [-1, feature_hidden.shape[-1]] ) # pass it through fc_stack feature_hidden = self.fc_stack( feature_hidden, training=training, mask=mask ) feature_hidden_size = feature_hidden.shape[-1] # reshape back to original first and second dimension if len(original_feature_hidden.shape) > 2: sequence_length = original_feature_hidden.shape[1] feature_hidden = tf.reshape( feature_hidden, [-1, sequence_length, feature_hidden_size] ) return feature_hidden def prepare_decoder_inputs( self, combiner_output, other_output_features, training=None, mask=None ): """ Takes the combiner output and the outputs of other outputs features computed so far and performs: - reduction of combiner outputs (if needed) - concatenating the outputs of dependent features (if needed) - output_specific fully connected layers (if needed) :param combiner_output: output tensor of the combiner :param other_output_features: output tensors from other features :return: tensor """ feature_hidden = combiner_output # ================ Reduce Inputs ================ if self.reduce_input is not None and len(feature_hidden.shape) > 2: feature_hidden = self.reduce_sequence_input( feature_hidden ) # ================ Concat Dependencies ================ feature_hidden = self.concat_dependencies( feature_hidden, other_output_features ) # ================ Output-wise Fully Connected ================ feature_hidden = self.output_specific_fully_connected( feature_hidden, training=training, mask=mask ) return feature_hidden
[ "tensorflow.concat", "tensorflow.cast", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.sequence_mask" ]
ludwig/features/base_feature.py
[(28, 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), False, 'import logging\n'), (143, 'ludwig.modules.fully_connected_modules.FCStack', 'FCStack', ([], {'layers': 'self.fc_layers', 'num_layers': 'self.num_fc_layers', 'default_fc_size': 'self.fc_size', 'default_use_bias': 'self.use_bias', 'default_weights_initializer': 'self.weights_initializer', 'default_bias_initializer': 'self.bias_initializer', 'default_weights_regularizer': 'self.weights_regularizer', 'default_bias_regularizer': 'self.bias_regularizer', 'default_activity_regularizer': 'self.activity_regularizer', 'default_norm': 'self.norm', 'default_norm_params': 'self.norm_params', 'default_activation': 'self.activation', 'default_dropout': 'self.dropout'}), False, 'from ludwig.modules.fully_connected_modules import FCStack\n'), (162, 'ludwig.modules.reduction_modules.SequenceReducer', 'SequenceReducer', ([], {'reduce_mode': 'self.reduce_input'}), False, 'from ludwig.modules.reduction_modules import SequenceReducer\n'), (105, 'ludwig.utils.misc_utils.get_from_registry', 'get_from_registry', (['self.encoder', 'self.encoder_registry'], {}), False, 'from ludwig.utils.misc_utils import merge_dict, get_from_registry\n'), (198, 'ludwig.utils.misc_utils.get_from_registry', 'get_from_registry', (['self.decoder', 'self.decoder_registry'], {}), False, 'from ludwig.utils.misc_utils import merge_dict, get_from_registry\n'), (394, 'tensorflow.reshape', 'tf.reshape', (['feature_hidden', '[-1, feature_hidden.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (410, 'tensorflow.reshape', 'tf.reshape', (['feature_hidden', '[-1, sequence_length, feature_hidden_size]'], {}), True, 'import tensorflow as tf\n'), (168, 'ludwig.modules.reduction_modules.SequenceReducer', 'SequenceReducer', ([], {'reduce_mode': 'self.reduce_dependencies'}), False, 'from ludwig.modules.reduction_modules import SequenceReducer\n'), (360, 'tensorflow.concat', 'tf.concat', (['([hidden] + dependencies_hidden)', '(-1)'], {}), True, 'import tensorflow as tf\n'), (326, 'tensorflow.concat', 'tf.concat', (['[[1], [sequence_max_length], [1]]', '(0)'], {}), True, 'import tensorflow as tf\n'), (336, 'ludwig.utils.tf_utils.sequence_length_3D', 'sequence_length_3D', (['hidden'], {}), False, 'from ludwig.utils.tf_utils import sequence_length_3D\n'), (337, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['sequence_length', 'sequence_max_length'], {}), True, 'import tensorflow as tf\n'), (331, 'tensorflow.expand_dims', 'tf.expand_dims', (['dependency_final_hidden', '(1)'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.cast', 'tf.cast', (['mask[:, :, (tf.newaxis)]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n')]
Dzinushi/models_1_4
d7e72793a68c1667d403b1542c205d1cd9b1d17c
# 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. # ============================================================================== """Tests for graphs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import defaultdict import operator import os import random import shutil import string import tempfile # Dependency imports import tensorflow as tf import graphs from adversarial_text.data import data_utils flags = tf.app.flags FLAGS = flags.FLAGS data = data_utils flags.DEFINE_integer('task', 0, 'Task id; needed for SyncReplicas test') def _build_random_vocabulary(vocab_size=100): """Builds and returns a dict<term, id>.""" vocab = set() while len(vocab) < (vocab_size - 1): rand_word = ''.join( random.choice(string.ascii_lowercase) for _ in range(random.randint(1, 10))) vocab.add(rand_word) vocab_ids = dict([(word, i) for i, word in enumerate(vocab)]) vocab_ids[data.EOS_TOKEN] = vocab_size - 1 return vocab_ids def _build_random_sequence(vocab_ids): seq_len = random.randint(10, 200) ids = vocab_ids.values() seq = data.SequenceWrapper() for token_id in [random.choice(ids) for _ in range(seq_len)]: seq.add_timestep().set_token(token_id) return seq def _build_vocab_frequencies(seqs, vocab_ids): vocab_freqs = defaultdict(int) ids_to_words = dict([(i, word) for word, i in vocab_ids.iteritems()]) for seq in seqs: for timestep in seq: vocab_freqs[ids_to_words[timestep.token]] += 1 vocab_freqs[data.EOS_TOKEN] = 0 return vocab_freqs class GraphsTest(tf.test.TestCase): """Test graph construction methods.""" @classmethod def setUpClass(cls): # Make model small FLAGS.batch_size = 2 FLAGS.num_timesteps = 3 FLAGS.embedding_dims = 4 FLAGS.rnn_num_layers = 2 FLAGS.rnn_cell_size = 4 FLAGS.cl_num_layers = 2 FLAGS.cl_hidden_size = 4 FLAGS.vocab_size = 10 # Set input/output flags FLAGS.data_dir = tempfile.mkdtemp() # Build and write sequence files. vocab_ids = _build_random_vocabulary(FLAGS.vocab_size) seqs = [_build_random_sequence(vocab_ids) for _ in range(5)] seqs_label = [ data.build_labeled_sequence(seq, random.choice([True, False])) for seq in seqs ] seqs_lm = [data.build_lm_sequence(seq) for seq in seqs] seqs_ae = [data.build_seq_ae_sequence(seq) for seq in seqs] seqs_rev = [data.build_reverse_sequence(seq) for seq in seqs] seqs_bidir = [ data.build_bidirectional_seq(seq, rev) for seq, rev in zip(seqs, seqs_rev) ] seqs_bidir_label = [ data.build_labeled_sequence(bd_seq, random.choice([True, False])) for bd_seq in seqs_bidir ] filenames = [ data.TRAIN_CLASS, data.TRAIN_LM, data.TRAIN_SA, data.TEST_CLASS, data.TRAIN_REV_LM, data.TRAIN_BD_CLASS, data.TEST_BD_CLASS ] seq_lists = [ seqs_label, seqs_lm, seqs_ae, seqs_label, seqs_rev, seqs_bidir, seqs_bidir_label ] for fname, seq_list in zip(filenames, seq_lists): with tf.python_io.TFRecordWriter( os.path.join(FLAGS.data_dir, fname)) as writer: for seq in seq_list: writer.write(seq.seq.SerializeToString()) # Write vocab.txt and vocab_freq.txt vocab_freqs = _build_vocab_frequencies(seqs, vocab_ids) ordered_vocab_freqs = sorted( vocab_freqs.items(), key=operator.itemgetter(1), reverse=True) with open(os.path.join(FLAGS.data_dir, 'vocab.txt'), 'w') as vocab_f: with open(os.path.join(FLAGS.data_dir, 'vocab_freq.txt'), 'w') as freq_f: for word, freq in ordered_vocab_freqs: vocab_f.write('{}\n'.format(word)) freq_f.write('{}\n'.format(freq)) @classmethod def tearDownClass(cls): shutil.rmtree(FLAGS.data_dir) def setUp(self): # Reset FLAGS FLAGS.rnn_num_layers = 1 FLAGS.sync_replicas = False FLAGS.adv_training_method = None FLAGS.num_candidate_samples = -1 FLAGS.num_classes = 2 FLAGS.use_seq2seq_autoencoder = False # Reset Graph tf.reset_default_graph() def testClassifierGraph(self): FLAGS.rnn_num_layers = 2 model = graphs.VatxtModel() train_op, _, _ = model.classifier_training() # Pretrained vars: embedding + LSTM layers self.assertEqual( len(model.pretrained_variables), 1 + 2 * FLAGS.rnn_num_layers) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) tf.train.start_queue_runners(sess) sess.run(train_op) def testLanguageModelGraph(self): train_op, _, _ = graphs.VatxtModel().language_model_training() with self.test_session() as sess: sess.run(tf.global_variables_initializer()) tf.train.start_queue_runners(sess) sess.run(train_op) def testMulticlass(self): FLAGS.num_classes = 10 graphs.VatxtModel().classifier_graph() def testATMethods(self): at_methods = [None, 'rp', 'at', 'vat', 'atvat'] for method in at_methods: FLAGS.adv_training_method = method with tf.Graph().as_default(): graphs.VatxtModel().classifier_graph() # Ensure variables have been reused # Embedding + LSTM layers + hidden layers + logits layer expected_num_vars = 1 + 2 * FLAGS.rnn_num_layers + 2 * ( FLAGS.cl_num_layers) + 2 self.assertEqual(len(tf.trainable_variables()), expected_num_vars) def testSyncReplicas(self): FLAGS.sync_replicas = True graphs.VatxtModel().language_model_training() def testCandidateSampling(self): FLAGS.num_candidate_samples = 10 graphs.VatxtModel().language_model_training() def testSeqAE(self): FLAGS.use_seq2seq_autoencoder = True graphs.VatxtModel().language_model_training() def testBidirLM(self): graphs.VatxtBidirModel().language_model_graph() def testBidirClassifier(self): at_methods = [None, 'rp', 'at', 'vat', 'atvat'] for method in at_methods: FLAGS.adv_training_method = method with tf.Graph().as_default(): graphs.VatxtBidirModel().classifier_graph() # Ensure variables have been reused # Embedding + 2 LSTM layers + hidden layers + logits layer expected_num_vars = 1 + 2 * 2 * FLAGS.rnn_num_layers + 2 * ( FLAGS.cl_num_layers) + 2 self.assertEqual(len(tf.trainable_variables()), expected_num_vars) def testEvalGraph(self): _, _ = graphs.VatxtModel().eval_graph() def testBidirEvalGraph(self): _, _ = graphs.VatxtBidirModel().eval_graph() if __name__ == '__main__': tf.test.main()
[ "tensorflow.Graph", "tensorflow.train.start_queue_runners", "tensorflow.test.main", "tensorflow.global_variables_initializer", "tensorflow.reset_default_graph", "tensorflow.trainable_variables" ]
research/adversarial_text/graphs_test.py
[(57, 'random.randint', 'random.randint', (['(10)', '(200)'], {}), False, 'import random\n'), (66, 'collections.defaultdict', 'defaultdict', (['int'], {}), False, 'from collections import defaultdict\n'), (225, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (60, 'random.choice', 'random.choice', (['ids'], {}), False, 'import random\n'), (92, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (139, 'shutil.rmtree', 'shutil.rmtree', (['FLAGS.data_dir'], {}), False, 'import shutil\n'), (151, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (155, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (162, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', (['sess'], {}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', (['sess'], {}), True, 'import tensorflow as tf\n'), (47, 'random.choice', 'random.choice', (['string.ascii_lowercase'], {}), False, 'import random\n'), (98, 'random.choice', 'random.choice', (['[True, False]'], {}), False, 'import random\n'), (109, 'random.choice', 'random.choice', (['[True, False]'], {}), False, 'import random\n'), (130, 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), False, 'import operator\n'), (131, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', '"""vocab.txt"""'], {}), False, 'import os\n'), (161, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (166, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (168, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (174, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (191, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (195, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (199, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (202, 'graphs.VatxtBidirModel', 'graphs.VatxtBidirModel', ([], {}), False, 'import graphs\n'), (218, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (221, 'graphs.VatxtBidirModel', 'graphs.VatxtBidirModel', ([], {}), False, 'import graphs\n'), (123, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', 'fname'], {}), False, 'import os\n'), (132, 'os.path.join', 'os.path.join', (['FLAGS.data_dir', '"""vocab_freq.txt"""'], {}), False, 'import os\n'), (48, 'random.randint', 'random.randint', (['(1)', '(10)'], {}), False, 'import random\n'), (180, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (181, 'graphs.VatxtModel', 'graphs.VatxtModel', ([], {}), False, 'import graphs\n'), (187, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (209, 'graphs.VatxtBidirModel', 'graphs.VatxtBidirModel', ([], {}), False, 'import graphs\n'), (215, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n')]
PaullMP/TensorFlowT
b9b3b5b19971671fe24868273ca5274c1ec7169f
# 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. # ============================================================================== """Contains metric-computing operations on streamed tensors. Module documentation, including "@@" callouts, should be put in third_party/tensorflow/contrib/metrics/__init__.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.framework import deprecated from tensorflow.contrib.framework import deprecated_args from tensorflow.contrib.framework import tensor_util from tensorflow.contrib.framework.python.ops import variables as contrib_variables from tensorflow.contrib.metrics.python.ops import confusion_matrix_ops from tensorflow.contrib.metrics.python.ops import set_ops from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops 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 sparse_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables IGNORE_MASK_DATE = '2016-10-19' IGNORE_MASK_INSTRUCTIONS = ( '`ignore_mask` is being deprecated. Instead use `weights` with values 0.0 ' 'and 1.0 to mask values. For example, `weights=tf.logical_not(mask)`.') def _mask_weights(mask=None, weights=None): """Mask a given set of weights. Elements are included when the corresponding `mask` element is `False`, and excluded otherwise. Args: mask: An optional, `bool` `Tensor`. weights: An optional `Tensor` whose shape matches `mask` if `mask` is not `None`. Returns: Masked weights if `mask` and `weights` are not `None`, weights equivalent to `mask` if `weights` is `None`, and otherwise `weights`. Raises: ValueError: If `weights` and `mask` are not `None` and have mismatched shapes. """ if mask is not None: check_ops.assert_type(mask, dtypes.bool) if weights is None: weights = array_ops.ones_like(mask, dtype=dtypes.float32) weights = math_ops.cast(math_ops.logical_not(mask), weights.dtype) * weights return weights def _safe_div(numerator, denominator, name): """Divides two values, returning 0 if the denominator is <= 0. Args: numerator: A real `Tensor`. denominator: A real `Tensor`, with dtype matching `numerator`. name: Name for the returned op. Returns: 0 if `denominator` <= 0, else `numerator` / `denominator` """ return math_ops.select( math_ops.greater(denominator, 0), math_ops.truediv(numerator, denominator), 0, name=name) def _safe_scalar_div(numerator, denominator, name): """Divides two values, returning 0 if the denominator is 0. Args: numerator: A scalar `float64` `Tensor`. denominator: A scalar `float64` `Tensor`. name: Name for the returned op. Returns: 0 if `denominator` == 0, else `numerator` / `denominator` """ numerator.get_shape().with_rank_at_most(1) denominator.get_shape().with_rank_at_most(1) return control_flow_ops.cond( math_ops.equal( array_ops.constant(0.0, dtype=dtypes.float64), denominator), lambda: array_ops.constant(0.0, dtype=dtypes.float64), lambda: math_ops.div(numerator, denominator), name=name) def _create_local(name, shape, collections=None, validate_shape=True, dtype=dtypes.float32): """Creates a new local variable. Args: name: The name of the new or existing variable. shape: Shape of the new or existing variable. collections: A list of collection names to which the Variable will be added. validate_shape: Whether to validate the shape of the variable. dtype: Data type of the variables. Returns: The created variable. """ # Make sure local variables are added to tf.GraphKeys.LOCAL_VARIABLES collections = list(collections or []) collections += [ops.GraphKeys.LOCAL_VARIABLES] return variables.Variable( initial_value=array_ops.zeros(shape, dtype=dtype), name=name, trainable=False, collections=collections, validate_shape=validate_shape) def _count_condition(values, weights=None, metrics_collections=None, updates_collections=None): """Sums the weights of cases where the given values are True. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: values: A `bool` `Tensor` of arbitrary size. weights: An optional `Tensor` whose shape is broadcastable to `values`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. Returns: value_tensor: A tensor representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ check_ops.assert_type(values, dtypes.bool) count = _create_local('count', shape=[]) values = math_ops.to_float(values) if weights is not None: weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) value_tensor = array_ops.identity(count) update_op = state_ops.assign_add(count, math_ops.reduce_sum(values)) if metrics_collections: ops.add_to_collections(metrics_collections, value_tensor) if updates_collections: ops.add_to_collections(updates_collections, update_op) return value_tensor, update_op def _streaming_true_positives(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Sum the weights of true_positives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `bool` `Tensor` of arbitrary dimensions. labels: The ground truth values, a `bool` `Tensor` whose dimensions must match `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A tensor representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'true_positives', [predictions, labels]): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) is_true_positive = math_ops.logical_and(math_ops.equal(labels, 1), math_ops.equal(predictions, 1)) return _count_condition(is_true_positive, weights, metrics_collections, updates_collections) def _streaming_false_positives(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Sum the weights of false positives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `bool` `Tensor` of arbitrary dimensions. labels: The ground truth values, a `bool` `Tensor` whose dimensions must match `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A tensor representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'false_positives', [predictions, labels]): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) is_false_positive = math_ops.logical_and(math_ops.equal(labels, 0), math_ops.equal(predictions, 1)) return _count_condition(is_false_positive, weights, metrics_collections, updates_collections) def _streaming_false_negatives(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the total number of false positives. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `bool` `Tensor` of arbitrary dimensions. labels: The ground truth values, a `bool` `Tensor` whose dimensions must match `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: value_tensor: A tensor representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'false_negatives', [predictions, labels]): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) is_false_negative = math_ops.logical_and(math_ops.equal(labels, 1), math_ops.equal(predictions, 0)) return _count_condition(is_false_negative, weights, metrics_collections, updates_collections) def _broadcast_weights(weights, values): """Broadcast `weights` to the same shape as `values`. This returns a version of `weights` following the same broadcast rules as `mul(weights, values)`. When computing a weighted average, use this function to broadcast `weights` before summing them; e.g., `reduce_sum(w * v) / reduce_sum(_broadcast_weights(w, v))`. Args: weights: `Tensor` whose shape is broadcastable to `values`. values: `Tensor` of any shape. Returns: `weights` broadcast to `values` shape. """ weights_shape = weights.get_shape() values_shape = values.get_shape() if (weights_shape.is_fully_defined() and values_shape.is_fully_defined() and weights_shape.is_compatible_with(values_shape)): return weights return math_ops.mul( weights, array_ops.ones_like(values), name='broadcast_weights') def streaming_mean(values, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the (weighted) mean of the given values. The `streaming_mean` function creates two local variables, `total` and `count` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean`. `update_op` increments `total` with the reduced sum of the product of `values` and `weights`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: values: A `Tensor` of arbitrary dimensions. weights: An optional `Tensor` whose shape is broadcastable to `values`. metrics_collections: An optional list of collections that `mean` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean', [values, weights]): values = math_ops.to_float(values) total = _create_local('total', shape=[]) count = _create_local('count', shape=[]) if weights is not None: weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) num_values = math_ops.reduce_sum(_broadcast_weights(weights, values)) else: num_values = math_ops.to_float(array_ops.size(values)) total_compute_op = state_ops.assign_add(total, math_ops.reduce_sum(values)) count_compute_op = state_ops.assign_add(count, num_values) mean = _safe_div(total, count, 'value') with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = _safe_div(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean, update_op def streaming_mean_tensor(values, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the element-wise (weighted) mean of the given tensors. In contrast to the `streaming_mean` function which returns a scalar with the mean, this function returns an average tensor with the same shape as the input tensors. The `streaming_mean_tensor` function creates two local variables, `total_tensor` and `count_tensor` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean`. `update_op` increments `total` with the reduced sum of the product of `values` and `weights`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: values: A `Tensor` of arbitrary dimensions. weights: An optional `Tensor` whose shape is broadcastable to `values`. metrics_collections: An optional list of collections that `mean` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean: A float tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean', [values, weights]): total = _create_local('total_tensor', shape=values.get_shape()) count = _create_local('count_tensor', shape=values.get_shape()) num_values = array_ops.ones_like(values) if weights is not None: weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) num_values = math_ops.mul(num_values, weights) total_compute_op = state_ops.assign_add(total, values) count_compute_op = state_ops.assign_add(count, num_values) def compute_mean(total, count, name): non_zero_count = math_ops.maximum(count, array_ops.ones_like(count), name=name) return math_ops.truediv(total, non_zero_count, name=name) mean = compute_mean(total, count, 'value') with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = compute_mean(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean, update_op def streaming_accuracy(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Calculates how often `predictions` matches `labels`. The `streaming_accuracy` function creates two local variables, `total` and `count` that are used to compute the frequency with which `predictions` matches `labels`. This frequency is ultimately returned as `accuracy`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `accuracy`. Internally, an `is_correct` operation computes a `Tensor` with elements 1.0 where the corresponding elements of `predictions` and `labels` match and 0.0 otherwise. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `is_correct`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: The predicted values, a `Tensor` of any shape. labels: The ground truth values, a `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `accuracy` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: accuracy: A tensor representing the accuracy, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `accuracy`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) if labels.dtype != predictions.dtype: predictions = math_ops.cast(predictions, labels.dtype) is_correct = math_ops.to_float(math_ops.equal(predictions, labels)) return streaming_mean(is_correct, weights, metrics_collections, updates_collections, name or 'accuracy') @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_precision(predictions, labels, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the precision of the predictions with respect to the labels. The `streaming_precision` function creates two local variables, `true_positives` and `false_positives`, that are used to compute the precision. This value is ultimately returned as `precision`, an idempotent operation that simply divides `true_positives` by the sum of `true_positives` and `false_positives`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision`. `update_op` weights each prediction by the corresponding value in `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: The predicted values, a `bool` `Tensor` of arbitrary shape. labels: The ground truth values, a `bool` `Tensor` whose dimensions must match `predictions`. ignore_mask: An optional, `bool` `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `precision` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: precision: Scalar float `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately and whose value matches `precision`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'precision', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) weights = _mask_weights(ignore_mask, weights) true_positives, true_positives_update_op = _streaming_true_positives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None) false_positives, false_positives_update_op = _streaming_false_positives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None) def compute_precision(name): return math_ops.select( math_ops.greater(true_positives + false_positives, 0), math_ops.div(true_positives, true_positives + false_positives), 0, name) precision = compute_precision('value') with ops.control_dependencies([true_positives_update_op, false_positives_update_op]): update_op = compute_precision('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, precision) if updates_collections: ops.add_to_collections(updates_collections, update_op) return precision, update_op @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_recall(predictions, labels, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the recall of the predictions with respect to the labels. The `streaming_recall` function creates two local variables, `true_positives` and `false_negatives`, that are used to compute the recall. This value is ultimately returned as `recall`, an idempotent operation that simply divides `true_positives` by the sum of `true_positives` and `false_negatives`. For estimation of the metric over a stream of data, the function creates an `update_op` that updates these variables and returns the `recall`. `update_op` weights each prediction by the corresponding value in `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: The predicted values, a `bool` `Tensor` of arbitrary shape. labels: The ground truth values, a `bool` `Tensor` whose dimensions must match `predictions`. ignore_mask: An optional, `bool` `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `recall` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: recall: Scalar float `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_negatives`. update_op: `Operation` that increments `true_positives` and `false_negatives` variables appropriately and whose value matches `recall`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'recall', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) weights = _mask_weights(ignore_mask, weights) true_positives, true_positives_update_op = _streaming_true_positives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None) false_negatives, false_negatives_update_op = _streaming_false_negatives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None) def compute_recall(true_positives, false_negatives, name): return math_ops.select( math_ops.greater(true_positives + false_negatives, 0), math_ops.div(true_positives, true_positives + false_negatives), 0, name) recall = compute_recall(true_positives, false_negatives, 'value') with ops.control_dependencies([true_positives_update_op, false_negatives_update_op]): update_op = compute_recall(true_positives, false_negatives, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, recall) if updates_collections: ops.add_to_collections(updates_collections, update_op) return recall, update_op def _tp_fn_tn_fp(predictions, labels, thresholds, weights=None): """Computes true_positives, false_negatives, true_negatives, false_positives. The `_tp_fn_tn_fp` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives`. `true_positive[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`. `false_negatives[i]` is defined as the total weight of values in `predictions` at most `thresholds[i]` whose corresponding entry in `labels` is `True`. `true_negatives[i]` is defined as the total weight of values in `predictions` at most `thresholds[i]` whose corresponding entry in `labels` is `False`. `false_positives[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `False`. For estimation of these metrics over a stream of data, for each metric the function respectively creates an `update_op` operation that updates the variable and returns its value. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `Tensor` whose shape matches `predictions`. `labels` will be cast to `bool`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. Returns: true_positive: A variable of shape [len(thresholds)]. false_negative: A variable of shape [len(thresholds)]. true_negatives: A variable of shape [len(thresholds)]. false_positives: A variable of shape [len(thresholds)]. true_positives_update_op: An operation that increments the `true_positives`. false_negative_update_op: An operation that increments the `false_negative`. true_negatives_update_op: An operation that increments the `true_negatives`. false_positives_update_op: An operation that increments the `false_positives`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) num_thresholds = len(thresholds) # Reshape predictions and labels. predictions_2d = array_ops.reshape(predictions, [-1, 1]) labels_2d = array_ops.reshape( math_ops.cast(labels, dtype=dtypes.bool), [1, -1]) # Use static shape if known. num_predictions = predictions_2d.get_shape().as_list()[0] # Otherwise use dynamic shape. if num_predictions is None: num_predictions = array_ops.shape(predictions_2d)[0] thresh_tiled = array_ops.tile( array_ops.expand_dims(array_ops.constant(thresholds), [1]), array_ops.pack([1, num_predictions])) # Tile the predictions after thresholding them across different thresholds. pred_is_pos = math_ops.greater( array_ops.tile(array_ops.transpose(predictions_2d), [num_thresholds, 1]), thresh_tiled) pred_is_neg = math_ops.logical_not(pred_is_pos) # Tile labels by number of thresholds label_is_pos = array_ops.tile(labels_2d, [num_thresholds, 1]) label_is_neg = math_ops.logical_not(label_is_pos) true_positives = _create_local('true_positives', shape=[num_thresholds]) false_negatives = _create_local('false_negatives', shape=[num_thresholds]) true_negatives = _create_local('true_negatives', shape=[num_thresholds]) false_positives = _create_local('false_positives', shape=[num_thresholds]) is_true_positive = math_ops.to_float( math_ops.logical_and(label_is_pos, pred_is_pos)) is_false_negative = math_ops.to_float( math_ops.logical_and(label_is_pos, pred_is_neg)) is_false_positive = math_ops.to_float( math_ops.logical_and(label_is_neg, pred_is_pos)) is_true_negative = math_ops.to_float( math_ops.logical_and(label_is_neg, pred_is_neg)) if weights is not None: weights = math_ops.to_float(weights) weights_tiled = array_ops.tile(array_ops.reshape( _broadcast_weights(weights, predictions), [1, -1]), [num_thresholds, 1]) thresh_tiled.get_shape().assert_is_compatible_with( weights_tiled.get_shape()) is_true_positive *= weights_tiled is_false_negative *= weights_tiled is_false_positive *= weights_tiled is_true_negative *= weights_tiled true_positives_update_op = state_ops.assign_add( true_positives, math_ops.reduce_sum(is_true_positive, 1)) false_negatives_update_op = state_ops.assign_add( false_negatives, math_ops.reduce_sum(is_false_negative, 1)) true_negatives_update_op = state_ops.assign_add( true_negatives, math_ops.reduce_sum(is_true_negative, 1)) false_positives_update_op = state_ops.assign_add( false_positives, math_ops.reduce_sum(is_false_positive, 1)) return (true_positives, false_negatives, true_negatives, false_positives, true_positives_update_op, false_negatives_update_op, true_negatives_update_op, false_positives_update_op) def streaming_auc(predictions, labels, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, curve='ROC', name=None): """Computes the approximate AUC via a Riemann sum. The `streaming_auc` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall. This value is ultimately returned as `auc`, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The `num_thresholds` variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `auc`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. num_thresholds: The number of thresholds to use when discretizing the roc curve. metrics_collections: An optional list of collections that `auc` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. curve: Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. name: An optional variable_scope name. Returns: auc: A scalar tensor representing the current area-under-curve. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `auc`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'auc', [predictions, labels]): if curve != 'ROC' and curve != 'PR': raise ValueError('curve must be either ROC or PR, %s unknown' % (curve)) kepsilon = 1e-7 # to account for floating point imprecisions thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds-2)] thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] (tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op, fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights) # Add epsilons to avoid dividing by 0. epsilon = 1.0e-6 assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds def compute_auc(tp, fn, tn, fp, name): """Computes the roc-auc or pr-auc based on confusion counts.""" recall = math_ops.div(tp + epsilon, tp + fn + epsilon) if curve == 'ROC': fp_rate = math_ops.div(fp, fp + tn + epsilon) x = fp_rate y = recall else: # curve == 'PR'. precision = math_ops.div(tp + epsilon, tp + fp + epsilon) x = recall y = precision return math_ops.reduce_sum(math_ops.mul( x[:num_thresholds - 1] - x[1:], (y[:num_thresholds - 1] + y[1:]) / 2.), name=name) # sum up the areas of all the trapeziums auc = compute_auc(tp, fn, tn, fp, 'value') update_op = compute_auc( tp_update_op, fn_update_op, tn_update_op, fp_update_op, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, auc) if updates_collections: ops.add_to_collections(updates_collections, update_op) return auc, update_op def streaming_specificity_at_sensitivity( predictions, labels, sensitivity, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None): """Computes the the specificity at a given sensitivity. The `streaming_specificity_at_sensitivity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the specificity at the given sensitivity value. The threshold for the given sensitivity value is computed and used to evaluate the corresponding specificity. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `specificity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about specificity and sensitivity, see the following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. sensitivity: A scalar value in range `[0, 1]`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. num_thresholds: The number of thresholds to use for matching the given sensitivity. metrics_collections: An optional list of collections that `specificity` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: specificity: A scalar tensor representing the specificity at the given `specificity` value. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `specificity`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `sensitivity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ if sensitivity < 0 or sensitivity > 1: raise ValueError('`sensitivity` must be in the range [0, 1].') with variable_scope.variable_scope(name, 'specificity_at_sensitivity', [predictions, labels]): kepsilon = 1e-7 # to account for floating point imprecisions thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds-2)] thresholds = [0.0 - kepsilon] + thresholds + [1.0 - kepsilon] (tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op, fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights) assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds def compute_specificity_at_sensitivity(name): """Computes the specificity at the given sensitivity. Args: name: The name of the operation. Returns: The specificity using the aggregated values. """ sensitivities = math_ops.div(tp, tp + fn + kepsilon) # We'll need to use this trick until tf.argmax allows us to specify # whether we should use the first or last index in case of ties. min_val = math_ops.reduce_min(math_ops.abs(sensitivities - sensitivity)) indices_at_minval = math_ops.equal( math_ops.abs(sensitivities - sensitivity), min_val) indices_at_minval = math_ops.to_int64(indices_at_minval) indices_at_minval = math_ops.cumsum(indices_at_minval) tf_index = math_ops.argmax(indices_at_minval, 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the specificity: return math_ops.div(tn[tf_index], tn[tf_index] + fp[tf_index] + kepsilon, name) specificity = compute_specificity_at_sensitivity('value') with ops.control_dependencies( [tp_update_op, fn_update_op, tn_update_op, fp_update_op]): update_op = compute_specificity_at_sensitivity('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, specificity) if updates_collections: ops.add_to_collections(updates_collections, update_op) return specificity, update_op def streaming_sensitivity_at_specificity( predictions, labels, specificity, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None): """Computes the the specificity at a given sensitivity. The `streaming_sensitivity_at_specificity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the sensitivity at the given specificity value. The threshold for the given specificity value is computed and used to evaluate the corresponding sensitivity. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `sensitivity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about specificity and sensitivity, see the following: https://en.wikipedia.org/wiki/Sensitivity_and_specificity Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. specificity: A scalar value in range `[0, 1]`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. num_thresholds: The number of thresholds to use for matching the given specificity. metrics_collections: An optional list of collections that `sensitivity` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: sensitivity: A scalar tensor representing the sensitivity at the given `specificity` value. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `sensitivity`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `specificity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ if specificity < 0 or specificity > 1: raise ValueError('`specificity` must be in the range [0, 1].') with variable_scope.variable_scope(name, 'sensitivity_at_specificity', [predictions, labels]): kepsilon = 1e-7 # to account for floating point imprecisions thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds-2)] thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] (tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op, fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights) assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds def compute_sensitivity_at_specificity(name): specificities = math_ops.div(tn, tn + fp + kepsilon) tf_index = math_ops.argmin(math_ops.abs(specificities - specificity), 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the sensitivity: return math_ops.div(tp[tf_index], tp[tf_index] + fn[tf_index] + kepsilon, name) sensitivity = compute_sensitivity_at_specificity('value') with ops.control_dependencies( [tp_update_op, fn_update_op, tn_update_op, fp_update_op]): update_op = compute_sensitivity_at_specificity('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, sensitivity) if updates_collections: ops.add_to_collections(updates_collections, update_op) return sensitivity, update_op def streaming_precision_at_thresholds(predictions, labels, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes precision values for different `thresholds` on `predictions`. The `streaming_precision_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `precision[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of values in `predictions` above `thresholds[i]` (`true_positives[i] / (true_positives[i] + false_positives[i])`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `auc` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: precision: A float tensor of shape [len(thresholds)]. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `precision`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'precision_at_thresholds', [predictions, labels]): # TODO(nsilberman): Replace with only tp and fp, this results in unnecessary # variable creation. b/30842882 (true_positives, _, _, false_positives, true_positives_compute_op, _, _, false_positives_compute_op,) = _tp_fn_tn_fp( predictions, labels, thresholds, weights) # avoid division by zero epsilon = 1e-7 def compute_precision(name): precision = math_ops.div(true_positives, epsilon + true_positives + false_positives, name='precision_' + name) return precision precision = compute_precision('value') with ops.control_dependencies([true_positives_compute_op, false_positives_compute_op]): update_op = compute_precision('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, precision) if updates_collections: ops.add_to_collections(updates_collections, update_op) return precision, update_op def streaming_recall_at_thresholds(predictions, labels, thresholds, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes various recall values for different `thresholds` on `predictions`. The `streaming_recall_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `recall[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of `True` values in `labels` (`true_positives[i] / (true_positives[i] + false_negatives[i])`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. labels: A `bool` `Tensor` whose shape matches `predictions`. thresholds: A python list or tuple of float thresholds in `[0, 1]`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `recall` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: recall: A float tensor of shape [len(thresholds)]. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `recall`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'recall_at_thresholds', [predictions, labels]): (true_positives, false_negatives, _, _, true_positives_compute_op, false_negatives_compute_op, _, _,) = _tp_fn_tn_fp( predictions, labels, thresholds, weights) # avoid division by zero epsilon = 1e-7 def compute_recall(name): recall = math_ops.div(true_positives, epsilon + true_positives + false_negatives, name='recall_' + name) return recall recall = compute_recall('value') with ops.control_dependencies([true_positives_compute_op, false_negatives_compute_op]): update_op = compute_recall('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, recall) if updates_collections: ops.add_to_collections(updates_collections, update_op) return recall, update_op def _at_k_name(name, k=None, class_id=None): if k is not None: name = '%s_at_%d' % (name, k) else: name = '%s_at_k' % (name) if class_id is not None: name = '%s_class%d' % (name, class_id) return name @deprecated('2016-11-08', 'Please use `streaming_sparse_recall_at_k`, ' 'and reshape labels from [batch_size] to [batch_size, 1].') @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_recall_at_k(predictions, labels, k, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the recall@k of the predictions with respect to dense labels. The `streaming_recall_at_k` function creates two local variables, `total` and `count`, that are used to compute the recall@k frequency. This frequency is ultimately returned as `recall_at_<k>`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall_at_<k>`. Internally, an `in_top_k` operation computes a `Tensor` with shape [batch_size] whose elements indicate whether or not the corresponding label is in the top `k` `predictions`. Then `update_op` increments `total` with the reduced sum of `weights` where `in_top_k` is `True`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: A floating point tensor of dimension [batch_size, num_classes] labels: A tensor of dimension [batch_size] whose type is in `int32`, `int64`. k: The number of top elements to look at for computing recall. ignore_mask: An optional, `bool` `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `recall_at_k` should be added to. updates_collections: An optional list of collections `update_op` should be added to. name: An optional variable_scope name. Returns: recall_at_k: A tensor representing the recall@k, the fraction of labels which fall into the top `k` predictions. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `recall_at_k`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ in_top_k = math_ops.to_float(nn.in_top_k(predictions, labels, k)) return streaming_mean(in_top_k, _mask_weights(ignore_mask, weights), metrics_collections, updates_collections, name or _at_k_name('recall', k)) # TODO(ptucker): Validate range of values in labels? @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_sparse_recall_at_k(predictions, labels, k, class_id=None, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes recall@k of the predictions with respect to sparse labels. If `class_id` is specified, we calculate recall by considering only the entries in the batch for which `class_id` is in the label, and computing the fraction of them for which `class_id` is in the top-k `predictions`. If `class_id` is not specified, we'll calculate recall as how often on average a class among the labels of a batch entry is in the top-k `predictions`. `streaming_sparse_recall_at_k` creates two local variables, `true_positive_at_<k>` and `false_negative_at_<k>`, that are used to compute the recall_at_k frequency. This frequency is ultimately returned as `recall_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_negative_at_<k>`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false negatives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_negative_at_<k>` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range always count towards `false_negative_at_<k>`. k: Integer, k for @k metric. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. If class_id is outside this range, the method returns NAN. ignore_mask: An optional, `bool` `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. weights: An optional `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: recall: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_negatives`. update_op: `Operation` that increments `true_positives` and `false_negatives` variables appropriately, and whose value matches `recall`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ default_name = _at_k_name('recall', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions, labels)) as scope: _, top_k_idx = nn.top_k(predictions, k) top_k_idx = math_ops.to_int64(top_k_idx) weights = _mask_weights(ignore_mask, weights) tp, tp_update = _streaming_sparse_true_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) fn, fn_update = _streaming_sparse_false_negative_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope) update = math_ops.div( tp_update, math_ops.add(tp_update, fn_update), name='update') if metrics_collections: ops.add_to_collections(metrics_collections, metric) if updates_collections: ops.add_to_collections(updates_collections, update) return metric, update def _streaming_sparse_precision_at_k(top_k_idx, labels, k=None, class_id=None, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes precision@k of the top-k indices with respect to sparse labels. This method contains the code shared by streaming_sparse_precision_at_k and streaming_sparse_precision_at_top_k. Refer to those methods for more details. Args: top_k_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and top_k_idx has shape [batch size, k]. The final dimension contains the indices of top-k labels. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range are ignored. k: Integer, k for @k metric or `None`. Only used for default op name. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. If `class_id` is outside this range, the method returns NAN. ignore_mask: An optional, `bool` `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. weights: An optional `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of the metric and of the enclosing scope. Returns: precision: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ top_k_idx = math_ops.to_int64(top_k_idx) weights = _mask_weights(ignore_mask, weights) tp, tp_update = _streaming_sparse_true_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) fp, fp_update = _streaming_sparse_false_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) metric = math_ops.div(tp, math_ops.add(tp, fp), name=name) update = math_ops.div( tp_update, math_ops.add(tp_update, fp_update), name='update') if metrics_collections: ops.add_to_collections(metrics_collections, metric) if updates_collections: ops.add_to_collections(updates_collections, update) return metric, update # TODO(ptucker): Validate range of values in labels? @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_sparse_precision_at_k(predictions, labels, k, class_id=None, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes precision@k of the predictions with respect to sparse labels. If `class_id` is specified, we calculate precision by considering only the entries in the batch for which `class_id` is in the top-k highest `predictions`, and computing the fraction of them for which `class_id` is indeed a correct label. If `class_id` is not specified, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry. `streaming_sparse_precision_at_k` creates two local variables, `true_positive_at_<k>` and `false_positive_at_<k>`, that are used to compute the precision@k frequency. This frequency is ultimately returned as `precision_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_positive_at_<k>`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range are ignored. k: Integer, k for @k metric. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes], where num_classes is the last dimension of `predictions`. If `class_id` is outside this range, the method returns NAN. ignore_mask: An optional, `bool` `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. weights: An optional `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: precision: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ default_name = _at_k_name('precision', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions, labels, ignore_mask, weights)) as scope: _, top_k_idx = nn.top_k(predictions, k) return _streaming_sparse_precision_at_k( top_k_idx=top_k_idx, labels=labels, k=k, class_id=class_id, ignore_mask=ignore_mask, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=scope) # TODO(ptucker): Validate range of values in labels? @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_sparse_precision_at_top_k(top_k_predictions, labels, class_id=None, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes precision@k of top-k predictions with respect to sparse labels. If `class_id` is specified, we calculate precision by considering only the entries in the batch for which `class_id` is in the top-k highest `predictions`, and computing the fraction of them for which `class_id` is indeed a correct label. If `class_id` is not specified, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry. `streaming_sparse_precision_at_top_k` creates two local variables, `true_positive_at_k` and `false_positive_at_k`, that are used to compute the precision@k frequency. This frequency is ultimately returned as `precision_at_k`: an idempotent operation that simply divides `true_positive_at_k` by total (`true_positive_at_k` + `false_positive_at_k`). For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_k`. Internally, set operations applied to `top_k_predictions` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_k` and `false_positive_at_k` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: top_k_predictions: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and top_k_predictions has shape [batch size, k]. The final dimension contains the indices of top-k labels. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `top_k_predictions`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range are ignored. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. If `class_id` is outside this range, the method returns NAN. ignore_mask: An optional, `bool` `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. weights: An optional `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: precision: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. ValueError: If `top_k_predictions` has rank < 2. """ default_name = _at_k_name('precision', class_id=class_id) with ops.name_scope( name, default_name, (top_k_predictions, labels, ignore_mask, weights)) as scope: rank = array_ops.rank(top_k_predictions) check_rank_op = control_flow_ops.Assert( math_ops.greater_equal(rank, 2), ['top_k_predictions must have rank 2 or higher, e.g. [batch_size, k].']) with ops.control_dependencies([check_rank_op]): return _streaming_sparse_precision_at_k( top_k_idx=top_k_predictions, labels=labels, class_id=class_id, ignore_mask=ignore_mask, weights=weights, metrics_collections=metrics_collections, updates_collections=updates_collections, name=scope) def num_relevant(labels, k): """Computes number of relevant values for each row in labels. For labels with shape [D1, ... DN, num_labels], this is the minimum of `num_labels` and `k`. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. k: Integer, k for @k metric. Returns: Integer `Tensor` of shape [D1, ... DN], where each value is the number of relevant values for that row. Raises: ValueError: if inputs have invalid dtypes or values. """ if k < 1: raise ValueError('Invalid k=%s.' % k) with ops.name_scope(None, 'num_relevant', (labels,)) as scope: # For SparseTensor, calculate separate count for each row. if isinstance(labels, (ops.SparseTensor, ops.SparseTensorValue)): labels_sizes = set_ops.set_size(labels) return math_ops.minimum(labels_sizes, k, name=scope) # For dense Tensor, calculate scalar count based on last dimension, and # tile across labels shape. labels_shape = array_ops.shape(labels) labels_size = labels_shape[-1] num_relevant_scalar = math_ops.minimum(labels_size, k) return array_ops.fill(labels_shape[0:-1], num_relevant_scalar, name=scope) def expand_and_tile(tensor, multiple, dim=0, name=None): """Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. multiple: Integer, number of times to tile. dim: Integer, dimension along which to tile. name: Name of operation. Returns: `Tensor` result of expanding and tiling `tensor`. Raises: ValueError: if `multiple` is less than 1, or `dim` is not in `[-rank(tensor), rank(tensor)]`. """ if multiple < 1: raise ValueError('Invalid multiple %s, must be > 0.' % multiple) with ops.name_scope( name, 'expand_and_tile', (tensor, multiple, dim)) as scope: # Sparse. if isinstance(tensor, ops.SparseTensorValue): tensor = ops.SparseTensor.from_value(tensor) if isinstance(tensor, ops.SparseTensor): if dim < 0: expand_dims = array_ops.reshape( array_ops.size(tensor.shape) + dim, [1]) else: expand_dims = [dim] expanded_shape = array_ops.concat( 0, (array_ops.slice(tensor.shape, [0], expand_dims), [1], array_ops.slice(tensor.shape, expand_dims, [-1])), name='expanded_shape') expanded = sparse_ops.sparse_reshape( tensor, shape=expanded_shape, name='expand') if multiple == 1: return expanded return sparse_ops.sparse_concat( dim - 1 if dim < 0 else dim, [expanded] * multiple, name=scope) # Dense. expanded = array_ops.expand_dims( tensor, dim if (dim >= 0) else (dim - 1), name='expand') if multiple == 1: return expanded ones = array_ops.ones_like(array_ops.shape(tensor)) tile_multiples = array_ops.concat( 0, (ones[:dim], (multiple,), ones[dim:]), name='multiples') return array_ops.tile(expanded, tile_multiples, name=scope) def sparse_average_precision_at_k(predictions, labels, k): """Computes average precision@k of predictions with respect to sparse labels. From en.wikipedia.org/wiki/Information_retrieval#Average_precision, formula for each row is: AveP = sum_{i=1...k} P_{i} * rel_{i} / num_relevant_items A "row" is the elements in dimension [D1, ... DN] of `predictions`, `labels`, and the result `Tensors`. In the common case, this is [batch_size]. Each row of the results contains the average precision for that row. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives, which are used to calculate the precision ("P_{i}" term, above). Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and `predictions` has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range are ignored. k: Integer, k for @k metric. This will calculate an average precision for range `[1,k]`, as documented above. Returns: `float64` `Tensor` of shape [D1, ... DN], where each value is the average precision for that row. Raises: ValueError: if k is invalid. """ if k < 1: raise ValueError('Invalid k=%s.' % k) with ops.name_scope( None, 'average_precision', (predictions, labels, k)) as scope: # Calculate top k indices to produce [D1, ... DN, k] tensor. _, predictions_idx = nn.top_k(predictions, k) predictions_idx = math_ops.to_int64(predictions_idx, name='predictions_idx') # Expand dims to produce [D1, ... DN, k, 1] tensor. This gives us a separate # prediction for each k, so we can calculate separate true positive values # for each k. predictions_idx_per_k = array_ops.expand_dims( predictions_idx, -1, name='predictions_idx_per_k') # Replicate labels k times to produce [D1, ... DN, k, num_labels] tensor. labels_per_k = expand_and_tile( labels, multiple=k, dim=-1, name='labels_per_k') # The following tensors are all of shape [D1, ... DN, k], containing values # per row, per k value. # `relevant_per_k` (int32) - Relevance indicator, 1 if the prediction at # that k value is correct, 0 otherwise. This is the "rel_{i}" term from # the formula above. # `tp_per_k` (int32) - True positive counts. # `retrieved_per_k` (int32) - Number of predicted values at each k. This is # the precision denominator. # `precision_per_k` (float64) - Precision at each k. This is the "P_{i}" # term from the formula above. # `relevant_precision_per_k` (float64) - Relevant precisions; i.e., # precisions at all k for which relevance indicator is true. relevant_per_k = _sparse_true_positive_at_k( predictions_idx_per_k, labels_per_k, name='relevant_per_k') tp_per_k = math_ops.cumsum(relevant_per_k, axis=-1, name='tp_per_k') retrieved_per_k = math_ops.cumsum( array_ops.ones_like(relevant_per_k), axis=-1, name='retrieved_per_k') precision_per_k = math_ops.div( math_ops.to_double(tp_per_k), math_ops.to_double(retrieved_per_k), name='precision_per_k') relevant_precision_per_k = math_ops.mul( precision_per_k, math_ops.to_double(relevant_per_k), name='relevant_precision_per_k') # Reduce along k dimension to get the sum, yielding a [D1, ... DN] tensor. precision_sum = math_ops.reduce_sum( relevant_precision_per_k, reduction_indices=(-1,), name='precision_sum') # Divide by number of relevant items to get average precision. These are # the "num_relevant_items" and "AveP" terms from the formula above. num_relevant_items = math_ops.to_double(num_relevant(labels, k)) return math_ops.div(precision_sum, num_relevant_items, name=scope) def streaming_sparse_average_precision_at_k(predictions, labels, k, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes average precision@k of predictions with respect to sparse labels. See `sparse_average_precision_at_k` for details on formula. `weights` are applied to the result of `sparse_average_precision_at_k` `streaming_sparse_average_precision_at_k` creates two local variables, `average_precision_at_<k>/total` and `average_precision_at_<k>/max`, that are used to compute the frequency. This frequency is ultimately returned as `average_precision_at_<k>`: an idempotent operation that simply divides `average_precision_at_<k>/total` by `average_precision_at_<k>/max`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and `predictions` has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_`. Values should be in range [0, num_classes), where num_classes is the last dimension of `predictions`. Values outside this range are ignored. k: Integer, k for @k metric. This will calculate an average precision for range `[1,k]`, as documented above. weights: An optional `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: mean_average_precision: Scalar `float64` `Tensor` with the mean average precision values. update: `Operation` that increments variables appropriately, and whose value matches `metric`. """ default_name = _at_k_name('average_precision', k) with ops.name_scope(name, default_name, (predictions, labels)) as scope: # Calculate per-example average precision, and apply weights. average_precision = sparse_average_precision_at_k( predictions=predictions, labels=labels, k=k) if weights is not None: weights = math_ops.to_double(weights) average_precision = math_ops.mul(average_precision, weights) # Create accumulation variables and update ops for max average precision and # total average precision. with ops.name_scope(None, 'max', (average_precision,)) as max_scope: # `max` is the max possible precision. Since max for any row is 1.0: # - For the unweighted case, this is just the number of rows. # - For the weighted case, it's the sum of the weights broadcast across # `average_precision` rows. max_var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=max_scope) if weights is None: batch_max = math_ops.to_double( array_ops.size(average_precision, name='batch_max')) else: # TODO(ptucker): More efficient way to broadcast? broadcast_weights = math_ops.mul( weights, array_ops.ones_like(average_precision), name='broadcast_weights') batch_max = math_ops.reduce_sum(broadcast_weights, name='batch_max') max_update = state_ops.assign_add(max_var, batch_max, name='update') with ops.name_scope(None, 'total', (average_precision,)) as total_scope: total_var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=total_scope) batch_total = math_ops.reduce_sum(average_precision, name='batch_total') total_update = state_ops.assign_add(total_var, batch_total, name='update') # Divide total by max to get mean, for both vars and the update ops. mean_average_precision = _safe_scalar_div(total_var, max_var, name='mean') update = _safe_scalar_div(total_update, max_update, name=scope) if metrics_collections: ops.add_to_collections(metrics_collections, mean_average_precision) if updates_collections: ops.add_to_collections(updates_collections, update) return mean_average_precision, update def _select_class_id(ids, selected_id): """Filter all but `selected_id` out of `ids`. Args: ids: `int64` `Tensor` or `SparseTensor` of IDs. selected_id: Int id to select. Returns: `SparseTensor` of same dimensions as `ids`. This contains only the entries equal to `selected_id`. """ if isinstance(ids, (ops.SparseTensor, ops.SparseTensorValue)): return sparse_ops.sparse_retain( ids, math_ops.equal(ids.values, selected_id)) # TODO(ptucker): Make this more efficient, maybe add a sparse version of # tf.equal and tf.reduce_any? # Shape of filled IDs is the same as `ids` with the last dim collapsed to 1. ids_shape = array_ops.shape(ids, out_type=dtypes.int64) ids_last_dim = array_ops.size(ids_shape) - 1 filled_selected_id_shape = math_ops.reduced_shape( ids_shape, array_ops.reshape(ids_last_dim, [1])) # Intersect `ids` with the selected ID. filled_selected_id = array_ops.fill( filled_selected_id_shape, math_ops.to_int64(selected_id)) result = set_ops.set_intersection(filled_selected_id, ids) return ops.SparseTensor( indices=result.indices, values=result.values, shape=ids_shape) def _maybe_select_class_id(labels, predictions_idx, selected_id=None): """If class ID is specified, filter all other classes. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. predictions_idx: `int64` `Tensor` of class IDs, with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and `predictions_idx` has shape [batch size, k]. selected_id: Int id to select. Returns: Tuple of `labels` and `predictions_idx`, possibly with classes removed. """ if selected_id is None: return labels, predictions_idx return (_select_class_id(labels, selected_id), _select_class_id(predictions_idx, selected_id)) def _sparse_true_positive_at_k(predictions_idx, labels, class_id=None, weights=None, name=None): """Calculates true positives for recall@k and precision@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. name: Name of operation. Returns: A [D1, ... DN] `Tensor` of true positive counts. """ with ops.name_scope(name, 'true_positives', (predictions_idx, labels)): labels, predictions_idx = _maybe_select_class_id( labels, predictions_idx, class_id) tp = set_ops.set_size(set_ops.set_intersection(predictions_idx, labels)) tp = math_ops.to_double(tp) if weights is not None: weights = math_ops.to_double(weights) tp = math_ops.mul(tp, weights) return tp def _streaming_sparse_true_positive_at_k(predictions_idx, labels, k=None, class_id=None, weights=None, name=None): """Calculates weighted per step true positives for recall@k and precision@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. k: Integer, k for @k metric. This is only used for default op name. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. name: Name of new variable, and namespace for other dependent ops. Returns: A tuple of `Variable` and update `Operation`. Raises: ValueError: If `weights` is not `None` and has an incomptable shape. """ default_name = _at_k_name('true_positive', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions_idx, labels)) as scope: tp = _sparse_true_positive_at_k( predictions_idx=predictions_idx, labels=labels, class_id=class_id, weights=weights) batch_total_tp = math_ops.to_double(math_ops.reduce_sum(tp)) var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=scope) return var, state_ops.assign_add(var, batch_total_tp, name='update') def _sparse_false_positive_at_k(predictions_idx, labels, class_id=None, weights=None): """Calculates false positives for precision@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. Returns: A [D1, ... DN] `Tensor` of false positive counts. """ with ops.name_scope(None, 'false_positives', (predictions_idx, labels)): labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, class_id) fp = set_ops.set_size(set_ops.set_difference( predictions_idx, labels, aminusb=True)) fp = math_ops.to_double(fp) if weights is not None: weights = math_ops.to_double(weights) fp = math_ops.mul(fp, weights) return fp def _streaming_sparse_false_positive_at_k(predictions_idx, labels, k=None, class_id=None, weights=None, name=None): """Calculates weighted per step false positives for precision@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. k: Integer, k for @k metric. This is only used for default op name. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. name: Name of new variable, and namespace for other dependent ops. Returns: A tuple of `Variable` and update `Operation`. Raises: ValueError: If `weights` is not `None` and has an incomptable shape. """ default_name = _at_k_name('false_positive', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions_idx, labels)) as scope: fp = _sparse_false_positive_at_k( predictions_idx=predictions_idx, labels=labels, class_id=class_id, weights=weights) batch_total_fp = math_ops.to_double(math_ops.reduce_sum(fp)) var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=scope) return var, state_ops.assign_add(var, batch_total_fp, name='update') def _sparse_false_negative_at_k(predictions_idx, labels, class_id=None, weights=None): """Calculates false negatives for recall@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels_sparse`. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. Returns: A [D1, ... DN] `Tensor` of false negative counts. """ with ops.name_scope(None, 'false_negatives', (predictions_idx, labels)): labels, predictions_idx = _maybe_select_class_id(labels, predictions_idx, class_id) fn = set_ops.set_size(set_ops.set_difference(predictions_idx, labels, aminusb=False)) fn = math_ops.to_double(fn) if weights is not None: weights = math_ops.to_double(weights) fn = math_ops.mul(fn, weights) return fn def _streaming_sparse_false_negative_at_k(predictions_idx, labels, k, class_id=None, weights=None, name=None): """Calculates weighted per step false negatives for recall@k. If `class_id` is specified, calculate binary true positives for `class_id` only. If `class_id` is not specified, calculate metrics for `k` predicted vs `n` label classes, where `n` is the 2nd dimension of `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions_idx: 1-D or higher `int64` `Tensor` with last dimension `k`, top `k` predicted classes. For rank `n`, the first `n-1` dimensions must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. k: Integer, k for @k metric. This is only used for default op name. class_id: Class for which we want binary metrics. weights: `Tensor` whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. name: Name of new variable, and namespace for other dependent ops. Returns: A tuple of `Variable` and update `Operation`. Raises: ValueError: If `weights` is not `None` and has an incomptable shape. """ default_name = _at_k_name('false_negative', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions_idx, labels)) as scope: fn = _sparse_false_negative_at_k( predictions_idx=predictions_idx, labels=labels, class_id=class_id, weights=weights) batch_total_fn = math_ops.to_double(math_ops.reduce_sum(fn)) var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=scope) return var, state_ops.assign_add(var, batch_total_fn, name='update') def streaming_mean_absolute_error(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the mean absolute error between the labels and predictions. The `streaming_mean_absolute_error` function creates two local variables, `total` and `count` that are used to compute the mean absolute error. This average is weighted by `weights`, and it is ultimately returned as `mean_absolute_error`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_absolute_error`. Internally, an `absolute_errors` operation computes the absolute value of the differences between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `absolute_errors`, and it increments `count` with the reduced sum of `weights` If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A `Tensor` of arbitrary shape. labels: A `Tensor` of the same shape as `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `mean_absolute_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean_absolute_error: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_absolute_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) absolute_errors = math_ops.abs(predictions - labels) return streaming_mean(absolute_errors, weights, metrics_collections, updates_collections, name or 'mean_absolute_error') def streaming_mean_relative_error(predictions, labels, normalizer, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the mean relative error by normalizing with the given values. The `streaming_mean_relative_error` function creates two local variables, `total` and `count` that are used to compute the mean relative absolute error. This average is weighted by `weights`, and it is ultimately returned as `mean_relative_error`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_reative_error`. Internally, a `relative_errors` operation divides the absolute value of the differences between `predictions` and `labels` by the `normalizer`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `relative_errors`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A `Tensor` of arbitrary shape. labels: A `Tensor` of the same shape as `predictions`. normalizer: A `Tensor` of the same shape as `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `mean_relative_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean_relative_error: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_relative_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) predictions, normalizer = tensor_util.remove_squeezable_dimensions( predictions, normalizer) predictions.get_shape().assert_is_compatible_with(normalizer.get_shape()) relative_errors = math_ops.select( math_ops.equal(normalizer, 0.0), array_ops.zeros_like(labels), math_ops.div(math_ops.abs(labels - predictions), normalizer)) return streaming_mean(relative_errors, weights, metrics_collections, updates_collections, name or 'mean_relative_error') def streaming_mean_squared_error(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the mean squared error between the labels and predictions. The `streaming_mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the mean squared error. This average is weighted by `weights`, and it is ultimately returned as `mean_squared_error`: an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A `Tensor` of arbitrary shape. labels: A `Tensor` of the same shape as `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `mean_squared_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: mean_squared_error: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_squared_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) squared_error = math_ops.square(labels - predictions) return streaming_mean(squared_error, weights, metrics_collections, updates_collections, name or 'mean_squared_error') def streaming_root_mean_squared_error(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the root mean squared error between the labels and predictions. The `streaming_root_mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the root mean squared error. This average is weighted by `weights`, and it is ultimately returned as `root_mean_squared_error`: an idempotent operation that takes the square root of the division of `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `root_mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A `Tensor` of arbitrary shape. labels: A `Tensor` of the same shape as `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `root_mean_squared_error` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_scope name. Returns: root_mean_squared_error: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `root_mean_squared_error`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) value_tensor, update_op = streaming_mean_squared_error( predictions, labels, weights, None, None, name or 'root_mean_squared_error') root_mean_squared_error = math_ops.sqrt(value_tensor) with ops.control_dependencies([update_op]): update_op = math_ops.sqrt(update_op) if metrics_collections: ops.add_to_collections(metrics_collections, root_mean_squared_error) if updates_collections: ops.add_to_collections(updates_collections, update_op) return root_mean_squared_error, update_op def streaming_covariance(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the unbiased sample covariance between `predictions` and `labels`. The `streaming_covariance` function creates four local variables, `comoment`, `mean_prediction`, `mean_label`, and `count`, which are used to compute the sample covariance between predictions and labels across multiple batches of data. The covariance is ultimately returned as an idempotent operation that simply divides `comoment` by `count` - 1. We use `count` - 1 in order to get an unbiased estimate. The algorithm used for this online computation is described in https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance. Specifically, the formula used to combine two sample comoments is `C_AB = C_A + C_B + (E[x_A] - E[x_B]) * (E[y_A] - E[y_B]) * n_A * n_B / n_AB` The comoment for a single batch of data is simply `sum((x - E[x]) * (y - E[y]))`, optionally weighted. If `weights` is not None, then it is used to compute weighted comoments, means, and count. NOTE: these weights are treated as "frequency weights", as opposed to "reliability weights". See discussion of the difference on https://wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance To facilitate the computation of covariance across multiple batches of data, the function creates an `update_op` operation, which updates underlying variables and returns the updated covariance. Args: predictions: A `Tensor` of arbitrary size. labels: A `Tensor` of the same size as `predictions`. weights: An optional set of weights which indicates the frequency with which an example is sampled. Must be broadcastable with `labels`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: covariance: A `Tensor` representing the current unbiased sample covariance, `comoment` / (`count` - 1). update_op: An operation that updates the local variables appropriately. Raises: ValueError: If labels and predictions are of different sizes or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'covariance', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) count = _create_local('count', []) mean_prediction = _create_local('mean_prediction', []) mean_label = _create_local('mean_label', []) comoment = _create_local('comoment', []) # C_A in update equation if weights is None: batch_count = math_ops.to_float(array_ops.size(labels)) # n_B in eqn weighted_predictions = predictions weighted_labels = labels else: batch_count = math_ops.reduce_sum( _broadcast_weights(weights, labels)) # n_B in eqn weighted_predictions = predictions * weights weighted_labels = labels * weights update_count = state_ops.assign_add(count, batch_count) # n_AB in eqn prev_count = update_count - batch_count # n_A in update equation # We update the means by Delta=Error*BatchCount/(BatchCount+PrevCount) # batch_mean_prediction is E[x_B] in the update equation batch_mean_prediction = _safe_div( math_ops.reduce_sum(weighted_predictions), batch_count, 'batch_mean_prediction') delta_mean_prediction = _safe_div( (batch_mean_prediction - mean_prediction) * batch_count, update_count, 'delta_mean_prediction') update_mean_prediction = state_ops.assign_add(mean_prediction, delta_mean_prediction) # prev_mean_prediction is E[x_A] in the update equation prev_mean_prediction = update_mean_prediction - delta_mean_prediction # batch_mean_label is E[y_B] in the update equation batch_mean_label = _safe_div( math_ops.reduce_sum(weighted_labels), batch_count, 'batch_mean_label') delta_mean_label = _safe_div((batch_mean_label - mean_label) * batch_count, update_count, 'delta_mean_label') update_mean_label = state_ops.assign_add(mean_label, delta_mean_label) # prev_mean_label is E[y_A] in the update equation prev_mean_label = update_mean_label - delta_mean_label unweighted_batch_coresiduals = ( (predictions - batch_mean_prediction) * (labels - batch_mean_label)) # batch_comoment is C_B in the update equation if weights is None: batch_comoment = math_ops.reduce_sum(unweighted_batch_coresiduals) else: batch_comoment = math_ops.reduce_sum(unweighted_batch_coresiduals * weights) # View delta_comoment as = C_AB - C_A in the update equation above. # Since C_A is stored in a var, by how much do we need to increment that var # to make the var = C_AB? delta_comoment = (batch_comoment + (prev_mean_prediction - batch_mean_prediction) * (prev_mean_label - batch_mean_label) * (prev_count * batch_count / update_count)) update_comoment = state_ops.assign_add(comoment, delta_comoment) covariance = _safe_div(comoment, count - 1, 'covariance') with ops.control_dependencies([update_comoment]): update_op = _safe_div(comoment, count - 1, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, covariance) if updates_collections: ops.add_to_collections(updates_collections, update_op) return covariance, update_op def streaming_pearson_correlation(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes Pearson correlation coefficient between `predictions`, `labels`. The `streaming_pearson_correlation` function delegates to `streaming_covariance` the tracking of three [co]variances: - `streaming_covariance(predictions, labels)`, i.e. covariance - `streaming_covariance(predictions, predictions)`, i.e. variance - `streaming_covariance(labels, labels)`, i.e. variance The product-moment correlation ultimately returned is an idempotent operation `cov(predictions, labels) / sqrt(var(predictions) * var(labels))`. To facilitate correlation computation across multiple batches, the function groups the `update_op`s of the underlying streaming_covariance and returns an `update_op`. If `weights` is not None, then it is used to compute a weighted correlation. NOTE: these weights are treated as "frequency weights", as opposed to "reliability weights". See discussion of the difference on https://wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance Args: predictions: A `Tensor` of arbitrary size. labels: A `Tensor` of the same size as predictions. weights: An optional set of weights which indicates the frequency with which an example is sampled. Must be broadcastable with `labels`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: pearson_r: A tensor representing the current Pearson product-moment correlation coefficient, the value of `cov(predictions, labels) / sqrt(var(predictions) * var(labels))`. update_op: An operation that updates the underlying variables appropriately. Raises: ValueError: If `labels` and `predictions` are of different sizes, or if `weights` is the wrong size, or if either `metrics_collections` or `updates_collections` are not a `list` or `tuple`. """ with variable_scope.variable_scope(name, 'pearson_r', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) cov, update_cov = streaming_covariance( predictions, labels, weights=weights, name='covariance') var_predictions, update_var_predictions = streaming_covariance( predictions, predictions, weights=weights, name='variance_predictions') var_labels, update_var_labels = streaming_covariance( labels, labels, weights=weights, name='variance_labels') pearson_r = _safe_div( cov, math_ops.mul(math_ops.sqrt(var_predictions), math_ops.sqrt(var_labels)), 'pearson_r') with ops.control_dependencies( [update_cov, update_var_predictions, update_var_labels]): update_op = _safe_div(update_cov, math_ops.mul( math_ops.sqrt(update_var_predictions), math_ops.sqrt(update_var_labels)), 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, pearson_r) if updates_collections: ops.add_to_collections(updates_collections, update_op) return pearson_r, update_op # TODO(nsilberman): add a 'normalized' flag so that the user can request # normalization if the inputs are not normalized. def streaming_mean_cosine_distance(predictions, labels, dim, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the cosine distance between the labels and predictions. The `streaming_mean_cosine_distance` function creates two local variables, `total` and `count` that are used to compute the average cosine distance between `predictions` and `labels`. This average is weighted by `weights`, and it is ultimately returned as `mean_distance`, which is an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_distance`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: predictions: A `Tensor` of the same shape as `labels`. labels: A `Tensor` of arbitrary shape. dim: The dimension along which the cosine distance is computed. weights: An optional `Tensor` whose shape is broadcastable to `predictions`, and whose dimension `dim` is 1. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: mean_distance: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) radial_diffs = math_ops.mul(predictions, labels) radial_diffs = math_ops.reduce_sum(radial_diffs, reduction_indices=[dim,], keep_dims=True) mean_distance, update_op = streaming_mean(radial_diffs, weights, None, None, name or 'mean_cosine_distance') mean_distance = math_ops.sub(1.0, mean_distance) update_op = math_ops.sub(1.0, update_op) if metrics_collections: ops.add_to_collections(metrics_collections, mean_distance) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean_distance, update_op @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_percentage_less(values, threshold, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the percentage of values less than the given threshold. The `streaming_percentage_less` function creates two local variables, `total` and `count` that are used to compute the percentage of `values` that fall below `threshold`. This rate is weighted by `weights`, and it is ultimately returned as `percentage` which is an idempotent operation that simply divides `total` by `count`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `percentage`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: values: A numeric `Tensor` of arbitrary size. threshold: A scalar threshold. ignore_mask: An optional, `bool` `Tensor` whose shape matches `values`. weights: An optional `Tensor` whose shape is broadcastable to `values`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: percentage: A tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `values`, or if `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ is_below_threshold = math_ops.to_float(math_ops.less(values, threshold)) return streaming_mean(is_below_threshold, _mask_weights(ignore_mask, weights), metrics_collections, updates_collections, name or 'percentage_below_threshold') @deprecated_args(IGNORE_MASK_DATE, IGNORE_MASK_INSTRUCTIONS, 'ignore_mask') def streaming_mean_iou(predictions, labels, num_classes, ignore_mask=None, weights=None, metrics_collections=None, updates_collections=None, name=None): """Calculate per-step mean Intersection-Over-Union (mIOU). Mean Intersection-Over-Union is a common evaluation metric for semantic image segmentation, which first computes the IOU for each semantic class and then computes the average over classes. IOU is defined as follows: IOU = true_positive / (true_positive + false_positive + false_negative). The predictions are accumulated in a confusion matrix, weighted by `weights`, and mIOU is then calculated from it. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_iou`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Alternatively, if `ignore_mask` is not `None`, then mask values where `ignore_mask` is `True`. Args: predictions: A tensor of prediction results for semantic labels, whose shape is [batch size] and type `int32` or `int64`. The tensor will be flattened, if its rank > 1. labels: A tensor of ground truth labels with shape [batch size] and of type `int32` or `int64`. The tensor will be flattened, if its rank > 1. num_classes: The possible number of labels the prediction task can have. This value must be provided, since a confusion matrix of dimension = [num_classes, num_classes] will be allocated. ignore_mask: An optional, `bool` `Tensor` whose shape matches `predictions`. weights: An optional `Tensor` whose shape is broadcastable to `predictions`. metrics_collections: An optional list of collections that `mean_iou` should be added to. updates_collections: An optional list of collections `update_op` should be added to. name: An optional variable_scope name. Returns: mean_iou: A tensor representing the mean intersection-over-union. update_op: An operation that increments the confusion matrix. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean_iou', [predictions, labels]): # Check if shape is compatible. predictions.get_shape().assert_is_compatible_with(labels.get_shape()) # Local variable to accumulate the predictions in the confusion matrix. cm_dtype = dtypes.int64 if weights is not None else dtypes.float64 total_cm = _create_local('total_confusion_matrix', shape=[num_classes, num_classes], dtype=cm_dtype) # Cast the type to int64 required by confusion_matrix_ops. predictions = math_ops.to_int64(predictions) labels = math_ops.to_int64(labels) num_classes = math_ops.to_int64(num_classes) # Flatten the input if its rank > 1. predictions_rank = predictions.get_shape().ndims if predictions_rank > 1: predictions = array_ops.reshape(predictions, [-1]) labels_rank = labels.get_shape().ndims if labels_rank > 1: labels = array_ops.reshape(labels, [-1]) weights = _mask_weights(ignore_mask, weights) if weights is not None: weights_rank = weights.get_shape().ndims if weights_rank > 1: weights = array_ops.reshape(weights, [-1]) # Accumulate the prediction to current confusion matrix. current_cm = confusion_matrix_ops.confusion_matrix( predictions, labels, num_classes, weights=weights, dtype=cm_dtype) update_op = state_ops.assign_add(total_cm, current_cm) def compute_mean_iou(name): """Compute the mean intersection-over-union via the confusion matrix.""" sum_over_row = math_ops.to_float(math_ops.reduce_sum(total_cm, 0)) sum_over_col = math_ops.to_float(math_ops.reduce_sum(total_cm, 1)) cm_diag = math_ops.to_float(array_ops.diag_part(total_cm)) denominator = sum_over_row + sum_over_col - cm_diag # If the value of the denominator is 0, set it to 1 to avoid # zero division. denominator = math_ops.select( math_ops.greater(denominator, 0), denominator, array_ops.ones_like(denominator)) iou = math_ops.div(cm_diag, denominator) return math_ops.reduce_mean(iou, name=name) mean_iou = compute_mean_iou('mean_iou') if metrics_collections: ops.add_to_collections(metrics_collections, mean_iou) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean_iou, update_op def _next_array_size(required_size, growth_factor=1.5): """Calculate the next size for reallocating a dynamic array. Args: required_size: number or tf.Tensor specifying required array capacity. growth_factor: optional number or tf.Tensor specifying the growth factor between subsequent allocations. Returns: tf.Tensor with dtype=int32 giving the next array size. """ exponent = math_ops.ceil( math_ops.log(math_ops.cast(required_size, dtypes.float32)) / math_ops.log(math_ops.cast(growth_factor, dtypes.float32))) return math_ops.cast(math_ops.ceil(growth_factor ** exponent), dtypes.int32) def streaming_concat(values, axis=0, max_size=None, metrics_collections=None, updates_collections=None, name=None): """Concatenate values along an axis across batches. The function `streaming_concat` creates two local variables, `array` and `size`, that are used to store concatenated values. Internally, `array` is used as storage for a dynamic array (if `maxsize` is `None`), which ensures that updates can be run in amortized constant time. For estimation of the metric over a stream of data, the function creates an `update_op` operation that appends the values of a tensor and returns the `value` of the concatenated tensors. This op allows for evaluating metrics that cannot be updated incrementally using the same framework as other streaming metrics. Args: values: tensor to concatenate. Rank and the shape along all axes other than the axis to concatenate along must be statically known. axis: optional integer axis to concatenate along. max_size: optional integer maximum size of `value` along the given axis. Once the maximum size is reached, further updates are no-ops. By default, there is no maximum size: the array is resized as necessary. metrics_collections: An optional list of collections that `value` should be added to. updates_collections: An optional list of collections `update_op` should be added to. name: An optional variable_scope name. Returns: value: A tensor representing the concatenated values. update_op: An operation that concatenates the next values. Raises: ValueError: if `values` does not have a statically known rank, `axis` is not in the valid range or the size of `values` is not statically known along any axis other than `axis`. """ with variable_scope.variable_scope(name, 'streaming_concat', [values]): # pylint: disable=invalid-slice-index values_shape = values.get_shape() if values_shape.dims is None: raise ValueError('`values` must have known statically known rank') ndim = len(values_shape) if axis < 0: axis += ndim if not 0 <= axis < ndim: raise ValueError('axis = %r not in [0, %r)' % (axis, ndim)) fixed_shape = [dim.value for n, dim in enumerate(values_shape) if n != axis] if any(value is None for value in fixed_shape): raise ValueError('all dimensions of `values` other than the dimension to ' 'concatenate along must have statically known size') # We move `axis` to the front of the internal array so assign ops can be # applied to contiguous slices init_size = 0 if max_size is None else max_size init_shape = [init_size] + fixed_shape array = _create_local( 'array', shape=init_shape, validate_shape=False, dtype=values.dtype) size = _create_local('size', shape=[], dtype=dtypes.int32) perm = [0 if n == axis else n + 1 if n < axis else n for n in range(ndim)] valid_array = array[:size] valid_array.set_shape([None] + fixed_shape) value = array_ops.transpose(valid_array, perm, name='concat') values_size = array_ops.shape(values)[axis] if max_size is None: batch_size = values_size else: batch_size = math_ops.minimum(values_size, max_size - size) perm = [axis] + [n for n in range(ndim) if n != axis] batch_values = array_ops.transpose(values, perm)[:batch_size] def reallocate(): next_size = _next_array_size(new_size) next_shape = array_ops.pack([next_size] + fixed_shape) new_value = array_ops.zeros(next_shape, dtype=values.dtype) old_value = array.value() assign_op = state_ops.assign(array, new_value, validate_shape=False) with ops.control_dependencies([assign_op]): copy_op = array[:size].assign(old_value[:size]) # return value needs to be the same dtype as no_op() for cond with ops.control_dependencies([copy_op]): return control_flow_ops.no_op() new_size = size + batch_size array_size = array_ops.shape_internal(array, optimize=False)[0] maybe_reallocate_op = control_flow_ops.cond( new_size > array_size, reallocate, control_flow_ops.no_op) with ops.control_dependencies([maybe_reallocate_op]): append_values_op = array[size:new_size].assign(batch_values) with ops.control_dependencies([append_values_op]): update_op = size.assign(new_size) if metrics_collections: ops.add_to_collections(metrics_collections, value) if updates_collections: ops.add_to_collections(updates_collections, update_op) return value, update_op # pylint: enable=invalid-slice-index def aggregate_metrics(*value_update_tuples): """Aggregates the metric value tensors and update ops into two lists. Args: *value_update_tuples: a variable number of tuples, each of which contain the pair of (value_tensor, update_op) from a streaming metric. Returns: a list of value tensors and a list of update ops. Raises: ValueError: if `value_update_tuples` is empty. """ if not value_update_tuples: raise ValueError('Expected at least one value_tensor/update_op pair') value_ops, update_ops = zip(*value_update_tuples) return list(value_ops), list(update_ops) def aggregate_metric_map(names_to_tuples): """Aggregates the metric names to tuple dictionary. This function is useful for pairing metric names with their associated value and update ops when the list of metrics is long. For example: ```python metrics_to_values, metrics_to_updates = slim.metrics.aggregate_metric_map({ 'Mean Absolute Error': new_slim.metrics.streaming_mean_absolute_error( predictions, labels, weights), 'Mean Relative Error': new_slim.metrics.streaming_mean_relative_error( predictions, labels, labels, weights), 'RMSE Linear': new_slim.metrics.streaming_root_mean_squared_error( predictions, labels, weights), 'RMSE Log': new_slim.metrics.streaming_root_mean_squared_error( predictions, labels, weights), }) ``` Args: names_to_tuples: a map of metric names to tuples, each of which contain the pair of (value_tensor, update_op) from a streaming metric. Returns: A dictionary from metric names to value ops and a dictionary from metric names to update ops. """ metric_names = names_to_tuples.keys() value_ops, update_ops = zip(*names_to_tuples.values()) return dict(zip(metric_names, value_ops)), dict(zip(metric_names, update_ops)) __all__ = [ 'aggregate_metric_map', 'aggregate_metrics', 'streaming_accuracy', 'streaming_auc', 'streaming_mean', 'streaming_mean_absolute_error', 'streaming_mean_cosine_distance', 'streaming_mean_iou', 'streaming_mean_relative_error', 'streaming_mean_squared_error', 'streaming_mean_tensor', 'streaming_percentage_less', 'streaming_precision', 'streaming_precision_at_thresholds', 'streaming_recall', 'streaming_recall_at_k', 'streaming_recall_at_thresholds', 'streaming_root_mean_squared_error', 'streaming_sensitivity_at_specificity', 'streaming_sparse_average_precision_at_k', 'streaming_sparse_precision_at_k', 'streaming_sparse_recall_at_k', 'streaming_specificity_at_sensitivity', ]
[ "tensorflow.python.ops.math_ops.greater_equal", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.nn.in_top_k", "tensorflow.python.ops.math_ops.ceil", "tensorflow.python.ops.state_ops.assign_add", "tensorflow.python.ops.math_ops.to_double", "tensorflow.python.ops.math_ops.greater", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.math_ops.sqrt", "tensorflow.python.ops.math_ops.to_float", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.ops.array_ops.diag_part", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.ops.math_ops.sub", "tensorflow.python.ops.math_ops.logical_and", "tensorflow.python.ops.math_ops.logical_not", "tensorflow.contrib.metrics.python.ops.set_ops.set_intersection", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.ops.math_ops.to_int64", "tensorflow.python.ops.math_ops.abs", "tensorflow.python.ops.array_ops.fill", "tensorflow.contrib.metrics.python.ops.set_ops.set_size", "tensorflow.python.ops.math_ops.argmax", "tensorflow.python.ops.math_ops.less", "tensorflow.python.ops.sparse_ops.sparse_concat", "tensorflow.contrib.metrics.python.ops.set_ops.set_difference", "tensorflow.python.ops.math_ops.add", "tensorflow.python.ops.array_ops.size", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.array_ops.pack", "tensorflow.python.ops.sparse_ops.sparse_reshape", "tensorflow.contrib.framework.deprecated_args", "tensorflow.python.ops.math_ops.cast", "tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions", "tensorflow.python.ops.math_ops.minimum", "tensorflow.contrib.metrics.python.ops.confusion_matrix_ops.confusion_matrix", "tensorflow.python.ops.array_ops.tile", "tensorflow.python.ops.array_ops.slice", "tensorflow.python.framework.ops.SparseTensor", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.ops.math_ops.truediv", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.ops.math_ops.div", "tensorflow.python.ops.math_ops.mul", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.ops.nn.top_k", "tensorflow.python.ops.check_ops.assert_type", "tensorflow.python.framework.ops.SparseTensor.from_value", "tensorflow.python.framework.ops.add_to_collections", "tensorflow.contrib.framework.deprecated", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.shape_internal", "tensorflow.python.ops.math_ops.cumsum", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_sum" ]
tensorflow/contrib/metrics/python/ops/metric_ops.py
[(519, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (602, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (1235, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-08"""', '"""Please use `streaming_sparse_recall_at_k`, and reshape labels from [batch_size] to [batch_size, 1]."""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (1237, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (1295, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (1468, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (1564, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (2762, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (2813, 'tensorflow.contrib.framework.deprecated_args', 'deprecated_args', (['IGNORE_MASK_DATE', 'IGNORE_MASK_INSTRUCTIONS', '"""ignore_mask"""'], {}), False, 'from tensorflow.contrib.framework import deprecated_args\n'), (165, 'tensorflow.python.ops.check_ops.assert_type', 'check_ops.assert_type', (['values', 'dtypes.bool'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (168, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['values'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (173, 'tensorflow.python.ops.array_ops.identity', 'array_ops.identity', (['count'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (509, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (724, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (731, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['predictions', '[-1, 1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (749, 'tensorflow.python.ops.math_ops.logical_not', 'math_ops.logical_not', (['pred_is_pos'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (752, 'tensorflow.python.ops.array_ops.tile', 'array_ops.tile', (['labels_2d', '[num_thresholds, 1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (753, 'tensorflow.python.ops.math_ops.logical_not', 'math_ops.logical_not', (['label_is_pos'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1448, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['top_k_idx'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1962, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['ids'], {'out_type': 'dtypes.int64'}), False, 'from tensorflow.python.ops import array_ops\n'), (1970, 'tensorflow.contrib.metrics.python.ops.set_ops.set_intersection', 'set_ops.set_intersection', (['filled_selected_id', 'ids'], {}), False, 'from tensorflow.contrib.metrics.python.ops import set_ops\n'), (1971, 'tensorflow.python.framework.ops.SparseTensor', 'ops.SparseTensor', ([], {'indices': 'result.indices', 'values': 'result.values', 'shape': 'ids_shape'}), False, 'from tensorflow.python.framework import ops\n'), (2307, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2310, 'tensorflow.python.ops.math_ops.abs', 'math_ops.abs', (['(predictions - labels)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2360, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2364, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'normalizer'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2419, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2422, 'tensorflow.python.ops.math_ops.square', 'math_ops.square', (['(labels - predictions)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2471, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2478, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['value_tensor'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2739, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2742, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['predictions', 'labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2743, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['radial_diffs'], {'reduction_indices': '[dim]', 'keep_dims': '(True)'}), False, 'from tensorflow.python.ops import math_ops\n'), (2750, 'tensorflow.python.ops.math_ops.sub', 'math_ops.sub', (['(1.0)', 'mean_distance'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2751, 'tensorflow.python.ops.math_ops.sub', 'math_ops.sub', (['(1.0)', 'update_op'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (70, 'tensorflow.python.ops.check_ops.assert_type', 'check_ops.assert_type', (['mask', 'dtypes.bool'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (90, 'tensorflow.python.ops.math_ops.greater', 'math_ops.greater', (['denominator', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (91, 'tensorflow.python.ops.math_ops.truediv', 'math_ops.truediv', (['numerator', 'denominator'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (170, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (171, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['values', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (174, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['values'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (177, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'value_tensor'], {}), False, 'from tensorflow.python.framework import ops\n'), (180, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (215, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""true_positives"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (255, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""false_positives"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (294, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""false_negatives"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (326, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['values'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (365, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""mean"""', '[values, weights]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (366, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['values'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (379, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['count', 'num_values'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (434, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""mean"""', '[values, weights]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (438, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['values'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (444, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['total', 'values'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (445, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['count', 'num_values'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (513, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['predictions', 'labels.dtype'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (514, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['predictions', 'labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (566, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""precision"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (569, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (647, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""recall"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (648, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (733, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['labels'], {'dtype': 'dtypes.bool'}), False, 'from tensorflow.python.ops import math_ops\n'), (743, 'tensorflow.python.ops.array_ops.pack', 'array_ops.pack', (['[1, num_predictions]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (761, 'tensorflow.python.ops.math_ops.logical_and', 'math_ops.logical_and', (['label_is_pos', 'pred_is_pos'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (763, 'tensorflow.python.ops.math_ops.logical_and', 'math_ops.logical_and', (['label_is_pos', 'pred_is_neg'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (765, 'tensorflow.python.ops.math_ops.logical_and', 'math_ops.logical_and', (['label_is_neg', 'pred_is_pos'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (767, 'tensorflow.python.ops.math_ops.logical_and', 'math_ops.logical_and', (['label_is_neg', 'pred_is_neg'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (770, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (781, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['is_true_positive', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (783, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['is_false_negative', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (785, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['is_true_negative', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (787, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['is_false_positive', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (845, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""auc"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (942, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""specificity_at_sensitivity"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (1046, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""sensitivity_at_specificity"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (1125, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""precision_at_thresholds"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (1197, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""recall_at_thresholds"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (1286, 'tensorflow.python.ops.nn.in_top_k', 'nn.in_top_k', (['predictions', 'labels', 'k'], {}), False, 'from tensorflow.python.ops import nn\n'), (1373, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1374, 'tensorflow.python.ops.nn.top_k', 'nn.top_k', (['predictions', 'k'], {}), False, 'from tensorflow.python.ops import nn\n'), (1375, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['top_k_idx'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1457, 'tensorflow.python.ops.math_ops.add', 'math_ops.add', (['tp', 'fp'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1459, 'tensorflow.python.ops.math_ops.add', 'math_ops.add', (['tp_update', 'fp_update'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1461, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'metric'], {}), False, 'from tensorflow.python.framework import ops\n'), (1463, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update'], {}), False, 'from tensorflow.python.framework import ops\n'), (1548, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions, labels, ignore_mask, weights)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1550, 'tensorflow.python.ops.nn.top_k', 'nn.top_k', (['predictions', 'k'], {}), False, 'from tensorflow.python.ops import nn\n'), (1641, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(top_k_predictions, labels, ignore_mask, weights)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1644, 'tensorflow.python.ops.array_ops.rank', 'array_ops.rank', (['top_k_predictions'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1682, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""num_relevant"""', '(labels,)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1690, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['labels'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1692, 'tensorflow.python.ops.math_ops.minimum', 'math_ops.minimum', (['labels_size', 'k'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1693, 'tensorflow.python.ops.array_ops.fill', 'array_ops.fill', (['labels_shape[0:-1]', 'num_relevant_scalar'], {'name': 'scope'}), False, 'from tensorflow.python.ops import array_ops\n'), (1717, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', '"""expand_and_tile"""', '(tensor, multiple, dim)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1740, 'tensorflow.python.ops.array_ops.expand_dims', 'array_ops.expand_dims', (['tensor', '(dim if dim >= 0 else dim - 1)'], {'name': '"""expand"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (1745, 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['(0)', '(ones[:dim], (multiple,), ones[dim:])'], {'name': '"""multiples"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (1747, 'tensorflow.python.ops.array_ops.tile', 'array_ops.tile', (['expanded', 'tile_multiples'], {'name': 'scope'}), False, 'from tensorflow.python.ops import array_ops\n'), (1791, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""average_precision"""', '(predictions, labels, k)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1794, 'tensorflow.python.ops.nn.top_k', 'nn.top_k', (['predictions', 'k'], {}), False, 'from tensorflow.python.ops import nn\n'), (1795, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['predictions_idx'], {'name': '"""predictions_idx"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (1800, 'tensorflow.python.ops.array_ops.expand_dims', 'array_ops.expand_dims', (['predictions_idx', '(-1)'], {'name': '"""predictions_idx_per_k"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (1821, 'tensorflow.python.ops.math_ops.cumsum', 'math_ops.cumsum', (['relevant_per_k'], {'axis': '(-1)', 'name': '"""tp_per_k"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (1832, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['relevant_precision_per_k'], {'reduction_indices': '(-1,)', 'name': '"""precision_sum"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (1838, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['precision_sum', 'num_relevant_items'], {'name': 'scope'}), False, 'from tensorflow.python.ops import math_ops\n'), (1898, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1963, 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['ids_shape'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1965, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['ids_last_dim', '[1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1969, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['selected_id'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2027, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', '"""true_positives"""', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2031, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['tp'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2075, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2113, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""false_positives"""', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2119, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['fp'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2163, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2201, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""false_negatives"""', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2208, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['fn'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2252, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name', 'default_name', '(predictions_idx, labels)'], {}), False, 'from tensorflow.python.framework import ops\n'), (2368, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['normalizer', '(0.0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2369, 'tensorflow.python.ops.array_ops.zeros_like', 'array_ops.zeros_like', (['labels'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2479, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[update_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (2480, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['update_op'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2483, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'root_mean_squared_error'], {}), False, 'from tensorflow.python.framework import ops\n'), (2486, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (2542, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""covariance"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (2543, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2561, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['count', 'batch_count'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (2572, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['mean_prediction', 'delta_mean_prediction'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (2582, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['mean_label', 'delta_mean_label'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (2602, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['comoment', 'delta_comoment'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (2609, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'covariance'], {}), False, 'from tensorflow.python.framework import ops\n'), (2612, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (2665, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""pearson_r"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (2666, 'tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions', 'tensor_util.remove_squeezable_dimensions', (['predictions', 'labels'], {}), False, 'from tensorflow.contrib.framework import tensor_util\n'), (2687, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'pearson_r'], {}), False, 'from tensorflow.python.framework import ops\n'), (2690, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (2754, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'mean_distance'], {}), False, 'from tensorflow.python.framework import ops\n'), (2757, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (2806, 'tensorflow.python.ops.math_ops.less', 'math_ops.less', (['values', 'threshold'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2867, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""mean_iou"""', '[predictions, labels]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (2877, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['predictions'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2878, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2879, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['num_classes'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2897, 'tensorflow.contrib.metrics.python.ops.confusion_matrix_ops.confusion_matrix', 'confusion_matrix_ops.confusion_matrix', (['predictions', 'labels', 'num_classes'], {'weights': 'weights', 'dtype': 'cm_dtype'}), False, 'from tensorflow.contrib.metrics.python.ops import confusion_matrix_ops\n'), (2899, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['total_cm', 'current_cm'], {}), False, 'from tensorflow.python.ops import state_ops\n'), (2942, 'tensorflow.python.ops.math_ops.ceil', 'math_ops.ceil', (['(growth_factor ** exponent)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2987, 'tensorflow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', (['name', '"""streaming_concat"""', '[values]'], {}), False, 'from tensorflow.python.ops import variable_scope\n'), (3016, 'tensorflow.python.ops.array_ops.transpose', 'array_ops.transpose', (['valid_array', 'perm'], {'name': '"""concat"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (3041, 'tensorflow.python.ops.control_flow_ops.cond', 'control_flow_ops.cond', (['(new_size > array_size)', 'reallocate', 'control_flow_ops.no_op'], {}), False, 'from tensorflow.python.ops import control_flow_ops\n'), (72, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['mask'], {'dtype': 'dtypes.float32'}), False, 'from tensorflow.python.ops import array_ops\n'), (111, 'tensorflow.python.ops.array_ops.constant', 'array_ops.constant', (['(0.0)'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (112, 'tensorflow.python.ops.array_ops.constant', 'array_ops.constant', (['(0.0)'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (113, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['numerator', 'denominator'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (135, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['shape'], {'dtype': 'dtype'}), False, 'from tensorflow.python.ops import array_ops\n'), (219, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['labels', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (220, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['predictions', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (259, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['labels', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (260, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['predictions', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (298, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['labels', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (299, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['predictions', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (372, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (373, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['values', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (378, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['values'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (382, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[total_compute_op, count_compute_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (386, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'mean'], {}), False, 'from tensorflow.python.framework import ops\n'), (389, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (440, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (441, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['values', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (442, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['num_values', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (451, 'tensorflow.python.ops.math_ops.truediv', 'math_ops.truediv', (['total', 'non_zero_count'], {'name': 'name'}), False, 'from tensorflow.python.ops import math_ops\n'), (454, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[total_compute_op, count_compute_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (458, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'mean'], {}), False, 'from tensorflow.python.framework import ops\n'), (461, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (589, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[true_positives_update_op, false_positives_update_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (594, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'precision'], {}), False, 'from tensorflow.python.framework import ops\n'), (597, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (668, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[true_positives_update_op, false_negatives_update_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (673, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'recall'], {}), False, 'from tensorflow.python.framework import ops\n'), (676, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (740, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['predictions_2d'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (742, 'tensorflow.python.ops.array_ops.constant', 'array_ops.constant', (['thresholds'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (747, 'tensorflow.python.ops.array_ops.transpose', 'array_ops.transpose', (['predictions_2d'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (863, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['(tp + epsilon)', '(tp + fn + epsilon)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (882, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'auc'], {}), False, 'from tensorflow.python.framework import ops\n'), (885, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (963, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['tp', '(tp + fn + kepsilon)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (970, 'tensorflow.python.ops.math_ops.to_int64', 'math_ops.to_int64', (['indices_at_minval'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (971, 'tensorflow.python.ops.math_ops.cumsum', 'math_ops.cumsum', (['indices_at_minval'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (972, 'tensorflow.python.ops.math_ops.argmax', 'math_ops.argmax', (['indices_at_minval', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (973, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['tf_index', 'dtypes.int32'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (976, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['tn[tf_index]', '(tn[tf_index] + fp[tf_index] + kepsilon)', 'name'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (981, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[tp_update_op, fn_update_op, tn_update_op, fp_update_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (986, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'specificity'], {}), False, 'from tensorflow.python.framework import ops\n'), (989, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (1058, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['tn', '(tn + fp + kepsilon)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1060, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['tf_index', 'dtypes.int32'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1063, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['tp[tf_index]', '(tp[tf_index] + fn[tf_index] + kepsilon)', 'name'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1068, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[tp_update_op, fn_update_op, tn_update_op, fp_update_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (1073, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'sensitivity'], {}), False, 'from tensorflow.python.framework import ops\n'), (1076, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (1137, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['true_positives', '(epsilon + true_positives + false_positives)'], {'name': "('precision_' + name)"}), False, 'from tensorflow.python.ops import math_ops\n'), (1143, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[true_positives_compute_op, false_positives_compute_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (1148, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'precision'], {}), False, 'from tensorflow.python.framework import ops\n'), (1151, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (1206, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['true_positives', '(epsilon + true_positives + false_negatives)'], {'name': "('recall_' + name)"}), False, 'from tensorflow.python.ops import math_ops\n'), (1212, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[true_positives_compute_op, false_negatives_compute_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (1217, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'recall'], {}), False, 'from tensorflow.python.framework import ops\n'), (1220, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (1384, 'tensorflow.python.ops.math_ops.add', 'math_ops.add', (['tp', 'fn'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1386, 'tensorflow.python.ops.math_ops.add', 'math_ops.add', (['tp_update', 'fn_update'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1388, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'metric'], {}), False, 'from tensorflow.python.framework import ops\n'), (1390, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update'], {}), False, 'from tensorflow.python.framework import ops\n'), (1646, 'tensorflow.python.ops.math_ops.greater_equal', 'math_ops.greater_equal', (['rank', '(2)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1648, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[check_rank_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (1685, 'tensorflow.contrib.metrics.python.ops.set_ops.set_size', 'set_ops.set_size', (['labels'], {}), False, 'from tensorflow.contrib.metrics.python.ops import set_ops\n'), (1686, 'tensorflow.python.ops.math_ops.minimum', 'math_ops.minimum', (['labels_sizes', 'k'], {'name': 'scope'}), False, 'from tensorflow.python.ops import math_ops\n'), (1721, 'tensorflow.python.framework.ops.SparseTensor.from_value', 'ops.SparseTensor.from_value', (['tensor'], {}), False, 'from tensorflow.python.framework import ops\n'), (1732, 'tensorflow.python.ops.sparse_ops.sparse_reshape', 'sparse_ops.sparse_reshape', (['tensor'], {'shape': 'expanded_shape', 'name': '"""expand"""'}), False, 'from tensorflow.python.ops import sparse_ops\n'), (1736, 'tensorflow.python.ops.sparse_ops.sparse_concat', 'sparse_ops.sparse_concat', (['(dim - 1 if dim < 0 else dim)', '([expanded] * multiple)'], {'name': 'scope'}), False, 'from tensorflow.python.ops import sparse_ops\n'), (1744, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['tensor'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1823, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['relevant_per_k'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1825, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['tp_per_k'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1825, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['retrieved_per_k'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1828, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['relevant_per_k'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1903, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1904, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['average_precision', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1908, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""max"""', '(average_precision,)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1924, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['max_var', 'batch_max'], {'name': '"""update"""'}), False, 'from tensorflow.python.ops import state_ops\n'), (1925, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['None', '"""total"""', '(average_precision,)'], {}), False, 'from tensorflow.python.framework import ops\n'), (1928, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['average_precision'], {'name': '"""batch_total"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (1929, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['total_var', 'batch_total'], {'name': '"""update"""'}), False, 'from tensorflow.python.ops import state_ops\n'), (1936, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'mean_average_precision'], {}), False, 'from tensorflow.python.framework import ops\n'), (1938, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update'], {}), False, 'from tensorflow.python.framework import ops\n'), (1956, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['ids.values', 'selected_id'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2030, 'tensorflow.contrib.metrics.python.ops.set_ops.set_intersection', 'set_ops.set_intersection', (['predictions_idx', 'labels'], {}), False, 'from tensorflow.contrib.metrics.python.ops import set_ops\n'), (2033, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2034, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['tp', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2079, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['tp'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2082, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[]'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (2083, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['var', 'batch_total_tp'], {'name': '"""update"""'}), False, 'from tensorflow.python.ops import state_ops\n'), (2117, 'tensorflow.contrib.metrics.python.ops.set_ops.set_difference', 'set_ops.set_difference', (['predictions_idx', 'labels'], {'aminusb': '(True)'}), False, 'from tensorflow.contrib.metrics.python.ops import set_ops\n'), (2121, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2122, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['fp', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2167, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['fp'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2170, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[]'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (2171, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['var', 'batch_total_fp'], {'name': '"""update"""'}), False, 'from tensorflow.python.ops import state_ops\n'), (2205, 'tensorflow.contrib.metrics.python.ops.set_ops.set_difference', 'set_ops.set_difference', (['predictions_idx', 'labels'], {'aminusb': '(False)'}), False, 'from tensorflow.contrib.metrics.python.ops import set_ops\n'), (2210, 'tensorflow.python.ops.math_ops.to_double', 'math_ops.to_double', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2211, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['fn', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2256, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['fn'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2259, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[]'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (2260, 'tensorflow.python.ops.state_ops.assign_add', 'state_ops.assign_add', (['var', 'batch_total_fn'], {'name': '"""update"""'}), False, 'from tensorflow.python.ops import state_ops\n'), (2370, 'tensorflow.python.ops.math_ops.abs', 'math_ops.abs', (['(labels - predictions)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2567, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['weighted_predictions'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2579, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['weighted_labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2590, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['unweighted_batch_coresiduals'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2592, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['(unweighted_batch_coresiduals * weights)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2605, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[update_comoment]'], {}), False, 'from tensorflow.python.framework import ops\n'), (2680, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[update_cov, update_var_predictions, update_var_labels]'], {}), False, 'from tensorflow.python.framework import ops\n'), (2884, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['predictions', '[-1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2888, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['labels', '[-1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2914, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['cm_diag', 'denominator'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2915, 'tensorflow.python.ops.math_ops.reduce_mean', 'math_ops.reduce_mean', (['iou'], {'name': 'name'}), False, 'from tensorflow.python.ops import math_ops\n'), (2920, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'mean_iou'], {}), False, 'from tensorflow.python.framework import ops\n'), (2923, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (3018, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['values'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (3022, 'tensorflow.python.ops.math_ops.minimum', 'math_ops.minimum', (['values_size', '(max_size - size)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (3025, 'tensorflow.python.ops.array_ops.transpose', 'array_ops.transpose', (['values', 'perm'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (3029, 'tensorflow.python.ops.array_ops.pack', 'array_ops.pack', (['([next_size] + fixed_shape)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (3030, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['next_shape'], {'dtype': 'values.dtype'}), False, 'from tensorflow.python.ops import array_ops\n'), (3032, 'tensorflow.python.ops.state_ops.assign', 'state_ops.assign', (['array', 'new_value'], {'validate_shape': '(False)'}), False, 'from tensorflow.python.ops import state_ops\n'), (3040, 'tensorflow.python.ops.array_ops.shape_internal', 'array_ops.shape_internal', (['array'], {'optimize': '(False)'}), False, 'from tensorflow.python.ops import array_ops\n'), (3043, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[maybe_reallocate_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (3045, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[append_values_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (3049, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['metrics_collections', 'value'], {}), False, 'from tensorflow.python.framework import ops\n'), (3052, 'tensorflow.python.framework.ops.add_to_collections', 'ops.add_to_collections', (['updates_collections', 'update_op'], {}), False, 'from tensorflow.python.framework import ops\n'), (73, 'tensorflow.python.ops.math_ops.logical_not', 'math_ops.logical_not', (['mask'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (376, 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['values'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (449, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['count'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (583, 'tensorflow.python.ops.math_ops.greater', 'math_ops.greater', (['(true_positives + false_positives)', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (584, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['true_positives', '(true_positives + false_positives)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (662, 'tensorflow.python.ops.math_ops.greater', 'math_ops.greater', (['(true_positives + false_negatives)', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (663, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['true_positives', '(true_positives + false_negatives)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (865, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['fp', '(fp + tn + epsilon)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (869, 'tensorflow.python.ops.math_ops.div', 'math_ops.div', (['(tp + epsilon)', '(tp + fp + epsilon)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (872, 'tensorflow.python.ops.math_ops.mul', 'math_ops.mul', (['(x[:num_thresholds - 1] - x[1:])', '((y[:num_thresholds - 1] + y[1:]) / 2.0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (967, 'tensorflow.python.ops.math_ops.abs', 'math_ops.abs', (['(sensitivities - sensitivity)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (969, 'tensorflow.python.ops.math_ops.abs', 'math_ops.abs', (['(sensitivities - sensitivity)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1059, 'tensorflow.python.ops.math_ops.abs', 'math_ops.abs', (['(specificities - specificity)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1914, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[]'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (1923, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['broadcast_weights'], {'name': '"""batch_max"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (1927, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[]'], {'dtype': 'dtypes.float64'}), False, 'from tensorflow.python.ops import array_ops\n'), (2552, 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['labels'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2678, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['var_predictions'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2678, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['var_labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2894, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['weights', '[-1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2903, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['total_cm', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2904, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['total_cm', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2905, 'tensorflow.python.ops.array_ops.diag_part', 'array_ops.diag_part', (['total_cm'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2911, 'tensorflow.python.ops.math_ops.greater', 'math_ops.greater', (['denominator', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2913, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['denominator'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2940, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['required_size', 'dtypes.float32'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2941, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['growth_factor', 'dtypes.float32'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (3033, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[assign_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (3036, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[copy_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (3037, 'tensorflow.python.ops.control_flow_ops.no_op', 'control_flow_ops.no_op', ([], {}), False, 'from tensorflow.python.ops import control_flow_ops\n'), (1729, 'tensorflow.python.ops.array_ops.slice', 'array_ops.slice', (['tensor.shape', '[0]', 'expand_dims'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1730, 'tensorflow.python.ops.array_ops.slice', 'array_ops.slice', (['tensor.shape', 'expand_dims', '[-1]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1917, 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['average_precision'], {'name': '"""batch_max"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (1921, 'tensorflow.python.ops.array_ops.ones_like', 'array_ops.ones_like', (['average_precision'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (2683, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['update_var_predictions'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (2684, 'tensorflow.python.ops.math_ops.sqrt', 'math_ops.sqrt', (['update_var_labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (1725, 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['tensor.shape'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (859, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['fp'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (952, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['fp'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (1055, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['fp'], {}), False, 'from tensorflow.python.ops import array_ops\n')]
TianjieZhang1993/PINNs
9034ba7f4fef81c24954fa3cbf08a2d4a7fee85a
""" @author: Maziar Raissi """ import sys sys.path.insert(0, '../../Utilities/') import tensorflow as tf import numpy as np import time import scipy.io np.random.seed(1234) tf.set_random_seed(1234) class PhysicsInformedNN: # Initialize the class def __init__(self, x0, u0, x1, u1, layers, dt, lb, ub, q): self.lb = lb self.ub = ub self.x0 = x0 self.x1 = x1 self.u0 = u0 self.u1 = u1 self.layers = layers self.dt = dt self.q = max(q,1) # Initialize NN self.weights, self.biases = self.initialize_NN(layers) # Initialize parameters self.lambda_1 = tf.Variable([0.0], dtype=tf.float32) self.lambda_2 = tf.Variable([-6.0], dtype=tf.float32) # Load IRK weights tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2)) weights = np.reshape(tmp[0:q**2+q], (q+1,q)) self.IRK_alpha = weights[0:-1,:] self.IRK_beta = weights[-1:,:] self.IRK_times = tmp[q**2+q:] # tf placeholders and graph self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) self.x0_tf = tf.placeholder(tf.float32, shape=(None, self.x0.shape[1])) self.x1_tf = tf.placeholder(tf.float32, shape=(None, self.x1.shape[1])) self.u0_tf = tf.placeholder(tf.float32, shape=(None, self.u0.shape[1])) self.u1_tf = tf.placeholder(tf.float32, shape=(None, self.u1.shape[1])) self.dummy_x0_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.dummy_x1_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.U0_pred = self.net_U0(self.x0_tf) # N0 x q self.U1_pred = self.net_U1(self.x1_tf) # N1 x q self.loss = tf.reduce_sum(tf.square(self.u0_tf - self.U0_pred)) + \ tf.reduce_sum(tf.square(self.u1_tf - self.U1_pred)) self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, method = 'L-BFGS-B', options = {'maxiter': 50000, 'maxfun': 50000, 'maxcor': 50, 'maxls': 50, 'ftol' : 1.0 * np.finfo(float).eps}) self.optimizer_Adam = tf.train.AdamOptimizer() self.train_op_Adam = self.optimizer_Adam.minimize(self.loss) init = tf.global_variables_initializer() self.sess.run(init) def initialize_NN(self, layers): weights = [] biases = [] num_layers = len(layers) for l in range(0,num_layers-1): W = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) weights.append(W) biases.append(b) return weights, biases def xavier_init(self, size): in_dim = size[0] out_dim = size[1] xavier_stddev = np.sqrt(2/(in_dim + out_dim)) return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32) def neural_net(self, X, weights, biases): num_layers = len(weights) + 1 H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0 for l in range(0,num_layers-2): W = weights[l] b = biases[l] H = tf.tanh(tf.add(tf.matmul(H, W), b)) W = weights[-1] b = biases[-1] Y = tf.add(tf.matmul(H, W), b) return Y def fwd_gradients_0(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0] return tf.gradients(g, self.dummy_x0_tf)[0] def fwd_gradients_1(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0] return tf.gradients(g, self.dummy_x1_tf)[0] def net_U0(self, x): lambda_1 = self.lambda_1 lambda_2 = tf.exp(self.lambda_2) U = self.neural_net(x, self.weights, self.biases) U_x = self.fwd_gradients_0(U, x) U_xx = self.fwd_gradients_0(U_x, x) F = -lambda_1*U*U_x + lambda_2*U_xx U0 = U - self.dt*tf.matmul(F, self.IRK_alpha.T) return U0 def net_U1(self, x): lambda_1 = self.lambda_1 lambda_2 = tf.exp(self.lambda_2) U = self.neural_net(x, self.weights, self.biases) U_x = self.fwd_gradients_1(U, x) U_xx = self.fwd_gradients_1(U_x, x) F = -lambda_1*U*U_x + lambda_2*U_xx U1 = U + self.dt*tf.matmul(F, (self.IRK_beta - self.IRK_alpha).T) return U1 def callback(self, loss): print('Loss:', loss) def train(self, nIter): tf_dict = {self.x0_tf: self.x0, self.u0_tf: self.u0, self.x1_tf: self.x1, self.u1_tf: self.u1, self.dummy_x0_tf: np.ones((self.x0.shape[0], self.q)), self.dummy_x1_tf: np.ones((self.x1.shape[0], self.q))} start_time = time.time() for it in range(nIter): self.sess.run(self.train_op_Adam, tf_dict) # Print if it % 10 == 0: elapsed = time.time() - start_time loss_value = self.sess.run(self.loss, tf_dict) lambda_1_value = self.sess.run(self.lambda_1) lambda_2_value = np.exp(self.sess.run(self.lambda_2)) print('It: %d, Loss: %.3e, l1: %.3f, l2: %.5f, Time: %.2f' % (it, loss_value, lambda_1_value, lambda_2_value, elapsed)) start_time = time.time() self.optimizer.minimize(self.sess, feed_dict = tf_dict, fetches = [self.loss], loss_callback = self.callback) def predict(self, x_star): U0_star = self.sess.run(self.U0_pred, {self.x0_tf: x_star, self.dummy_x0_tf: np.ones((x_star.shape[0], self.q))}) U1_star = self.sess.run(self.U1_pred, {self.x1_tf: x_star, self.dummy_x1_tf: np.ones((x_star.shape[0], self.q))}) return U0_star, U1_star def main_loop(skip, noise, num_layers, num_neurons): N0 = 199 N1 = 201 data = scipy.io.loadmat('../Data/burgers_shock.mat') t_star = data['t'].flatten()[:,None] x_star = data['x'].flatten()[:,None] Exact = np.real(data['usol']) idx_t = 10 idx_x = np.random.choice(Exact.shape[0], N0, replace=False) x0 = x_star[idx_x,:] u0 = Exact[idx_x,idx_t][:,None] u0 = u0 + noise*np.std(u0)*np.random.randn(u0.shape[0], u0.shape[1]) idx_x = np.random.choice(Exact.shape[0], N1, replace=False) x1 = x_star[idx_x,:] u1 = Exact[idx_x,idx_t + skip][:,None] u1 = u1 + noise*np.std(u1)*np.random.randn(u1.shape[0], u1.shape[1]) dt = np.asscalar(t_star[idx_t+skip] - t_star[idx_t]) q = int(np.ceil(0.5*np.log(np.finfo(float).eps)/np.log(dt))) layers = np.concatenate([[1], num_neurons*np.ones(num_layers), [q]]).astype(int).tolist() # Doman bounds lb = x_star.min(0) ub = x_star.max(0) model = PhysicsInformedNN(x0, u0, x1, u1, layers, dt, lb, ub, q) model.train(nIter = 50000) U0_pred, U1_pred = model.predict(x_star) lambda_1_value = model.sess.run(model.lambda_1) lambda_2_value = np.exp(model.sess.run(model.lambda_2)) nu = 0.01/np.pi error_lambda_1 = np.abs(lambda_1_value - 1.0)/1.0 *100 error_lambda_2 = np.abs(lambda_2_value - nu)/nu * 100 print('Error lambda_1: %f%%' % (error_lambda_1)) print('Error lambda_2: %f%%' % (error_lambda_2)) return error_lambda_1, error_lambda_2 if __name__ == "__main__": skip = [20, 40, 60, 80] noise = [0.0, 0.01, 0.05, 0.1] num_layers = [1,2,3,4] num_neurons = [10,25,50] error_lambda_1_table_1 = np.zeros((len(skip), len(noise))) error_lambda_2_table_1 = np.zeros((len(skip), len(noise))) error_lambda_1_table_2 = np.zeros((len(num_layers), len(num_neurons))) error_lambda_2_table_2 = np.zeros((len(num_layers), len(num_neurons))) for i in range(len(skip)): for j in range(len(noise)): error_lambda_1_table_1[i,j], error_lambda_2_table_1[i,j] = main_loop(skip[i], noise[j], num_layers[-1], num_neurons[-1]) for i in range(len(num_layers)): for j in range(len(num_neurons)): error_lambda_1_table_2[i,j], error_lambda_2_table_2[i,j] = main_loop(skip[-1], noise[0], num_layers[i], num_neurons[j]) np.savetxt('./tables/error_lambda_1_table_1.csv', error_lambda_1_table_1, delimiter=' & ', fmt='$%2.3f$', newline=' \\\\\n') np.savetxt('./tables/error_lambda_2_table_1.csv', error_lambda_2_table_1, delimiter=' & ', fmt='$%2.3f$', newline=' \\\\\n') np.savetxt('./tables/error_lambda_1_table_2.csv', error_lambda_1_table_2, delimiter=' & ', fmt='$%2.3f$', newline=' \\\\\n') np.savetxt('./tables/error_lambda_2_table_2.csv', error_lambda_2_table_2, delimiter=' & ', fmt='$%2.3f$', newline=' \\\\\n')
[ "numpy.sqrt", "tensorflow.zeros", "numpy.random.randn", "tensorflow.train.AdamOptimizer", "numpy.asscalar", "tensorflow.Variable", "numpy.reshape", "tensorflow.gradients", "numpy.finfo", "tensorflow.ConfigProto", "numpy.real", "numpy.std", "tensorflow.square", "tensorflow.matmul", "numpy.log", "tensorflow.truncated_normal", "numpy.random.choice", "tensorflow.placeholder", "tensorflow.exp", "tensorflow.global_variables_initializer", "tensorflow.set_random_seed", "numpy.savetxt", "numpy.abs", "numpy.random.seed", "numpy.ones", "numpy.loadtxt" ]
appendix/discrete_time_identification (Burgers)/Burgers_systematic.py
[(6, 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../Utilities/"""'], {}), False, 'import sys\n'), (13, 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), True, 'import numpy as np\n'), (14, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1234)'], {}), True, 'import tensorflow as tf\n'), (182, 'numpy.real', 'np.real', (["data['usol']"], {}), True, 'import numpy as np\n'), (186, 'numpy.random.choice', 'np.random.choice', (['Exact.shape[0]', 'N0'], {'replace': '(False)'}), True, 'import numpy as np\n'), (191, 'numpy.random.choice', 'np.random.choice', (['Exact.shape[0]', 'N1'], {'replace': '(False)'}), True, 'import numpy as np\n'), (196, 'numpy.asscalar', 'np.asscalar', (['(t_star[idx_t + skip] - t_star[idx_t])'], {}), True, 'import numpy as np\n'), (246, 'numpy.savetxt', 'np.savetxt', (['"""./tables/error_lambda_1_table_1.csv"""', 'error_lambda_1_table_1'], {'delimiter': '""" & """', 'fmt': '"""$%2.3f$"""', 'newline': '""" \\\\\\\\\n"""'}), True, 'import numpy as np\n'), (247, 'numpy.savetxt', 'np.savetxt', (['"""./tables/error_lambda_2_table_1.csv"""', 'error_lambda_2_table_1'], {'delimiter': '""" & """', 'fmt': '"""$%2.3f$"""', 'newline': '""" \\\\\\\\\n"""'}), True, 'import numpy as np\n'), (249, 'numpy.savetxt', 'np.savetxt', (['"""./tables/error_lambda_1_table_2.csv"""', 'error_lambda_1_table_2'], {'delimiter': '""" & """', 'fmt': '"""$%2.3f$"""', 'newline': '""" \\\\\\\\\n"""'}), True, 'import numpy as np\n'), (250, 'numpy.savetxt', 'np.savetxt', (['"""./tables/error_lambda_2_table_2.csv"""', 'error_lambda_2_table_2'], {'delimiter': '""" & """', 'fmt': '"""$%2.3f$"""', 'newline': '""" \\\\\\\\\n"""'}), True, 'import numpy as np\n'), (38, 'tensorflow.Variable', 'tf.Variable', (['[0.0]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.Variable', 'tf.Variable', (['[-6.0]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (43, 'numpy.reshape', 'np.reshape', (['tmp[0:q ** 2 + q]', '(q + 1, q)'], {}), True, 'import numpy as np\n'), (52, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.x0.shape[1])'}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.x1.shape[1])'}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.u0.shape[1])'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.u1.shape[1])'}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.q)'}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, self.q)'}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (93, 'numpy.sqrt', 'np.sqrt', (['(2 / (in_dim + out_dim))'], {}), True, 'import numpy as np\n'), (119, 'tensorflow.exp', 'tf.exp', (['self.lambda_2'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.exp', 'tf.exp', (['self.lambda_2'], {}), True, 'import tensorflow as tf\n'), (146, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (42, 'numpy.loadtxt', 'np.loadtxt', (["('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % q)"], {'ndmin': '(2)'}), True, 'import numpy as np\n'), (94, 'tensorflow.truncated_normal', 'tf.truncated_normal', (['[in_dim, out_dim]'], {'stddev': 'xavier_stddev'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.matmul', 'tf.matmul', (['H', 'W'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.gradients', 'tf.gradients', (['U', 'x'], {'grad_ys': 'self.dummy_x0_tf'}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.gradients', 'tf.gradients', (['g', 'self.dummy_x0_tf'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.gradients', 'tf.gradients', (['U', 'x'], {'grad_ys': 'self.dummy_x1_tf'}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.gradients', 'tf.gradients', (['g', 'self.dummy_x1_tf'], {}), True, 'import tensorflow as tf\n'), (143, 'numpy.ones', 'np.ones', (['(self.x0.shape[0], self.q)'], {}), True, 'import numpy as np\n'), (144, 'numpy.ones', 'np.ones', (['(self.x1.shape[0], self.q)'], {}), True, 'import numpy as np\n'), (189, 'numpy.random.randn', 'np.random.randn', (['u0.shape[0]', 'u0.shape[1]'], {}), True, 'import numpy as np\n'), (194, 'numpy.random.randn', 'np.random.randn', (['u1.shape[0]', 'u1.shape[1]'], {}), True, 'import numpy as np\n'), (214, 'numpy.abs', 'np.abs', (['(lambda_1_value - 1.0)'], {}), True, 'import numpy as np\n'), (215, 'numpy.abs', 'np.abs', (['(lambda_2_value - nu)'], {}), True, 'import numpy as np\n'), (49, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': '(True)'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.square', 'tf.square', (['(self.u0_tf - self.U0_pred)'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.square', 'tf.square', (['(self.u1_tf - self.U1_pred)'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.zeros', 'tf.zeros', (['[1, layers[l + 1]]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.matmul', 'tf.matmul', (['F', 'self.IRK_alpha.T'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.matmul', 'tf.matmul', (['F', '(self.IRK_beta - self.IRK_alpha).T'], {}), True, 'import tensorflow as tf\n'), (158, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (167, 'numpy.ones', 'np.ones', (['(x_star.shape[0], self.q)'], {}), True, 'import numpy as np\n'), (168, 'numpy.ones', 'np.ones', (['(x_star.shape[0], self.q)'], {}), True, 'import numpy as np\n'), (189, 'numpy.std', 'np.std', (['u0'], {}), True, 'import numpy as np\n'), (194, 'numpy.std', 'np.std', (['u1'], {}), True, 'import numpy as np\n'), (197, 'numpy.log', 'np.log', (['dt'], {}), True, 'import numpy as np\n'), (103, 'tensorflow.matmul', 'tf.matmul', (['H', 'W'], {}), True, 'import tensorflow as tf\n'), (152, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (71, 'numpy.finfo', 'np.finfo', (['float'], {}), True, 'import numpy as np\n'), (197, 'numpy.finfo', 'np.finfo', (['float'], {}), True, 'import numpy as np\n'), (199, 'numpy.ones', 'np.ones', (['num_layers'], {}), True, 'import numpy as np\n')]
ash-vs/tensorflow
303dc341a6300a4a2eee820679bca30547426aa6
# Copyright 2015 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. """Base Estimator class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import os import tempfile import time import six from tensorflow.contrib import framework as contrib_framework from tensorflow.contrib import layers from tensorflow.contrib import losses from tensorflow.contrib.learn.python.learn.estimators import _sklearn as sklearn from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.estimators import tensor_signature from tensorflow.contrib.learn.python.learn.graph_actions import evaluate from tensorflow.contrib.learn.python.learn.graph_actions import infer from tensorflow.contrib.learn.python.learn.graph_actions import train from tensorflow.contrib.learn.python.learn.io import data_feeder from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import device_setter from tensorflow.python.training import saver # Default metrics for evaluation. _EVAL_METRICS = { 'regression': { 'mean_squared_error': losses.sum_of_squares, }, 'classification': { 'logistic': losses.sigmoid_cross_entropy, },} class ModeKeys(object): """Standard names for model modes. The following standard keys are defined: * `TRAIN`: training mode. * `EVAL`: evaluation mode. * `INFER`: inference mode. """ TRAIN = 'train' EVAL = 'eval' INFER = 'infer' def _get_input_fn(x, y, batch_size): # TODO(ipoloshukin): Remove this when refactor of data_feeder is done if hasattr(x, 'create_graph') and hasattr(y, 'create_graph'): def input_fn(): return x.create_graph(), y.create_graph() return input_fn, None df = data_feeder.setup_train_data_feeder(x, y, n_classes=None, batch_size=batch_size) return df.input_builder, df.get_feed_dict_fn() def _get_predict_input_fn(x, batch_size): # TODO(ipoloshukin): Remove this when refactor of data_feeder is done if hasattr(x, 'create_graph'): def input_fn(): return x.create_graph() return input_fn, None df = data_feeder.setup_train_data_feeder(x, None, n_classes=None, batch_size=batch_size) return df.input_builder, df.get_feed_dict_fn() class BaseEstimator(sklearn.BaseEstimator): """Abstract BaseEstimator class to train and evaluate TensorFlow models. Concrete implementation of this class should provide following functions: * _get_train_ops * _get_eval_ops * _get_predict_ops It may override _get_default_metric_functions. `Estimator` implemented below is a good example of how to use this class. Parameters: model_dir: Directory to save model parameters, graph and etc. """ __metaclass__ = abc.ABCMeta # TODO(wicke): Remove this once launcher takes over config functionality _Config = run_config.RunConfig # pylint: disable=invalid-name def __init__(self, model_dir=None): # Model directory. self._model_dir = model_dir if self._model_dir is None: self._model_dir = tempfile.mkdtemp() logging.info('Using temporary folder as model directory: %s', self._model_dir) # Create a run configuration self._config = BaseEstimator._Config() # Set device function depending if there are replicas or not. if self._config.num_ps_replicas > 0: ps_ops = ['Variable', 'AutoReloadVariable'] self._device_fn = device_setter.replica_device_setter( ps_tasks=self._config.num_ps_replicas, merge_devices=False, ps_ops=ps_ops) else: self._device_fn = None # Features and targets TensorSingature objects. self._features_info = None self._targets_info = None @abc.abstractproperty def _get_train_ops(self, features, targets): """Method that builds model graph and returns trainer ops. Expected to be overriden by sub-classes that require custom support. Args: features: `Tensor` or `dict` of `Tensor` objects. targets: `Tensor` or `dict` of `Tensor` objects. Returns: Tuple of train `Operation` and loss `Tensor`. """ pass @abc.abstractproperty def _get_predict_ops(self, features): """Method that builds model graph and returns prediction ops. Args: features: `Tensor` or `dict` of `Tensor` objects. Returns: predictions: `Tensor` or `dict` of `Tensor` objects. """ pass def _get_eval_ops(self, features, targets, metrics): """Method that builds model graph and returns evaluation ops. Args: features: `Tensor` or `dict` of `Tensor` objects. targets: `Tensor` or `dict` of `Tensor` objects. metrics: `dict` of functions that take predictions and targets. Returns: metrics: `dict` of `Tensor` objects. """ predictions = self._get_predict_ops(features) result = {} for name, metric in six.iteritems(metrics): result[name] = metric(predictions, targets) return result def _get_feature_ops_from_example(self, examples_batch): """Method that returns features given the batch of examples. This method will be used to export model into a server. Args: examples_batch: batch of tf.Example Returns: features: `Tensor` or `dict` of `Tensor` objects. """ raise NotImplementedError('_get_feature_ops_from_example not implemented ' 'in BaseEstimator') def _get_default_metric_functions(self): """Method that provides default metric operations. This functions is intented to be overridden by sub-classes. Returns: `dict` of functions that take predictions and targets `Tensor` objects and return `Tensor`. """ return {} def fit(self, x, y, steps, batch_size=32, monitor=None): """Trains a model given training data X and y. Args: x: matrix or tensor of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. y: vector or matrix [n_samples] or [n_samples, n_outputs]. Can be iterator that returns array of targets. The training target values (class labels in classification, real numbers in regression). steps: number of steps to train model for. batch_size: minibatch size to use on the input, defaults to 32. monitor: monitor object to print training progress and invoke early stopping. Returns: Returns self. """ input_fn, feed_fn = _get_input_fn(x, y, batch_size) return self._train_model(input_fn=input_fn, feed_fn=feed_fn, steps=steps, monitor=monitor) def train(self, input_fn, steps, monitor=None): """Trains a model given input builder function. Args: input_fn: Input builder function, returns tuple of dicts or dict and Tensor. steps: number of steps to train model for. monitor: monitor object to print training progress and invoke early stopping. Returns: Returns self. """ return self._train_model(input_fn=input_fn, steps=steps, monitor=monitor) def partial_fit(self, x, y, steps=1, batch_size=32, monitor=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different or the same chunks of the dataset. This either can implement iterative training or out-of-core/online training. This is especially useful when the whole dataset is too big to fit in memory at the same time. Or when model is taking long time to converge, and you want to split up training into subparts. Args: x: matrix or tensor of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. y: vector or matrix [n_samples] or [n_samples, n_outputs]. Can be iterator that returns array of targets. The training target values (class label in classification, real numbers in regression). steps: number of steps to train model for. batch_size: minibatch size to use on the input, defaults to 32. monitor: Monitor object to print training progress and invoke early stopping. Returns: Returns self. """ input_fn, feed_fn = _get_input_fn(x, y, batch_size) return self._train_model(input_fn=input_fn, feed_fn=feed_fn, steps=steps, monitor=monitor) def evaluate(self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=32, steps=100, metrics=None): """Evaluates given model with provided evaluation data. Args: x: features. y: targets. input_fn: Input function. If set, x and y must be None. feed_fn: Function creating a feed dict every time it is called. Called once per iteration. batch_size: minibatch size to use on the input, defaults to 32. Ignored if input_fn is set. steps: Number of steps to evalute for. metrics: Dict of metric ops to run. Returns: Returns self. Raises: ValueError: If x or y are not None while input_fn or feed_fn is not None. """ if (x is not None or y is not None) and input_fn is not None: raise ValueError('Either x and y or input_fn must be None.') if input_fn is None: assert x is not None input_fn, feed_fn = _get_input_fn(x, y, batch_size) return self._evaluate_model(input_fn=input_fn, feed_fn=feed_fn, steps=steps, metrics=metrics) def predict(self, x, axis=None, batch_size=None): """Returns predictions for given features. Args: x: features. axis: Axis on which to argmax. (for classification). batch_size: Override default batch size. Returns: Numpy array of predicted classes or regression values. """ return self._infer_model(x=x, batch_size=batch_size, axis=axis) def predict_proba(self, x, batch_size=None): """Returns prediction probabilities for given features (classification). Args: x: features. batch_size: OVerride default batch size. Returns: Numpy array of predicted probabilities. """ return self._infer_model(x=x, batch_size=batch_size, proba=True) def _check_inputs(self, features, targets): if self._features_info is not None: if not tensor_signature.tensors_compatible(features, self._features_info): raise ValueError('Features are incompatible with given information. ' 'Given features: %s, required signatures: %s.' % (str(features), str(self._features_info))) else: self._features_info = tensor_signature.create_signatures(features) if self._targets_info is not None: if not tensor_signature.tensors_compatible(targets, self._targets_info): raise ValueError('Targets are incompatible with given information. ' 'Given targets: %s, required signatures: %s.' % (str(targets), str(self._targets_info))) else: self._targets_info = tensor_signature.create_signatures(targets) def _train_model(self, input_fn, steps, feed_fn=None, device_fn=None, monitor=None, log_every_steps=100, fail_on_nan_loss=True): if self._config.execution_mode not in ('all', 'train'): return # Stagger startup of worker sessions based on task id. sleep_secs = min(self._config.training_worker_max_startup_secs, self._config.task * self._config.training_worker_session_startup_stagger_secs) if sleep_secs: logging.info('Waiting %d secs before starting task %d.', sleep_secs, self._config.task) time.sleep(sleep_secs) # Device allocation device_fn = device_fn or self._device_fn with ops.Graph().as_default() as g, g.device(device_fn): random_seed.set_random_seed(self._config.tf_random_seed) global_step = contrib_framework.create_global_step(g) features, targets = input_fn() self._check_inputs(features, targets) train_op, loss_op = self._get_train_ops(features, targets) return train( graph=g, output_dir=self._model_dir, train_op=train_op, loss_op=loss_op, global_step_tensor=global_step, log_every_steps=log_every_steps, supervisor_is_chief=(self._config.task == 0), supervisor_master=self._config.master, feed_fn=feed_fn, max_steps=steps, fail_on_nan_loss=fail_on_nan_loss) def _evaluate_model(self, input_fn, steps, feed_fn=None, metrics=None): if self._config.execution_mode not in ('all', 'evaluate', 'eval_evalset'): return checkpoint_path = saver.latest_checkpoint(self._model_dir) eval_dir = os.path.join(self._model_dir, 'eval') with ops.Graph().as_default() as g: random_seed.set_random_seed(self._config.tf_random_seed) global_step = contrib_framework.create_global_step(g) features, targets = input_fn() self._check_inputs(features, targets) eval_dict = self._get_eval_ops(features, targets, metrics or self._get_default_metric_functions()) eval_results, _ = evaluate( graph=g, output_dir=eval_dir, checkpoint_path=checkpoint_path, eval_dict=eval_dict, global_step_tensor=global_step, supervisor_master=self._config.master, feed_fn=feed_fn, max_steps=steps) return eval_results def _infer_model(self, x, batch_size=None, axis=None, proba=False): # Converts inputs into tf.DataFrame / tf.Series. batch_size = -1 if batch_size is None else batch_size input_fn, feed_fn = _get_predict_input_fn(x, batch_size) checkpoint_path = saver.latest_checkpoint(self._model_dir) with ops.Graph().as_default() as g: random_seed.set_random_seed(self._config.tf_random_seed) contrib_framework.create_global_step(g) features, _ = input_fn() feed_dict = feed_fn() if feed_fn is not None else None predictions = self._get_predict_ops(features) if not isinstance(predictions, dict): predictions = {'predictions': predictions} # TODO(ipolosukhin): Support batching return infer(checkpoint_path, predictions, feed_dict=feed_dict) class Estimator(BaseEstimator): """Estimator class is the basic TensorFlow model trainer/evaluator. Parameters: model_fn: Model function, takes features and targets tensors or dicts of tensors and returns predictions and loss tensors. E.g. `(features, targets) -> (predictions, loss)`. model_dir: Directory to save model parameters, graph and etc. classification: boolean, true if classification problem. learning_rate: learning rate for the model. optimizer: optimizer for the model, can be: string: name of optimizer, like 'SGD', 'Adam', 'Adagrad', 'Ftl', 'Momentum', 'RMSProp', 'Momentum'). Full list in contrib/layers/optimizers.py class: sub-class of Optimizer (like tf.train.GradientDescentOptimizer). clip_gradients: clip_norm value for call to `clip_by_global_norm`. None denotes no gradient clipping. """ def __init__(self, model_fn=None, model_dir=None, classification=True, learning_rate=0.01, optimizer='SGD', clip_gradients=None): super(Estimator, self).__init__(model_dir=model_dir) self._model_fn = model_fn self._classification = classification if isinstance(optimizer, six.string_types): if optimizer not in layers.OPTIMIZER_CLS_NAMES: raise ValueError( 'Optimizer name should be one of [%s], you provided %s.' % (', '.join(layers.OPTIMIZER_CLS_NAMES), optimizer)) self.optimizer = optimizer self.learning_rate = learning_rate self.clip_gradients = clip_gradients def _get_train_ops(self, features, targets): """Method that builds model graph and returns trainer ops. Expected to be overriden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. targets: `Tensor` or `dict` of `Tensor` objects. Returns: Tuple of train `Operation` and loss `Tensor`. """ _, loss = self._model_fn(features, targets, ModeKeys.TRAIN) train_op = layers.optimize_loss( loss, contrib_framework.get_global_step(), learning_rate=self.learning_rate, optimizer=self.optimizer, clip_gradients=self.clip_gradients) return train_op, loss def _get_eval_ops(self, features, targets, metrics): """Method that builds model graph and returns evaluation ops. Expected to be overriden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. targets: `Tensor` or `dict` of `Tensor` objects. metrics: `dict` of functions that take predictions and targets. Returns: metrics: `dict` of `Tensor` objects. """ predictions, loss = self._model_fn(features, targets, ModeKeys.EVAL) result = {'loss': loss} if isinstance(targets, dict) and len(targets) == 1: # Unpack single target into just tensor. targets = targets[targets.keys()[0]] for name, metric in six.iteritems(metrics): # TODO(ipolosukhin): Add support for multi-head metrics. result[name] = metric(predictions, targets) return result def _get_predict_ops(self, features): """Method that builds model graph and returns prediction ops. Expected to be overriden by sub-classes that require custom support. This implementation uses `model_fn` passed as parameter to constructor to build model. Args: features: `Tensor` or `dict` of `Tensor` objects. Returns: predictions: `Tensor` or `dict` of `Tensor` objects. """ targets = tensor_signature.create_placeholders_from_signatures( self._targets_info) predictions, _ = self._model_fn(features, targets, ModeKeys.INFER) return predictions def _get_default_metric_functions(self): """Method that provides default metric operations. Returns: a dictionary of metric operations. """ return _EVAL_METRICS[ 'classification' if self._classification else 'regression'] def _get_feature_ops_from_example(self, examples_batch): """Unimplemented. TODO(vihanjain): We need a way to parse tf.Example into features. Args: examples_batch: batch of tf.Example Returns: features: `Tensor` or `dict` of `Tensor` objects. Raises: Exception: Unimplemented """ raise NotImplementedError('_get_feature_ops_from_example not yet ' 'implemented')
[ "tensorflow.python.training.saver.latest_checkpoint", "tensorflow.contrib.learn.python.learn.estimators.tensor_signature.tensors_compatible", "tensorflow.python.training.device_setter.replica_device_setter", "tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_signatures", "tensorflow.contrib.learn.python.learn.graph_actions.infer", "tensorflow.python.platform.tf_logging.info", "tensorflow.contrib.learn.python.learn.graph_actions.evaluate", "tensorflow.contrib.framework.get_global_step", "tensorflow.python.framework.ops.Graph", "tensorflow.contrib.learn.python.learn.io.data_feeder.setup_train_data_feeder", "tensorflow.contrib.framework.create_global_step", "tensorflow.contrib.learn.python.learn.graph_actions.train", "tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_placeholders_from_signatures", "tensorflow.python.framework.random_seed.set_random_seed" ]
tensorflow/contrib/learn/python/learn/estimators/estimator.py
[(77, 'tensorflow.contrib.learn.python.learn.io.data_feeder.setup_train_data_feeder', 'data_feeder.setup_train_data_feeder', (['x', 'y'], {'n_classes': 'None', 'batch_size': 'batch_size'}), False, 'from tensorflow.contrib.learn.python.learn.io import data_feeder\n'), (90, 'tensorflow.contrib.learn.python.learn.io.data_feeder.setup_train_data_feeder', 'data_feeder.setup_train_data_feeder', (['x', 'None'], {'n_classes': 'None', 'batch_size': 'batch_size'}), False, 'from tensorflow.contrib.learn.python.learn.io import data_feeder\n'), (179, 'six.iteritems', 'six.iteritems', (['metrics'], {}), False, 'import six\n'), (394, 'tensorflow.python.training.saver.latest_checkpoint', 'saver.latest_checkpoint', (['self._model_dir'], {}), False, 'from tensorflow.python.training import saver\n'), (395, 'os.path.join', 'os.path.join', (['self._model_dir', '"""eval"""'], {}), False, 'import os\n'), (419, 'tensorflow.python.training.saver.latest_checkpoint', 'saver.latest_checkpoint', (['self._model_dir'], {}), False, 'from tensorflow.python.training import saver\n'), (515, 'six.iteritems', 'six.iteritems', (['metrics'], {}), False, 'import six\n'), (533, 'tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_placeholders_from_signatures', 'tensor_signature.create_placeholders_from_signatures', (['self._targets_info'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import tensor_signature\n'), (119, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (120, 'tensorflow.python.platform.tf_logging.info', 'logging.info', (['"""Using temporary folder as model directory: %s"""', 'self._model_dir'], {}), True, 'from tensorflow.python.platform import tf_logging as logging\n'), (129, 'tensorflow.python.training.device_setter.replica_device_setter', 'device_setter.replica_device_setter', ([], {'ps_tasks': 'self._config.num_ps_replicas', 'merge_devices': '(False)', 'ps_ops': 'ps_ops'}), False, 'from tensorflow.python.training import device_setter\n'), (339, 'tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_signatures', 'tensor_signature.create_signatures', (['features'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import tensor_signature\n'), (346, 'tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_signatures', 'tensor_signature.create_signatures', (['targets'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import tensor_signature\n'), (364, 'tensorflow.python.platform.tf_logging.info', 'logging.info', (['"""Waiting %d secs before starting task %d."""', 'sleep_secs', 'self._config.task'], {}), True, 'from tensorflow.python.platform import tf_logging as logging\n'), (366, 'time.sleep', 'time.sleep', (['sleep_secs'], {}), False, 'import time\n'), (372, 'tensorflow.python.framework.random_seed.set_random_seed', 'random_seed.set_random_seed', (['self._config.tf_random_seed'], {}), False, 'from tensorflow.python.framework import random_seed\n'), (373, 'tensorflow.contrib.framework.create_global_step', 'contrib_framework.create_global_step', (['g'], {}), True, 'from tensorflow.contrib import framework as contrib_framework\n'), (377, 'tensorflow.contrib.learn.python.learn.graph_actions.train', 'train', ([], {'graph': 'g', 'output_dir': 'self._model_dir', 'train_op': 'train_op', 'loss_op': 'loss_op', 'global_step_tensor': 'global_step', 'log_every_steps': 'log_every_steps', 'supervisor_is_chief': '(self._config.task == 0)', 'supervisor_master': 'self._config.master', 'feed_fn': 'feed_fn', 'max_steps': 'steps', 'fail_on_nan_loss': 'fail_on_nan_loss'}), False, 'from tensorflow.contrib.learn.python.learn.graph_actions import train\n'), (397, 'tensorflow.python.framework.random_seed.set_random_seed', 'random_seed.set_random_seed', (['self._config.tf_random_seed'], {}), False, 'from tensorflow.python.framework import random_seed\n'), (398, 'tensorflow.contrib.framework.create_global_step', 'contrib_framework.create_global_step', (['g'], {}), True, 'from tensorflow.contrib import framework as contrib_framework\n'), (403, 'tensorflow.contrib.learn.python.learn.graph_actions.evaluate', 'evaluate', ([], {'graph': 'g', 'output_dir': 'eval_dir', 'checkpoint_path': 'checkpoint_path', 'eval_dict': 'eval_dict', 'global_step_tensor': 'global_step', 'supervisor_master': 'self._config.master', 'feed_fn': 'feed_fn', 'max_steps': 'steps'}), False, 'from tensorflow.contrib.learn.python.learn.graph_actions import evaluate\n'), (421, 'tensorflow.python.framework.random_seed.set_random_seed', 'random_seed.set_random_seed', (['self._config.tf_random_seed'], {}), False, 'from tensorflow.python.framework import random_seed\n'), (422, 'tensorflow.contrib.framework.create_global_step', 'contrib_framework.create_global_step', (['g'], {}), True, 'from tensorflow.contrib import framework as contrib_framework\n'), (429, 'tensorflow.contrib.learn.python.learn.graph_actions.infer', 'infer', (['checkpoint_path', 'predictions'], {'feed_dict': 'feed_dict'}), False, 'from tensorflow.contrib.learn.python.learn.graph_actions import infer\n'), (489, 'tensorflow.contrib.framework.get_global_step', 'contrib_framework.get_global_step', ([], {}), True, 'from tensorflow.contrib import framework as contrib_framework\n'), (334, 'tensorflow.contrib.learn.python.learn.estimators.tensor_signature.tensors_compatible', 'tensor_signature.tensors_compatible', (['features', 'self._features_info'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import tensor_signature\n'), (341, 'tensorflow.contrib.learn.python.learn.estimators.tensor_signature.tensors_compatible', 'tensor_signature.tensors_compatible', (['targets', 'self._targets_info'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import tensor_signature\n'), (371, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (396, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (420, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n')]
souradip93/GCDT
5991044307f59598ea224b64f1f3b915fa00ebcc
#!/usr/bin/env python # coding=utf-8 # Copyright 2018 The THUMT Authors import argparse import os import numpy as np import tensorflow as tf import thumt.data.dataset as dataset import thumt.data.record as record import thumt.data.vocab as vocabulary import thumt.models as models import thumt.utils.hooks as hooks import thumt.utils.utils as utils import thumt.utils.parallel as parallel import thumt.utils.search as search def parse_args(args=None): parser = argparse.ArgumentParser( description="Training neural machine translation models", usage="trainer.py [<args>] [-h | --help]" ) # input files parser.add_argument("--input", type=str, nargs=2, help="Path of source and target corpus") parser.add_argument("--glove_emb_path", type=str, default=None, help="Path of glove embeddings") parser.add_argument("--bert_emb_path", type=str, default=None, help="Path of bert embeddings") parser.add_argument("--record", type=str, help="Path to tf.Record data") parser.add_argument("--output", type=str, default="train", help="Path to saved models") parser.add_argument("--vocabulary", type=str, nargs=3, help="Path of source and target vocabulary") parser.add_argument("--validation", type=str, help="Path of validation file") parser.add_argument("--references", type=str, nargs="+", help="Path of reference files") # model and configuration parser.add_argument("--model", type=str, required=True, help="Name of the model") parser.add_argument("--parameters", type=str, default="", help="Additional hyper parameters") return parser.parse_args(args) def default_parameters(): params = tf.contrib.training.HParams( input=["", ""], output="", record="", model="rnnsearch", vocab=["", ""], # Default training hyper parameters num_threads=6, batch_size=128, max_length=256, length_multiplier=1, mantissa_bits=2, warmup_steps=50, train_steps=100000, buffer_size=10000, constant_batch_size=False, device_list=[0], update_cycle=1, initializer="xavier", initializer_gain=0.08, adam_beta1=0.9, adam_beta2=0.999, adam_epsilon=1e-6, r0=2.0, s=1000, e=4000, clip_grad_norm=5.0, learning_rate=1.0, learning_rate_decay="rnnplus_warmup_decay", learning_rate_boundaries=[0], learning_rate_values=[0.0], keep_checkpoint_max=100, keep_top_checkpoint_max=5, gpu_memory_fraction=1, # Validation eval_steps=100000, eval_secs=0, eval_batch_size=64, top_beams=1, beam_size=4, decode_alpha=0.6, decode_length=0, decode_constant=5.0, decode_normalize=False, validation="", references=[""], save_checkpoint_secs=0, save_checkpoint_steps=1000, ) return params def import_params(model_dir, model_name, params): model_dir = os.path.abspath(model_dir) p_name = os.path.join(model_dir, "params.json") m_name = os.path.join(model_dir, model_name + ".json") if not tf.gfile.Exists(p_name) or not tf.gfile.Exists(m_name): return params with tf.gfile.Open(p_name) as fd: tf.logging.info("Restoring hyper parameters from %s" % p_name) json_str = fd.readline() params.parse_json(json_str) with tf.gfile.Open(m_name) as fd: tf.logging.info("Restoring model parameters from %s" % m_name) json_str = fd.readline() params.parse_json(json_str) return params def export_params(output_dir, name, params): if not tf.gfile.Exists(output_dir): tf.gfile.MkDir(output_dir) # Save params as params.json filename = os.path.join(output_dir, name) with tf.gfile.Open(filename, "w") as fd: fd.write(params.to_json()) def collect_params(all_params, params): collected = tf.contrib.training.HParams() for k in params.values().keys(): collected.add_hparam(k, getattr(all_params, k)) return collected def merge_parameters(params1, params2): params = tf.contrib.training.HParams() for (k, v) in params1.values().items(): params.add_hparam(k, v) params_dict = list(params.values()) ## key value pair for (k, v) in params2.values().items(): if k in params_dict: # Override setattr(params, k, v) else: params.add_hparam(k, v) return params def override_parameters(params, args): params.model = args.model params.input = args.input or params.input params.glove_emb_path = args.glove_emb_path params.bert_emb_path = args.bert_emb_path params.output = args.output or params.output params.record = args.record or params.record params.vocab = args.vocabulary or params.vocab params.validation = args.validation or params.validation params.references = args.references or params.references params.parse(args.parameters) params.vocabulary = { "source": vocabulary.load_vocabulary(params.vocab[0]), "target": vocabulary.load_vocabulary(params.vocab[1]), "char" : vocabulary.load_vocabulary(params.vocab[2]) } params.vocabulary["source"] = vocabulary.process_vocabulary( params.vocabulary["source"], params ) params.vocabulary["target"] = vocabulary.process_vocabulary( params.vocabulary["target"], params ) params.vocabulary["char"] = vocabulary.process_vocabulary( params.vocabulary["char"], params ) control_symbols = [params.pad, params.bos, params.eos, params.unk] params.mapping = { "source": vocabulary.get_control_mapping( params.vocabulary["source"], control_symbols ), "target": vocabulary.get_control_mapping( params.vocabulary["target"], control_symbols ), "char": vocabulary.get_control_mapping( params.vocabulary["char"], control_symbols ) } return params def get_initializer(params): if params.initializer == "xavier": return tf.contrib.layers.xavier_initializer() elif params.initializer == "uniform": max_val = params.initializer_gain return tf.random_uniform_initializer(-max_val, max_val) elif params.initializer == "normal": return tf.random_normal_initializer(0.0, params.initializer_gain) elif params.initializer == "normal_unit_scaling": return tf.variance_scaling_initializer(params.initializer_gain, mode="fan_avg", distribution="normal") elif params.initializer == "uniform_unit_scaling": return tf.variance_scaling_initializer(params.initializer_gain, mode="fan_avg", distribution="uniform") else: raise ValueError("Unrecognized initializer: %s" % params.initializer) def get_learning_rate_decay(learning_rate, global_step, params): if params.learning_rate_decay == "noam": step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "new_warmup_rsqrt_decay": step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = params.r0 * multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.0) * (warmup_steps ** -0.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "rnnplus_warmup_decay": step = tf.to_float(global_step) n = float(len(params.device_list)) warmup_steps = tf.to_float(params.warmup_steps) decay = tf.minimum(1 + step * (n - 1) / (n * warmup_steps), tf.minimum(n, n * ((2*n) ** ((params.s - n * step) / (params.e - params.s))))) return tf.maximum(learning_rate * decay, 5e-6) elif params.learning_rate_decay == "piecewise_constant": return tf.train.piecewise_constant(tf.to_int32(global_step), params.learning_rate_boundaries, params.learning_rate_values) elif params.learning_rate_decay == "none": return learning_rate else: raise ValueError("Unknown learning_rate_decay") def session_config(params): optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L1, do_function_inlining=True) graph_options = tf.GraphOptions(optimizer_options=optimizer_options) config = tf.ConfigProto(allow_soft_placement=True, graph_options=graph_options) if params.device_list: device_str = ",".join([str(i) for i in params.device_list]) config.gpu_options.visible_device_list = device_str config.gpu_options.per_process_gpu_memory_fraction = params.gpu_memory_fraction config.gpu_options.allow_growth = True return config def decode_target_ids(inputs, params): decoded = [] vocab = params.vocabulary["target"] for item in inputs: syms = [] for idx in item: sym = vocab[idx] if sym == params.eos: break if sym == params.pad: break syms.append(sym) decoded.append(syms) return decoded def main(args): tf.logging.set_verbosity(tf.logging.INFO) model_cls = models.get_model(args.model) params = default_parameters() # Import and override parameters # Priorities (low -> high): # default -> saved -> command params = merge_parameters(params, model_cls.get_parameters()) params = import_params(args.output, args.model, params) override_parameters(params, args) # Export all parameters and model specific parameters export_params(params.output, "params.json", params) export_params( params.output, "%s.json" % args.model, collect_params(params, model_cls.get_parameters()) ) # Build Graph with tf.Graph().as_default(): if not params.record: # Build input queue if params.use_bert and params.bert_emb_path: features = dataset.get_training_input_with_bert(params.input + [params.bert_emb_path], params) else: features = dataset.get_training_input(params.input, params) else: features = record.get_input_features( # ??? os.path.join(params.record, "*train*"), "train", params ) # Build model initializer = get_initializer(params) model = model_cls(params) # Multi-GPU setting sharded_losses = parallel.parallel_model( model.get_training_func(initializer), features, params.device_list ) loss = tf.add_n(sharded_losses) / len(sharded_losses) # Create global step global_step = tf.train.get_or_create_global_step() # Print parameters all_weights = {v.name: v for v in tf.trainable_variables()} total_size = 0 for v_name in sorted(list(all_weights)): v = all_weights[v_name] tf.logging.info("%s\tshape %s", v.name[:-2].ljust(80), str(v.shape).ljust(20)) v_size = np.prod(np.array(v.shape.as_list())).tolist() # mutiple all dimension size total_size += v_size tf.logging.info("Total trainable variables size: %d", total_size) learning_rate = get_learning_rate_decay(params.learning_rate, global_step, params) learning_rate = tf.convert_to_tensor(learning_rate, dtype=tf.float32) tf.summary.scalar("learning_rate", learning_rate) # Create optimizer opt = tf.train.AdamOptimizer(learning_rate, beta1=params.adam_beta1, beta2=params.adam_beta2, epsilon=params.adam_epsilon) if params.update_cycle == 1: train_op = tf.contrib.layers.optimize_loss( name="training", loss=loss, global_step=global_step, learning_rate=learning_rate, clip_gradients=params.clip_grad_norm or None, optimizer=opt, colocate_gradients_with_ops=True ) zero_op = tf.no_op("zero_op") collect_op = tf.no_op("collect_op") else: grads_and_vars = opt.compute_gradients( loss, colocate_gradients_with_ops=True) gradients = [item[0] for item in grads_and_vars] variables = [item[1] for item in grads_and_vars] variables = utils.replicate_variables(variables) zero_op = utils.zero_variables(variables) collect_op = utils.collect_gradients(gradients, variables) scale = 1.0 / params.update_cycle gradients, variables = utils.scale_gradients(grads_and_vars, scale) # Gradient clipping avoid greadient explosion!! if isinstance(params.clip_grad_norm or None, float): gradients, _ = tf.clip_by_global_norm(gradients, params.clip_grad_norm) # Update variables grads_and_vars = list(zip(gradients, variables)) with tf.control_dependencies([collect_op]): train_op = opt.apply_gradients(grads_and_vars, global_step) # Validation ''' if params.validation and params.references[0]: files = [params.validation] + list(params.references) eval_inputs = files eval_input_fn = dataset.get_evaluation_input else: print("Don't evaluate") eval_input_fn = None ''' # Add hooks train_hooks = [ tf.train.StopAtStepHook(last_step=params.train_steps), tf.train.NanTensorHook(loss), # Monitors the loss tensor and stops training if loss is NaN tf.train.LoggingTensorHook( { "step": global_step, "loss": loss, "chars": tf.shape(features["chars"]), "source": tf.shape(features["source"]), #"bert": tf.shape(features["bert"]), "lr": learning_rate }, every_n_iter=1 ), tf.train.CheckpointSaverHook( checkpoint_dir=params.output, save_secs=params.save_checkpoint_secs or None, save_steps=params.save_checkpoint_steps or None, saver=tf.train.Saver( max_to_keep=params.keep_checkpoint_max, sharded=False ) ) ] config = session_config(params) ''' if not eval_input_fn is None: train_hooks.append( hooks.EvaluationHook( lambda f: search.create_inference_graph( model.get_evaluation_func(), f, params ), lambda: eval_input_fn(eval_inputs, params), lambda x: decode_target_ids(x, params), params.output, config, params.keep_top_checkpoint_max, eval_secs=params.eval_secs, eval_steps=params.eval_steps ) ) ''' with tf.train.MonitoredTrainingSession( checkpoint_dir=params.output, hooks=train_hooks, save_checkpoint_secs=None, config=config) as sess: while not sess.should_stop(): utils.session_run(sess, zero_op) for i in range(1, params.update_cycle): utils.session_run(sess, collect_op) sess.run(train_op) if __name__ == "__main__": main(parse_args())
[ "tensorflow.convert_to_tensor", "tensorflow.control_dependencies", "tensorflow.gfile.Exists", "tensorflow.gfile.MkDir", "tensorflow.minimum", "tensorflow.train.AdamOptimizer", "tensorflow.to_int32", "tensorflow.train.MonitoredTrainingSession", "tensorflow.add_n", "tensorflow.summary.scalar", "tensorflow.Graph", "tensorflow.random_uniform_initializer", "tensorflow.OptimizerOptions", "tensorflow.train.get_or_create_global_step", "tensorflow.ConfigProto", "tensorflow.logging.set_verbosity", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.to_float", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.random_normal_initializer", "tensorflow.train.StopAtStepHook", "tensorflow.train.NanTensorHook", "tensorflow.gfile.Open", "tensorflow.shape", "tensorflow.variance_scaling_initializer", "tensorflow.logging.info", "tensorflow.no_op", "tensorflow.contrib.training.HParams", "tensorflow.maximum", "tensorflow.clip_by_global_norm", "tensorflow.GraphOptions", "tensorflow.contrib.layers.optimize_loss" ]
thumt/bin/trainer.py
[(20, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Training neural machine translation models"""', 'usage': '"""trainer.py [<args>] [-h | --help]"""'}), False, 'import argparse\n'), (53, 'tensorflow.contrib.training.HParams', 'tf.contrib.training.HParams', ([], {'input': "['', '']", 'output': '""""""', 'record': '""""""', 'model': '"""rnnsearch"""', 'vocab': "['', '']", 'num_threads': '(6)', 'batch_size': '(128)', 'max_length': '(256)', 'length_multiplier': '(1)', 'mantissa_bits': '(2)', 'warmup_steps': '(50)', 'train_steps': '(100000)', 'buffer_size': '(10000)', 'constant_batch_size': '(False)', 'device_list': '[0]', 'update_cycle': '(1)', 'initializer': '"""xavier"""', 'initializer_gain': '(0.08)', 'adam_beta1': '(0.9)', 'adam_beta2': '(0.999)', 'adam_epsilon': '(1e-06)', 'r0': '(2.0)', 's': '(1000)', 'e': '(4000)', 'clip_grad_norm': '(5.0)', 'learning_rate': '(1.0)', 'learning_rate_decay': '"""rnnplus_warmup_decay"""', 'learning_rate_boundaries': '[0]', 'learning_rate_values': '[0.0]', 'keep_checkpoint_max': '(100)', 'keep_top_checkpoint_max': '(5)', 'gpu_memory_fraction': '(1)', 'eval_steps': '(100000)', 'eval_secs': '(0)', 'eval_batch_size': '(64)', 'top_beams': '(1)', 'beam_size': '(4)', 'decode_alpha': '(0.6)', 'decode_length': '(0)', 'decode_constant': '(5.0)', 'decode_normalize': '(False)', 'validation': '""""""', 'references': "['']", 'save_checkpoint_secs': '(0)', 'save_checkpoint_steps': '(1000)'}), True, 'import tensorflow as tf\n'), (107, 'os.path.abspath', 'os.path.abspath', (['model_dir'], {}), False, 'import os\n'), (108, 'os.path.join', 'os.path.join', (['model_dir', '"""params.json"""'], {}), False, 'import os\n'), (109, 'os.path.join', 'os.path.join', (['model_dir', "(model_name + '.json')"], {}), False, 'import os\n'), (132, 'os.path.join', 'os.path.join', (['output_dir', 'name'], {}), False, 'import os\n'), (138, 'tensorflow.contrib.training.HParams', 'tf.contrib.training.HParams', ([], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.contrib.training.HParams', 'tf.contrib.training.HParams', ([], {}), True, 'import tensorflow as tf\n'), (182, 'thumt.data.vocab.process_vocabulary', 'vocabulary.process_vocabulary', (["params.vocabulary['source']", 'params'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (185, 'thumt.data.vocab.process_vocabulary', 'vocabulary.process_vocabulary', (["params.vocabulary['target']", 'params'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (188, 'thumt.data.vocab.process_vocabulary', 'vocabulary.process_vocabulary', (["params.vocabulary['char']", 'params'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (267, 'tensorflow.OptimizerOptions', 'tf.OptimizerOptions', ([], {'opt_level': 'tf.OptimizerOptions.L1', 'do_function_inlining': '(True)'}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.GraphOptions', 'tf.GraphOptions', ([], {'optimizer_options': 'optimizer_options'}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'graph_options': 'graph_options'}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), True, 'import tensorflow as tf\n'), (303, 'thumt.models.get_model', 'models.get_model', (['args.model'], {}), True, 'import thumt.models as models\n'), (114, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['p_name'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.logging.info', 'tf.logging.info', (["('Restoring hyper parameters from %s' % p_name)"], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['m_name'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.logging.info', 'tf.logging.info', (["('Restoring model parameters from %s' % m_name)"], {}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['output_dir'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.gfile.MkDir', 'tf.gfile.MkDir', (['output_dir'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.gfile.Open', 'tf.gfile.Open', (['filename', '"""w"""'], {}), True, 'import tensorflow as tf\n'), (178, 'thumt.data.vocab.load_vocabulary', 'vocabulary.load_vocabulary', (['params.vocab[0]'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (179, 'thumt.data.vocab.load_vocabulary', 'vocabulary.load_vocabulary', (['params.vocab[1]'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (180, 'thumt.data.vocab.load_vocabulary', 'vocabulary.load_vocabulary', (['params.vocab[2]'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (195, 'thumt.data.vocab.get_control_mapping', 'vocabulary.get_control_mapping', (["params.vocabulary['source']", 'control_symbols'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (199, 'thumt.data.vocab.get_control_mapping', 'vocabulary.get_control_mapping', (["params.vocabulary['target']", 'control_symbols'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (203, 'thumt.data.vocab.get_control_mapping', 'vocabulary.get_control_mapping', (["params.vocabulary['char']", 'control_symbols'], {}), True, 'import thumt.data.vocab as vocabulary\n'), (214, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.to_float', 'tf.to_float', (['global_step'], {}), True, 'import tensorflow as tf\n'), (235, 'tensorflow.to_float', 'tf.to_float', (['params.warmup_steps'], {}), True, 'import tensorflow as tf\n'), (346, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (358, 'tensorflow.logging.info', 'tf.logging.info', (['"""Total trainable variables size: %d"""', 'total_size'], {}), True, 'import tensorflow as tf\n'), (362, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['learning_rate'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""learning_rate"""', 'learning_rate'], {}), True, 'import tensorflow as tf\n'), (366, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {'beta1': 'params.adam_beta1', 'beta2': 'params.adam_beta2', 'epsilon': 'params.adam_epsilon'}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['p_name'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['m_name'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(-max_val)', 'max_val'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.minimum', 'tf.minimum', (['((step + 1) * warmup_steps ** -1.5)', '((step + 1) ** -0.5)'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.to_float', 'tf.to_float', (['global_step'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.to_float', 'tf.to_float', (['params.warmup_steps'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.add_n', 'tf.add_n', (['sharded_losses'], {}), True, 'import tensorflow as tf\n'), (372, 'tensorflow.contrib.layers.optimize_loss', 'tf.contrib.layers.optimize_loss', ([], {'name': '"""training"""', 'loss': 'loss', 'global_step': 'global_step', 'learning_rate': 'learning_rate', 'clip_gradients': '(params.clip_grad_norm or None)', 'optimizer': 'opt', 'colocate_gradients_with_ops': '(True)'}), True, 'import tensorflow as tf\n'), (381, 'tensorflow.no_op', 'tf.no_op', (['"""zero_op"""'], {}), True, 'import tensorflow as tf\n'), (382, 'tensorflow.no_op', 'tf.no_op', (['"""collect_op"""'], {}), True, 'import tensorflow as tf\n'), (388, 'thumt.utils.utils.replicate_variables', 'utils.replicate_variables', (['variables'], {}), True, 'import thumt.utils.utils as utils\n'), (389, 'thumt.utils.utils.zero_variables', 'utils.zero_variables', (['variables'], {}), True, 'import thumt.utils.utils as utils\n'), (390, 'thumt.utils.utils.collect_gradients', 'utils.collect_gradients', (['gradients', 'variables'], {}), True, 'import thumt.utils.utils as utils\n'), (393, 'thumt.utils.utils.scale_gradients', 'utils.scale_gradients', (['grads_and_vars', 'scale'], {}), True, 'import thumt.utils.utils as utils\n'), (417, 'tensorflow.train.StopAtStepHook', 'tf.train.StopAtStepHook', ([], {'last_step': 'params.train_steps'}), True, 'import tensorflow as tf\n'), (418, 'tensorflow.train.NanTensorHook', 'tf.train.NanTensorHook', (['loss'], {}), True, 'import tensorflow as tf\n'), (460, 'tensorflow.train.MonitoredTrainingSession', 'tf.train.MonitoredTrainingSession', ([], {'checkpoint_dir': 'params.output', 'hooks': 'train_hooks', 'save_checkpoint_secs': 'None', 'config': 'config'}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', 'params.initializer_gain'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.minimum', 'tf.minimum', (['((step + 1) * warmup_steps ** -1.0 * warmup_steps ** -0.5)', '((step + 1) ** -0.5)'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.to_float', 'tf.to_float', (['global_step'], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.to_float', 'tf.to_float', (['params.warmup_steps'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.maximum', 'tf.maximum', (['(learning_rate * decay)', '(5e-06)'], {}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (325, 'thumt.data.dataset.get_training_input_with_bert', 'dataset.get_training_input_with_bert', (['(params.input + [params.bert_emb_path])', 'params'], {}), True, 'import thumt.data.dataset as dataset\n'), (327, 'thumt.data.dataset.get_training_input', 'dataset.get_training_input', (['params.input', 'params'], {}), True, 'import thumt.data.dataset as dataset\n'), (330, 'os.path.join', 'os.path.join', (['params.record', '"""*train*"""'], {}), False, 'import os\n'), (349, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (397, 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', 'params.clip_grad_norm'], {}), True, 'import tensorflow as tf\n'), (402, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[collect_op]'], {}), True, 'import tensorflow as tf\n'), (464, 'thumt.utils.utils.session_run', 'utils.session_run', (['sess', 'zero_op'], {}), True, 'import thumt.utils.utils as utils\n'), (221, 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', (['params.initializer_gain'], {'mode': '"""fan_avg"""', 'distribution': '"""normal"""'}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.minimum', 'tf.minimum', (['n', '(n * (2 * n) ** ((params.s - n * step) / (params.e - params.s)))'], {}), True, 'import tensorflow as tf\n'), (423, 'tensorflow.shape', 'tf.shape', (["features['chars']"], {}), True, 'import tensorflow as tf\n'), (424, 'tensorflow.shape', 'tf.shape', (["features['source']"], {}), True, 'import tensorflow as tf\n'), (434, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': 'params.keep_checkpoint_max', 'sharded': '(False)'}), True, 'import tensorflow as tf\n'), (466, 'thumt.utils.utils.session_run', 'utils.session_run', (['sess', 'collect_op'], {}), True, 'import thumt.utils.utils as utils\n'), (225, 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', (['params.initializer_gain'], {'mode': '"""fan_avg"""', 'distribution': '"""uniform"""'}), True, 'import tensorflow as tf\n'), (257, 'tensorflow.to_int32', 'tf.to_int32', (['global_step'], {}), True, 'import tensorflow as tf\n')]
wull566/tensorflow_demo
c2c45050867cb056b8193eb53466d26b80b0ec13
import tensorflow as tf import numpy as np import gym import os import shutil np.random.seed(1) tf.set_random_seed(1) MAX_EPISODES = 2000 LR_A = 0.0005 # 1_tensorflow_new rate for actor LR_C = 0.0005 # 1_tensorflow_new rate for critic GAMMA = 0.999 # reward discount REPLACE_ITER_A = 1700 REPLACE_ITER_C = 1500 MEMORY_CAPACITY = 200000 BATCH_SIZE = 32 DISPLAY_THRESHOLD = 100 # display until the running reward > 100 DATA_PATH = './data' LOAD_MODEL = False SAVE_MODEL_ITER = 100000 RENDER = False OUTPUT_GRAPH = False ENV_NAME = 'BipedalWalker-v2' GLOBAL_STEP = tf.Variable(0, trainable=False) INCREASE_GS = GLOBAL_STEP.assign(tf.add(GLOBAL_STEP, 1)) LR_A = tf.train.exponential_decay(LR_A, GLOBAL_STEP, 10000, .97, staircase=True) LR_C = tf.train.exponential_decay(LR_C, GLOBAL_STEP, 10000, .97, staircase=True) END_POINT = (200 - 10) * (14/30) # from game env = gym.make(ENV_NAME) env.seed(1) STATE_DIM = env.observation_space.shape[0] # 24 ACTION_DIM = env.action_space.shape[0] # 4 ACTION_BOUND = env.action_space.high # [1, 1, 1, 1] # all placeholder for tf with tf.name_scope('S'): S = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s') with tf.name_scope('R'): R = tf.placeholder(tf.float32, [None, 1], name='r') with tf.name_scope('S_'): S_ = tf.placeholder(tf.float32, shape=[None, STATE_DIM], name='s_') ############################### Actor #################################### class Actor(object): def __init__(self, sess, action_dim, action_bound, learning_rate, t_replace_iter): self.sess = sess self.a_dim = action_dim self.action_bound = action_bound self.lr = learning_rate self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Actor'): # input s, output a self.a = self._build_net(S, scope='eval_net', trainable=True) # input s_, output a, get a_ for critic self.a_ = self._build_net(S_, scope='target_net', trainable=False) self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Actor/target_net') def _build_net(self, s, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) net = tf.layers.dense(s, 500, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l1', trainable=trainable) net = tf.layers.dense(net, 200, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('a'): actions = tf.layers.dense(net, self.a_dim, activation=tf.nn.tanh, kernel_initializer=init_w, bias_initializer=init_b, name='a', trainable=trainable) scaled_a = tf.multiply(actions, self.action_bound, name='scaled_a') # Scale output to -action_bound to action_bound return scaled_a def learn(self, s): # batch update self.sess.run(self.train_op, feed_dict={S: s}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1 def choose_action(self, s): s = s[np.newaxis, :] # single state return self.sess.run(self.a, feed_dict={S: s})[0] # single action def add_grad_to_graph(self, a_grads): with tf.variable_scope('policy_grads'): # ys = policy; # xs = policy's parameters; # self.a_grads = the gradients of the policy to get more Q # tf.gradients will calculate dys/dxs with a initial gradients for ys, so this is dq/da * da/dparams self.policy_grads_and_vars = tf.gradients(ys=self.a, xs=self.e_params, grad_ys=a_grads) with tf.variable_scope('A_train'): opt = tf.train.RMSPropOptimizer(-self.lr) # (- 1_tensorflow_new rate) for ascent policy self.train_op = opt.apply_gradients(zip(self.policy_grads_and_vars, self.e_params), global_step=GLOBAL_STEP) ############################### Critic #################################### class Critic(object): def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_): self.sess = sess self.s_dim = state_dim self.a_dim = action_dim self.lr = learning_rate self.gamma = gamma self.t_replace_iter = t_replace_iter self.t_replace_counter = 0 with tf.variable_scope('Critic'): # Input (s, a), output q self.a = a self.q = self._build_net(S, self.a, 'eval_net', trainable=True) # Input (s_, a_), output q_ for q_target self.q_ = self._build_net(S_, a_, 'target_net', trainable=False) # target_q is based on a_ from Actor's target_net self.e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/eval_net') self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Critic/target_net') with tf.variable_scope('target_q'): self.target_q = R + self.gamma * self.q_ with tf.variable_scope('abs_TD'): self.abs_td = tf.abs(self.target_q - self.q) self.ISWeights = tf.placeholder(tf.float32, [None, 1], name='IS_weights') with tf.variable_scope('TD_error'): self.loss = tf.reduce_mean(self.ISWeights * tf.squared_difference(self.target_q, self.q)) with tf.variable_scope('C_train'): self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=GLOBAL_STEP) with tf.variable_scope('a_grad'): self.a_grads = tf.gradients(self.q, a)[0] # tensor of gradients of each sample (None, a_dim) def _build_net(self, s, a, scope, trainable): with tf.variable_scope(scope): init_w = tf.random_normal_initializer(0., 0.01) init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 # combine the action and states together in this way w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable) net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1) with tf.variable_scope('l2'): net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('q'): q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a) return q def learn(self, s, a, r, s_, ISW): _, abs_td = self.sess.run([self.train_op, self.abs_td], feed_dict={S: s, self.a: a, R: r, S_: s_, self.ISWeights: ISW}) if self.t_replace_counter % self.t_replace_iter == 0: self.sess.run([tf.assign(t, e) for t, e in zip(self.t_params, self.e_params)]) self.t_replace_counter += 1 return abs_td class SumTree(object): """ This SumTree code is modified version and the original code is from: https://github.com/jaara/AI-blog/blob/master/SumTree.py Story the data with it priority in tree and data frameworks. """ data_pointer = 0 def __init__(self, capacity): self.capacity = capacity # for all priority values self.tree = np.zeros(2 * capacity - 1)+1e-5 # [--------------Parent nodes-------------][-------leaves to recode priority-------] # size: capacity - 1 size: capacity self.data = np.zeros(capacity, dtype=object) # for all transitions # [--------------data frame-------------] # size: capacity def add_new_priority(self, p, data): leaf_idx = self.data_pointer + self.capacity - 1 self.data[self.data_pointer] = data # update data_frame self.update(leaf_idx, p) # update tree_frame self.data_pointer += 1 if self.data_pointer >= self.capacity: # replace when exceed the capacity self.data_pointer = 0 def update(self, tree_idx, p): change = p - self.tree[tree_idx] self.tree[tree_idx] = p self._propagate_change(tree_idx, change) def _propagate_change(self, tree_idx, change): """change the sum of priority value in all parent nodes""" parent_idx = (tree_idx - 1) // 2 self.tree[parent_idx] += change if parent_idx != 0: self._propagate_change(parent_idx, change) def get_leaf(self, lower_bound): leaf_idx = self._retrieve(lower_bound) # search the max leaf priority based on the lower_bound data_idx = leaf_idx - self.capacity + 1 return [leaf_idx, self.tree[leaf_idx], self.data[data_idx]] def _retrieve(self, lower_bound, parent_idx=0): """ Tree structure and array storage: Tree index: 0 -> storing priority sum / \ 1 2 / \ / \ 3 4 5 6 -> storing priority for transitions Array type for storing: [0,1,2,3,4,5,6] """ left_child_idx = 2 * parent_idx + 1 right_child_idx = left_child_idx + 1 if left_child_idx >= len(self.tree): # end search when no more child return parent_idx if self.tree[left_child_idx] == self.tree[right_child_idx]: return self._retrieve(lower_bound, np.random.choice([left_child_idx, right_child_idx])) if lower_bound <= self.tree[left_child_idx]: # downward search, always search for a higher priority node return self._retrieve(lower_bound, left_child_idx) else: return self._retrieve(lower_bound - self.tree[left_child_idx], right_child_idx) @property def root_priority(self): return self.tree[0] # the root class Memory(object): # stored as ( s, a, r, s_ ) in SumTree """ This SumTree code is modified version and the original code is from: https://github.com/jaara/AI-blog/blob/master/Seaquest-DDQN-PER.py """ epsilon = 0.001 # small amount to avoid zero priority alpha = 0.6 # [0~1] convert the importance of TD error to priority beta = 0.4 # importance-sampling, from initial value increasing to 1 beta_increment_per_sampling = 1e-5 # annealing the bias abs_err_upper = 1 # for stability refer to paper def __init__(self, capacity): self.tree = SumTree(capacity) def store(self, error, transition): p = self._get_priority(error) self.tree.add_new_priority(p, transition) def prio_sample(self, n): batch_idx, batch_memory, ISWeights = [], [], [] segment = self.tree.root_priority / n self.beta = np.min([1, self.beta + self.beta_increment_per_sampling]) # max = 1 min_prob = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.root_priority maxiwi = np.power(self.tree.capacity * min_prob, -self.beta) # for later normalizing ISWeights for i in range(n): a = segment * i b = segment * (i + 1) lower_bound = np.random.uniform(a, b) while True: idx, p, data = self.tree.get_leaf(lower_bound) if type(data) is int: i -= 1 lower_bound = np.random.uniform(segment * i, segment * (i+1)) else: break prob = p / self.tree.root_priority ISWeights.append(self.tree.capacity * prob) batch_idx.append(idx) batch_memory.append(data) ISWeights = np.vstack(ISWeights) ISWeights = np.power(ISWeights, -self.beta) / maxiwi # normalize return batch_idx, np.vstack(batch_memory), ISWeights def random_sample(self, n): idx = np.random.randint(0, self.tree.capacity, size=n, dtype=np.int) return np.vstack(self.tree.data[idx]) def update(self, idx, error): p = self._get_priority(error) self.tree.update(idx, p) def _get_priority(self, error): error += self.epsilon # avoid 0 clipped_error = np.clip(error, 0, self.abs_err_upper) return np.power(clipped_error, self.alpha) sess = tf.Session() # Create actor and critic. actor = Actor(sess, ACTION_DIM, ACTION_BOUND, LR_A, REPLACE_ITER_A) critic = Critic(sess, STATE_DIM, ACTION_DIM, LR_C, GAMMA, REPLACE_ITER_C, actor.a, actor.a_) actor.add_grad_to_graph(critic.a_grads) M = Memory(MEMORY_CAPACITY) saver = tf.train.Saver(max_to_keep=100) if LOAD_MODEL: all_ckpt = tf.train.get_checkpoint_state('./data', 'checkpoint').all_model_checkpoint_paths saver.restore(sess, all_ckpt[-1]) else: if os.path.isdir(DATA_PATH): shutil.rmtree(DATA_PATH) os.mkdir(DATA_PATH) sess.run(tf.global_variables_initializer()) if OUTPUT_GRAPH: tf.summary.FileWriter('logs', graph=sess.graph) var = 3 # control exploration var_min = 0.01 for i_episode in range(MAX_EPISODES): # s = (hull angle speed, angular velocity, horizontal speed, vertical speed, position of joints and joints angular speed, legs contact with ground, and 10 lidar rangefinder measurements.) s = env.reset() ep_r = 0 while True: if RENDER: env.render() a = actor.choose_action(s) a = np.clip(np.random.normal(a, var), -1, 1) # add randomness to action selection for exploration s_, r, done, _ = env.step(a) # r = total 300+ points up to the far end. If the robot falls, it gets -100. if r == -100: r = -2 ep_r += r transition = np.hstack((s, a, [r], s_)) max_p = np.max(M.tree.tree[-M.tree.capacity:]) M.store(max_p, transition) if GLOBAL_STEP.eval(sess) > MEMORY_CAPACITY/20: var = max([var*0.9999, var_min]) # decay the action randomness tree_idx, b_M, ISWeights = M.prio_sample(BATCH_SIZE) # for critic update b_s = b_M[:, :STATE_DIM] b_a = b_M[:, STATE_DIM: STATE_DIM + ACTION_DIM] b_r = b_M[:, -STATE_DIM - 1: -STATE_DIM] b_s_ = b_M[:, -STATE_DIM:] abs_td = critic.learn(b_s, b_a, b_r, b_s_, ISWeights) actor.learn(b_s) for i in range(len(tree_idx)): # update priority idx = tree_idx[i] M.update(idx, abs_td[i]) if GLOBAL_STEP.eval(sess) % SAVE_MODEL_ITER == 0: ckpt_path = os.path.join(DATA_PATH, 'DDPG.ckpt') save_path = saver.save(sess, ckpt_path, global_step=GLOBAL_STEP, write_meta_graph=False) print("\nSave Model %s\n" % save_path) if done: if "running_r" not in globals(): running_r = ep_r else: running_r = 0.95*running_r + 0.05*ep_r if running_r > DISPLAY_THRESHOLD: RENDER = True else: RENDER = False done = '| Achieve ' if env.unwrapped.hull.position[0] >= END_POINT else '| -----' print('Episode:', i_episode, done, '| Running_r: %i' % int(running_r), '| Epi_r: %.2f' % ep_r, '| Exploration: %.3f' % var, '| Pos: %.i' % int(env.unwrapped.hull.position[0]), '| LR_A: %.6f' % sess.run(LR_A), '| LR_C: %.6f' % sess.run(LR_C), ) break s = s_ sess.run(INCREASE_GS)
[ "tensorflow.get_variable", "numpy.max", "tensorflow.abs", "tensorflow.train.AdamOptimizer", "numpy.random.randint", "numpy.hstack", "tensorflow.Variable", "numpy.clip", "tensorflow.get_collection", "tensorflow.gradients", "tensorflow.layers.dense", "tensorflow.train.exponential_decay", "tensorflow.add", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.random_normal_initializer", "numpy.zeros", "tensorflow.matmul", "tensorflow.train.RMSPropOptimizer", "numpy.min", "numpy.power", "numpy.random.choice", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.set_random_seed", "tensorflow.train.get_checkpoint_state", "tensorflow.multiply", "tensorflow.summary.FileWriter", "numpy.random.seed", "tensorflow.assign", "tensorflow.constant_initializer", "numpy.random.normal", "tensorflow.variable_scope", "numpy.random.uniform", "tensorflow.squared_difference", "numpy.vstack" ]
tutorials/3_reinforce/experiments/Solve_BipedalWalker/DDPG.py
[(7, 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), True, 'import numpy as np\n'), (8, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'trainable': '(False)'}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['LR_A', 'GLOBAL_STEP', '(10000)', '(0.97)'], {'staircase': '(True)'}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['LR_C', 'GLOBAL_STEP', '(10000)', '(0.97)'], {'staircase': '(True)'}), True, 'import tensorflow as tf\n'), (32, 'gym.make', 'gym.make', (['ENV_NAME'], {}), False, 'import gym\n'), (307, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (316, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': '(100)'}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.add', 'tf.add', (['GLOBAL_STEP', '(1)'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.name_scope', 'tf.name_scope', (['"""S"""'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, STATE_DIM]', 'name': '"""s"""'}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.name_scope', 'tf.name_scope', (['"""R"""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""r"""'}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.name_scope', 'tf.name_scope', (['"""S_"""'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, STATE_DIM]', 'name': '"""s_"""'}), True, 'import tensorflow as tf\n'), (322, 'os.path.isdir', 'os.path.isdir', (['DATA_PATH'], {}), False, 'import os\n'), (323, 'os.mkdir', 'os.mkdir', (['DATA_PATH'], {}), False, 'import os\n'), (327, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs"""'], {'graph': 'sess.graph'}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""Actor/eval_net"""'}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""Actor/target_net"""'}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""IS_weights"""'}), True, 'import tensorflow as tf\n'), (185, 'numpy.zeros', 'np.zeros', (['capacity'], {'dtype': 'object'}), True, 'import numpy as np\n'), (269, 'numpy.min', 'np.min', (['[1, self.beta + self.beta_increment_per_sampling]'], {}), True, 'import numpy as np\n'), (272, 'numpy.power', 'np.power', (['(self.tree.capacity * min_prob)', '(-self.beta)'], {}), True, 'import numpy as np\n'), (289, 'numpy.vstack', 'np.vstack', (['ISWeights'], {}), True, 'import numpy as np\n'), (294, 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.tree.capacity'], {'size': 'n', 'dtype': 'np.int'}), True, 'import numpy as np\n'), (295, 'numpy.vstack', 'np.vstack', (['self.tree.data[idx]'], {}), True, 'import numpy as np\n'), (303, 'numpy.clip', 'np.clip', (['error', '(0)', 'self.abs_err_upper'], {}), True, 'import numpy as np\n'), (304, 'numpy.power', 'np.power', (['clipped_error', 'self.alpha'], {}), True, 'import numpy as np\n'), (319, 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['"""./data"""', '"""checkpoint"""'], {}), True, 'import tensorflow as tf\n'), (322, 'shutil.rmtree', 'shutil.rmtree', (['DATA_PATH'], {}), False, 'import shutil\n'), (324, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (346, 'numpy.hstack', 'np.hstack', (['(s, a, [r], s_)'], {}), True, 'import numpy as np\n'), (347, 'numpy.max', 'np.max', (['M.tree.tree[-M.tree.capacity:]'], {}), True, 'import numpy as np\n'), (58, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Actor"""'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.01)'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.01)'], {}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.layers.dense', 'tf.layers.dense', (['s', '(500)'], {'activation': 'tf.nn.relu', 'kernel_initializer': 'init_w', 'bias_initializer': 'init_b', 'name': '"""l1"""', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.layers.dense', 'tf.layers.dense', (['net', '(200)'], {'activation': 'tf.nn.relu', 'kernel_initializer': 'init_w', 'bias_initializer': 'init_b', 'name': '"""l2"""', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""policy_grads"""'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.gradients', 'tf.gradients', ([], {'ys': 'self.a', 'xs': 'self.e_params', 'grad_ys': 'a_grads'}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""A_train"""'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', (['(-self.lr)'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Critic"""'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""Critic/eval_net"""'}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES'], {'scope': '"""Critic/target_net"""'}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""target_q"""'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""abs_TD"""'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.abs', 'tf.abs', (['(self.target_q - self.q)'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""TD_error"""'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""C_train"""'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""a_grad"""'], {}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.01)'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.01)'], {}), True, 'import tensorflow as tf\n'), (182, 'numpy.zeros', 'np.zeros', (['(2 * capacity - 1)'], {}), True, 'import numpy as np\n'), (271, 'numpy.min', 'np.min', (['self.tree.tree[-self.tree.capacity:]'], {}), True, 'import numpy as np\n'), (276, 'numpy.random.uniform', 'np.random.uniform', (['a', 'b'], {}), True, 'import numpy as np\n'), (290, 'numpy.power', 'np.power', (['ISWeights', '(-self.beta)'], {}), True, 'import numpy as np\n'), (291, 'numpy.vstack', 'np.vstack', (['batch_memory'], {}), True, 'import numpy as np\n'), (340, 'numpy.random.normal', 'np.random.normal', (['a', 'var'], {}), True, 'import numpy as np\n'), (364, 'os.path.join', 'os.path.join', (['DATA_PATH', '"""DDPG.ckpt"""'], {}), False, 'import os\n'), (77, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""a"""'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.layers.dense', 'tf.layers.dense', (['net', 'self.a_dim'], {'activation': 'tf.nn.tanh', 'kernel_initializer': 'init_w', 'bias_initializer': 'init_b', 'name': '"""a"""', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.multiply', 'tf.multiply', (['actions', 'self.action_bound'], {'name': '"""scaled_a"""'}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.gradients', 'tf.gradients', (['self.q', 'a'], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""l1"""'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.get_variable', 'tf.get_variable', (['"""w1_s"""', '[self.s_dim, n_l1]'], {'initializer': 'init_w', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.get_variable', 'tf.get_variable', (['"""w1_a"""', '[self.a_dim, n_l1]'], {'initializer': 'init_w', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.get_variable', 'tf.get_variable', (['"""b1"""', '[1, n_l1]'], {'initializer': 'init_b', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""l2"""'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.layers.dense', 'tf.layers.dense', (['net', '(20)'], {'activation': 'tf.nn.relu', 'kernel_initializer': 'init_w', 'bias_initializer': 'init_b', 'name': '"""l2"""', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""q"""'], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.layers.dense', 'tf.layers.dense', (['net', '(1)'], {'kernel_initializer': 'init_w', 'bias_initializer': 'init_b', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (237, 'numpy.random.choice', 'np.random.choice', (['[left_child_idx, right_child_idx]'], {}), True, 'import numpy as np\n'), (86, 'tensorflow.assign', 'tf.assign', (['t', 'e'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.squared_difference', 'tf.squared_difference', (['self.target_q', 'self.q'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.assign', 'tf.assign', (['t', 'e'], {}), True, 'import tensorflow as tf\n'), (281, 'numpy.random.uniform', 'np.random.uniform', (['(segment * i)', '(segment * (i + 1))'], {}), True, 'import numpy as np\n'), (155, 'tensorflow.matmul', 'tf.matmul', (['s', 'w1_s'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.matmul', 'tf.matmul', (['a', 'w1_a'], {}), True, 'import tensorflow as tf\n')]
Ravi-0809/question-generation
9065a3b47293b8a69a0548af1f6bedd4a4aa7f9c
import tensorflow as tf from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention class Model(object): def __init__(self, config, batch, word_mat=None, char_mat=None, trainable=True, opt=True, demo = False, graph = None): self.config = config self.demo = demo self.graph = graph if graph is not None else tf.Graph() with self.graph.as_default(): self.global_step = tf.get_variable('global_step', shape=[], dtype=tf.int32, initializer=tf.constant_initializer(0), trainable=False) self.dropout = tf.placeholder_with_default(0.0, (), name="dropout") if self.demo: self.c = tf.placeholder(tf.int32, [None, config.test_para_limit],"context") self.q = tf.placeholder(tf.int32, [None, config.test_ques_limit],"question") self.ch = tf.placeholder(tf.int32, [None, config.test_para_limit, config.char_limit],"context_char") self.qh = tf.placeholder(tf.int32, [None, config.test_ques_limit, config.char_limit],"question_char") self.y1 = tf.placeholder(tf.int32, [None, config.test_para_limit],"answer_index1") self.y2 = tf.placeholder(tf.int32, [None, config.test_para_limit],"answer_index2") else: self.c, self.q, self.ch, self.qh, self.y1, self.y2, self.qa_id = batch.get_next() # self.word_unk = tf.get_variable("word_unk", shape = [config.glove_dim], initializer=initializer()) self.word_mat = tf.get_variable("word_mat", initializer=tf.constant( word_mat, dtype=tf.float32), trainable=False) self.char_mat = tf.get_variable( "char_mat", initializer=tf.constant(char_mat, dtype=tf.float32)) self.c_mask = tf.cast(self.c, tf.bool) self.q_mask = tf.cast(self.q, tf.bool) self.c_len = tf.reduce_sum(tf.cast(self.c_mask, tf.int32), axis=1) self.q_len = tf.reduce_sum(tf.cast(self.q_mask, tf.int32), axis=1) if opt: # we have to hardcode the max batch size here! use the batch size from the generator as this will be used for PG N, CL = config.batch_size if not self.demo else config.batch_size, config.char_limit self.c_maxlen = tf.reduce_max(self.c_len) self.q_maxlen = tf.reduce_max(self.q_len) self.c = tf.slice(self.c, [0, 0], [N, self.c_maxlen]) self.q = tf.slice(self.q, [0, 0], [N, self.q_maxlen]) self.c_mask = tf.slice(self.c_mask, [0, 0], [N, self.c_maxlen]) self.q_mask = tf.slice(self.q_mask, [0, 0], [N, self.q_maxlen]) self.ch = tf.slice(self.ch, [0, 0, 0], [N, self.c_maxlen, CL]) self.qh = tf.slice(self.qh, [0, 0, 0], [N, self.q_maxlen, CL]) self.y1 = tf.argmax(tf.slice(self.y1, [0, 0], [N, self.c_maxlen]),axis=-1) self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1) else: self.c_maxlen, self.q_maxlen = config.para_limit, config.ques_limit self.ch_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.ch, tf.bool), tf.int32), axis=2), [-1]) self.qh_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.qh, tf.bool), tf.int32), axis=2), [-1]) self.forward() total_params() if trainable: self.lr = tf.minimum(config.learning_rate, 0.001 / tf.log(999.) * tf.log(tf.cast(self.global_step, tf.float32) + 1)) self.opt = tf.train.AdamOptimizer(learning_rate = self.lr, beta1 = 0.8, beta2 = 0.999, epsilon = 1e-7) grads = self.opt.compute_gradients(self.loss) gradients, variables = zip(*grads) capped_grads, _ = tf.clip_by_global_norm( gradients, config.grad_clip) self.train_op = self.opt.apply_gradients( zip(capped_grads, variables), global_step=self.global_step) def forward(self): config = self.config N, PL, QL, CL, d, dc, nh = config.batch_size if not self.demo else config.batch_size, self.c_maxlen, self.q_maxlen, config.char_limit, config.hidden, config.char_dim, config.num_heads with tf.variable_scope("Input_Embedding_Layer"): ch_emb = tf.reshape(tf.nn.embedding_lookup( self.char_mat, self.ch), [N * PL, CL, dc]) qh_emb = tf.reshape(tf.nn.embedding_lookup( self.char_mat, self.qh), [N * QL, CL, dc]) ch_emb = tf.nn.dropout(ch_emb, 1.0 - 0.5 * self.dropout) qh_emb = tf.nn.dropout(qh_emb, 1.0 - 0.5 * self.dropout) # Bidaf style conv-highway encoder ch_emb = conv(ch_emb, d, bias = True, activation = tf.nn.relu, kernel_size = 5, name = "char_conv", reuse = None) qh_emb = conv(qh_emb, d, bias = True, activation = tf.nn.relu, kernel_size = 5, name = "char_conv", reuse = True) ch_emb = tf.reduce_max(ch_emb, axis = 1) qh_emb = tf.reduce_max(qh_emb, axis = 1) ch_emb = tf.reshape(ch_emb, [N, PL, ch_emb.shape[-1]]) qh_emb = tf.reshape(qh_emb, [N, QL, ch_emb.shape[-1]]) c_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.c), 1.0 - self.dropout) q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout) c_emb = tf.concat([c_emb, ch_emb], axis=2) q_emb = tf.concat([q_emb, qh_emb], axis=2) c_emb = highway(c_emb, size = d, scope = "highway", dropout = self.dropout, reuse = None) q_emb = highway(q_emb, size = d, scope = "highway", dropout = self.dropout, reuse = True) with tf.variable_scope("Embedding_Encoder_Layer"): c = residual_block(c_emb, num_blocks = 1, num_conv_layers = 4, kernel_size = 7, mask = self.c_mask, num_filters = d, num_heads = nh, seq_len = self.c_len, scope = "Encoder_Residual_Block", bias = False, dropout = self.dropout) q = residual_block(q_emb, num_blocks = 1, num_conv_layers = 4, kernel_size = 7, mask = self.q_mask, num_filters = d, num_heads = nh, seq_len = self.q_len, scope = "Encoder_Residual_Block", reuse = True, # Share the weights between passage and question bias = False, dropout = self.dropout) with tf.variable_scope("Context_to_Query_Attention_Layer"): # C = tf.tile(tf.expand_dims(c,2),[1,1,self.q_maxlen,1]) # Q = tf.tile(tf.expand_dims(q,1),[1,self.c_maxlen,1,1]) # S = trilinear([C, Q, C*Q], input_keep_prob = 1.0 - self.dropout) S = optimized_trilinear_for_attention([c, q], self.c_maxlen, self.q_maxlen, input_keep_prob = 1.0 - self.dropout) mask_q = tf.expand_dims(self.q_mask, 1) S_ = tf.nn.softmax(mask_logits(S, mask = mask_q)) mask_c = tf.expand_dims(self.c_mask, 2) S_T = tf.transpose(tf.nn.softmax(mask_logits(S, mask = mask_c), dim = 1),(0,2,1)) self.c2q = tf.matmul(S_, q) self.q2c = tf.matmul(tf.matmul(S_, S_T), c) attention_outputs = [c, self.c2q, c * self.c2q, c * self.q2c] with tf.variable_scope("Model_Encoder_Layer"): inputs = tf.concat(attention_outputs, axis = -1) self.enc = [conv(inputs, d, name = "input_projection")] for i in range(3): if i % 2 == 0: # dropout every 2 blocks self.enc[i] = tf.nn.dropout(self.enc[i], 1.0 - self.dropout) self.enc.append( residual_block(self.enc[i], num_blocks = 7, num_conv_layers = 2, kernel_size = 5, mask = self.c_mask, num_filters = d, num_heads = nh, seq_len = self.c_len, scope = "Model_Encoder", bias = False, reuse = True if i > 0 else None, dropout = self.dropout) ) with tf.variable_scope("Output_Layer"): start_logits = tf.squeeze(conv(tf.concat([self.enc[1], self.enc[2]],axis = -1),1, bias = False, name = "start_pointer"),-1) end_logits = tf.squeeze(conv(tf.concat([self.enc[1], self.enc[3]],axis = -1),1, bias = False, name = "end_pointer"), -1) self.logits = [mask_logits(start_logits, mask = self.c_mask), mask_logits(end_logits, mask = self.c_mask)] logits1, logits2 = [l for l in self.logits] outer = tf.matmul(tf.expand_dims(tf.nn.softmax(logits1), axis=2), tf.expand_dims(tf.nn.softmax(logits2), axis=1)) outer = tf.matrix_band_part(outer, 0, config.ans_limit) self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1) self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1) losses = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits1, labels=self.y1) losses2 = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits2, labels=self.y2) self.loss = tf.reduce_mean(losses + losses2) if config.l2_norm is not None: variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) l2_loss = tf.contrib.layers.apply_regularization(regularizer, variables) self.loss += l2_loss if config.decay is not None: self.var_ema = tf.train.ExponentialMovingAverage(config.decay) ema_op = self.var_ema.apply(tf.trainable_variables()) with tf.control_dependencies([ema_op]): self.loss = tf.identity(self.loss) self.assign_vars = [] for var in tf.global_variables(): v = self.var_ema.average(var) if v: self.assign_vars.append(tf.assign(var,v)) def get_loss(self): return self.loss def get_global_step(self): return self.global_step
[ "tensorflow.concat", "tensorflow.matrix_band_part", "tensorflow.contrib.layers.apply_regularization", "tensorflow.control_dependencies", "tensorflow.cast", "tensorflow.global_variables", "tensorflow.train.ExponentialMovingAverage", "tensorflow.train.AdamOptimizer", "tensorflow.Graph", "tensorflow.get_collection", "tensorflow.placeholder_with_default", "tensorflow.trainable_variables", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.identity", "tensorflow.placeholder", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.nn.embedding_lookup", "tensorflow.reduce_max", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.slice", "tensorflow.reshape", "tensorflow.assign", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.clip_by_global_norm", "tensorflow.log", "tensorflow.variable_scope" ]
src/qa/qanet/model.py
[(8, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(0.0)', '()'], {'name': '"""dropout"""'}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.cast', 'tf.cast', (['self.c', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.cast', 'tf.cast', (['self.q', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (57, 'qa.qanet.layers.total_params', 'total_params', ([], {}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (73, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Input_Embedding_Layer"""'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['ch_emb', '(1.0 - 0.5 * self.dropout)'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['qh_emb', '(1.0 - 0.5 * self.dropout)'], {}), True, 'import tensorflow as tf\n'), (82, 'qa.qanet.layers.conv', 'conv', (['ch_emb', 'd'], {'bias': '(True)', 'activation': 'tf.nn.relu', 'kernel_size': '(5)', 'name': '"""char_conv"""', 'reuse': 'None'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (84, 'qa.qanet.layers.conv', 'conv', (['qh_emb', 'd'], {'bias': '(True)', 'activation': 'tf.nn.relu', 'kernel_size': '(5)', 'name': '"""char_conv"""', 'reuse': '(True)'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (87, 'tensorflow.reduce_max', 'tf.reduce_max', (['ch_emb'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.reduce_max', 'tf.reduce_max', (['qh_emb'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.reshape', 'tf.reshape', (['ch_emb', '[N, PL, ch_emb.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.reshape', 'tf.reshape', (['qh_emb', '[N, QL, ch_emb.shape[-1]]'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.concat', 'tf.concat', (['[c_emb, ch_emb]'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.concat', 'tf.concat', (['[q_emb, qh_emb]'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (99, 'qa.qanet.layers.highway', 'highway', (['c_emb'], {'size': 'd', 'scope': '"""highway"""', 'dropout': 'self.dropout', 'reuse': 'None'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (100, 'qa.qanet.layers.highway', 'highway', (['q_emb'], {'size': 'd', 'scope': '"""highway"""', 'dropout': 'self.dropout', 'reuse': '(True)'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (102, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Embedding_Encoder_Layer"""'], {}), True, 'import tensorflow as tf\n'), (103, 'qa.qanet.layers.residual_block', 'residual_block', (['c_emb'], {'num_blocks': '(1)', 'num_conv_layers': '(4)', 'kernel_size': '(7)', 'mask': 'self.c_mask', 'num_filters': 'd', 'num_heads': 'nh', 'seq_len': 'self.c_len', 'scope': '"""Encoder_Residual_Block"""', 'bias': '(False)', 'dropout': 'self.dropout'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (114, 'qa.qanet.layers.residual_block', 'residual_block', (['q_emb'], {'num_blocks': '(1)', 'num_conv_layers': '(4)', 'kernel_size': '(7)', 'mask': 'self.q_mask', 'num_filters': 'd', 'num_heads': 'nh', 'seq_len': 'self.q_len', 'scope': '"""Encoder_Residual_Block"""', 'reuse': '(True)', 'bias': '(False)', 'dropout': 'self.dropout'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (127, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Context_to_Query_Attention_Layer"""'], {}), True, 'import tensorflow as tf\n'), (131, 'qa.qanet.layers.optimized_trilinear_for_attention', 'optimized_trilinear_for_attention', (['[c, q]', 'self.c_maxlen', 'self.q_maxlen'], {'input_keep_prob': '(1.0 - self.dropout)'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (132, 'tensorflow.expand_dims', 'tf.expand_dims', (['self.q_mask', '(1)'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.expand_dims', 'tf.expand_dims', (['self.c_mask', '(2)'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.matmul', 'tf.matmul', (['S_', 'q'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Model_Encoder_Layer"""'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.concat', 'tf.concat', (['attention_outputs'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Output_Layer"""'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.matrix_band_part', 'tf.matrix_band_part', (['outer', '(0)', 'config.ans_limit'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits1', 'labels': 'self.y1'}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits2', 'labels': 'self.y2'}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(losses + losses2)'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.contrib.layers.apply_regularization', 'tf.contrib.layers.apply_regularization', (['regularizer', 'variables'], {}), True, 'import tensorflow as tf\n'), (186, 'tensorflow.train.ExponentialMovingAverage', 'tf.train.ExponentialMovingAverage', (['config.decay'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_para_limit]', '"""context"""'], {}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_ques_limit]', '"""question"""'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_para_limit, config.char_limit]', '"""context_char"""'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_ques_limit, config.char_limit]', '"""question_char"""'], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_para_limit]', '"""answer_index1"""'], {}), True, 'import tensorflow as tf\n'), (20, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, config.test_para_limit]', '"""answer_index2"""'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.cast', 'tf.cast', (['self.c_mask', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.cast', 'tf.cast', (['self.q_mask', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.reduce_max', 'tf.reduce_max', (['self.c_len'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.reduce_max', 'tf.reduce_max', (['self.q_len'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.slice', 'tf.slice', (['self.c', '[0, 0]', '[N, self.c_maxlen]'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.slice', 'tf.slice', (['self.q', '[0, 0]', '[N, self.q_maxlen]'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.slice', 'tf.slice', (['self.c_mask', '[0, 0]', '[N, self.c_maxlen]'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.slice', 'tf.slice', (['self.q_mask', '[0, 0]', '[N, self.q_maxlen]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.slice', 'tf.slice', (['self.ch', '[0, 0, 0]', '[N, self.c_maxlen, CL]'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.slice', 'tf.slice', (['self.qh', '[0, 0, 0]', '[N, self.q_maxlen, CL]'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.lr', 'beta1': '(0.8)', 'beta2': '(0.999)', 'epsilon': '(1e-07)'}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', 'config.grad_clip'], {}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.char_mat', 'self.ch'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.char_mat', 'self.qh'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.word_mat', 'self.c'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.word_mat', 'self.q'], {}), True, 'import tensorflow as tf\n'), (133, 'qa.qanet.layers.mask_logits', 'mask_logits', (['S'], {'mask': 'mask_q'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (137, 'tensorflow.matmul', 'tf.matmul', (['S_', 'S_T'], {}), True, 'import tensorflow as tf\n'), (142, 'qa.qanet.layers.conv', 'conv', (['inputs', 'd'], {'name': '"""input_projection"""'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (164, 'qa.qanet.layers.mask_logits', 'mask_logits', (['start_logits'], {'mask': 'self.c_mask'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (165, 'qa.qanet.layers.mask_logits', 'mask_logits', (['end_logits'], {'mask': 'self.c_mask'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (172, 'tensorflow.reduce_max', 'tf.reduce_max', (['outer'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.reduce_max', 'tf.reduce_max', (['outer'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (187, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[ema_op]'], {}), True, 'import tensorflow as tf\n'), (189, 'tensorflow.identity', 'tf.identity', (['self.loss'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (12, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.constant', 'tf.constant', (['word_mat'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.constant', 'tf.constant', (['char_mat'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.slice', 'tf.slice', (['self.y1', '[0, 0]', '[N, self.c_maxlen]'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.slice', 'tf.slice', (['self.y2', '[0, 0]', '[N, self.c_maxlen]'], {}), True, 'import tensorflow as tf\n'), (135, 'qa.qanet.layers.mask_logits', 'mask_logits', (['S'], {'mask': 'mask_c'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (145, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['self.enc[i]', '(1.0 - self.dropout)'], {}), True, 'import tensorflow as tf\n'), (147, 'qa.qanet.layers.residual_block', 'residual_block', (['self.enc[i]'], {'num_blocks': '(7)', 'num_conv_layers': '(2)', 'kernel_size': '(5)', 'mask': 'self.c_mask', 'num_filters': 'd', 'num_heads': 'nh', 'seq_len': 'self.c_len', 'scope': '"""Model_Encoder"""', 'bias': '(False)', 'reuse': '(True if i > 0 else None)', 'dropout': 'self.dropout'}), False, 'from qa.qanet.layers import initializer, regularizer, residual_block, highway, conv, mask_logits, trilinear, total_params, optimized_trilinear_for_attention\n'), (162, 'tensorflow.concat', 'tf.concat', (['[self.enc[1], self.enc[2]]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.concat', 'tf.concat', (['[self.enc[1], self.enc[3]]'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits1'], {}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits2'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.cast', 'tf.cast', (['self.ch', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.cast', 'tf.cast', (['self.qh', 'tf.bool'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.log', 'tf.log', (['(999.0)'], {}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.assign', 'tf.assign', (['var', 'v'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.cast', 'tf.cast', (['self.global_step', 'tf.float32'], {}), True, 'import tensorflow as tf\n')]
DdeGeus/single-network-panoptic-segmentation
891f13b8bca0f41e298900fe1c73bc3035caef5d
import tensorflow as tf import numpy as np from utils import box_utils def generate(base_size, stride, scales, ratios, features_height, features_width, offset=None): """ Args: base_size: (height, width) stride: (height, width) scales: (height, width) ratios: (height, width) features_height: features_width: offset: (height, width) Returns: """ with tf.variable_scope('anchor_generator'): if offset is None: offset = [stride[0]/2, stride[1]/2] features_width = tf.cast(features_width, tf.int32) features_height = tf.cast(features_height, tf.int32) scales = tf.convert_to_tensor(scales, dtype=tf.float32) ratios = tf.convert_to_tensor(ratios, dtype=tf.float32) offset = tf.convert_to_tensor(offset, dtype=tf.float32) scales_grid, ratios_grid = tf.meshgrid(scales, ratios) scales_grid = tf.reshape(scales_grid, [-1, 1]) ratios_grid = tf.reshape(ratios_grid, [-1, 1]) ratio_sqrts = tf.sqrt(ratios_grid) heights = scales_grid / ratio_sqrts * base_size[1] widths = scales_grid * ratio_sqrts * base_size[0] x_centers = tf.cast(tf.range(features_width), tf.float32) x_centers = x_centers * stride[1] y_centers = tf.cast(tf.range(features_height), tf.float32) y_centers = y_centers * stride[0] # x_centers = x_centers + offset[1] # y_centers = y_centers + offset[0] x_centers, y_centers = tf.meshgrid(x_centers, y_centers) widths, x_centers = tf.meshgrid(widths, x_centers) heights, y_centers = tf.meshgrid(heights, y_centers) anchor_centers = tf.stack([x_centers, y_centers], axis=2) anchor_centers = tf.reshape(anchor_centers, [-1, 2]) anchor_sizes = tf.stack([widths, heights], axis=2) anchor_sizes = tf.reshape(anchor_sizes, [-1, 2]) anchors = tf.concat([anchor_centers - .5 * anchor_sizes, anchor_centers + .5 * anchor_sizes], 1) # anchors = box_utils.convert_yxyx_to_xyxy_format(anchors) return anchors if __name__ == '__main__': anchor_size = [128, 128] anchor_stride = [8, 8] anchor_offset = [0, 0] anchor_scales = [0.0625, 0.125, 0.25, 0.5, 1.0, 2.0] anchor_ratios = [0.25, 0.5, 1.0, 2.0, 4.0] height, width = 64, 128 anchors = generate(anchor_size, anchor_stride, anchor_scales, anchor_ratios, height, width) init = tf.global_variables_initializer() with tf.Session(config=tf.ConfigProto(device_count={'GPU': 0})) as sess: sess.run(init) anchors_out = sess.run(anchors) print(anchors_out[-30:]) print(anchors.shape) print(anchors_out[158623])
[ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.range", "tensorflow.stack", "tensorflow.cast", "tensorflow.reshape", "tensorflow.ConfigProto", "tensorflow.global_variables_initializer", "tensorflow.meshgrid", "tensorflow.variable_scope", "tensorflow.sqrt" ]
components/anchor_generator.py
[(88, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""anchor_generator"""'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.cast', 'tf.cast', (['features_width', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.cast', 'tf.cast', (['features_height', 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['scales'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['ratios'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (35, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['offset'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.meshgrid', 'tf.meshgrid', (['scales', 'ratios'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.reshape', 'tf.reshape', (['scales_grid', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.reshape', 'tf.reshape', (['ratios_grid', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.sqrt', 'tf.sqrt', (['ratios_grid'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.meshgrid', 'tf.meshgrid', (['x_centers', 'y_centers'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.meshgrid', 'tf.meshgrid', (['widths', 'x_centers'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.meshgrid', 'tf.meshgrid', (['heights', 'y_centers'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.stack', 'tf.stack', (['[x_centers, y_centers]'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.reshape', 'tf.reshape', (['anchor_centers', '[-1, 2]'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.stack', 'tf.stack', (['[widths, heights]'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.reshape', 'tf.reshape', (['anchor_sizes', '[-1, 2]'], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.concat', 'tf.concat', (['[anchor_centers - 0.5 * anchor_sizes, anchor_centers + 0.5 * anchor_sizes]', '(1)'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.range', 'tf.range', (['features_width'], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.range', 'tf.range', (['features_height'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'GPU': 0}"}), True, 'import tensorflow as tf\n')]
Johnson-yue/stylegan2encoder
709ccb52fe9a1b4dfdc367f0390cf419f2c3e972
import tensorflow as tf import numpy as np import dnnlib.tflib as tflib from functools import partial def create_stub(name, batch_size): return tf.constant(0, dtype='float32', shape=(batch_size, 0)) def create_variable_for_generator(name, batch_size): return tf.get_variable('learnable_dlatents', shape=(batch_size, 18, 512), dtype='float32', initializer=tf.initializers.random_normal()) class Generator: def __init__(self, model, batch_size, randomize_noise=False): self.batch_size = batch_size self.initial_dlatents = np.zeros((self.batch_size, 18, 512)) model.components.synthesis.run(self.initial_dlatents, randomize_noise=randomize_noise, minibatch_size=self.batch_size, custom_inputs=[partial(create_variable_for_generator, batch_size=batch_size), partial(create_stub, batch_size=batch_size)], structure='fixed') self.sess = tf.get_default_session() self.graph = tf.get_default_graph() self.dlatent_variable = next(v for v in tf.global_variables() if 'learnable_dlatents' in v.name) self.set_dlatents(self.initial_dlatents) self.generator_output = self.graph.get_tensor_by_name('G_synthesis_1/_Run/concat/concat:0') self.generated_image = tflib.convert_images_to_uint8(self.generator_output, nchw_to_nhwc=True, uint8_cast=False) self.generated_image_uint8 = tf.saturate_cast(self.generated_image, tf.uint8) def reset_dlatents(self): self.set_dlatents(self.initial_dlatents) def set_dlatents(self, dlatents): assert (dlatents.shape == (self.batch_size, 18, 512)) self.sess.run(tf.assign(self.dlatent_variable, dlatents)) def get_dlatents(self): return self.sess.run(self.dlatent_variable) def generate_images(self, dlatents=None): if dlatents: self.set_dlatents(dlatents) return self.sess.run(self.generated_image_uint8)
[ "tensorflow.get_default_session", "tensorflow.constant", "tensorflow.assign", "tensorflow.global_variables", "tensorflow.initializers.random_normal", "tensorflow.saturate_cast", "tensorflow.get_default_graph", "numpy.zeros" ]
encoder/generator_model.py
[(8, 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': '"""float32"""', 'shape': '(batch_size, 0)'}), True, 'import tensorflow as tf\n'), (22, 'numpy.zeros', 'np.zeros', (['(self.batch_size, 18, 512)'], {}), True, 'import numpy as np\n'), (29, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (36, 'dnnlib.tflib.convert_images_to_uint8', 'tflib.convert_images_to_uint8', (['self.generator_output'], {'nchw_to_nhwc': '(True)', 'uint8_cast': '(False)'}), True, 'import dnnlib.tflib as tflib\n'), (37, 'tensorflow.saturate_cast', 'tf.saturate_cast', (['self.generated_image', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.initializers.random_normal', 'tf.initializers.random_normal', ([], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.assign', 'tf.assign', (['self.dlatent_variable', 'dlatents'], {}), True, 'import tensorflow as tf\n'), (25, 'functools.partial', 'partial', (['create_variable_for_generator'], {'batch_size': 'batch_size'}), False, 'from functools import partial\n'), (26, 'functools.partial', 'partial', (['create_stub'], {'batch_size': 'batch_size'}), False, 'from functools import partial\n'), (32, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n')]
failure-to-thrive/addons
63c82e318e68b07eb1162d1ff247fe9f4d3194fc
# 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. # ============================================================================== """Cyclical Learning Rate Schedule policies for TensorFlow.""" import tensorflow as tf @tf.keras.utils.register_keras_serializable(package="Addons") class CyclicalLearningRate(tf.keras.optimizers.schedules.LearningRateSchedule): """A LearningRateSchedule that uses cyclical schedule.""" def __init__( self, initial_learning_rate, maximal_learning_rate, step_size, scale_fn, scale_mode="cycle", name=None, ): """Applies cyclical schedule to the learning rate. See Cyclical Learning Rates for Training Neural Networks. https://arxiv.org/abs/1506.01186 ```python lr_schedule = tf.keras.optimizers.schedules.CyclicalLearningRate( initial_learning_rate=1e-4, maximal_learning_rate=1e-2, step_size=2000, scale_fn=lambda x: 1., scale_mode="cycle", name="MyCyclicScheduler") model.compile(optimizer=tf.keras.optimizers.SGD( learning_rate=lr_schedule), loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels, epochs=5) ``` You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` as the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The initial learning rate. maximal_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The maximum learning rate. step_size: A scalar `float32` or `float64` `Tensor` or a Python number. Step size. scale_fn: A function. Scheduling function applied in cycle scale_mode: ['cycle', 'iterations']. Mode to apply during cyclic schedule name: (Optional) Name for the operation. Returns: Updated learning rate value. """ super().__init__() self.initial_learning_rate = initial_learning_rate self.maximal_learning_rate = maximal_learning_rate self.step_size = step_size self.scale_fn = scale_fn self.scale_mode = scale_mode self.name = name def __call__(self, step): with tf.name_scope(self.name or "CyclicalLearningRate"): initial_learning_rate = tf.convert_to_tensor( self.initial_learning_rate, name="initial_learning_rate" ) dtype = initial_learning_rate.dtype maximal_learning_rate = tf.cast(self.maximal_learning_rate, dtype) step_size = tf.cast(self.step_size, dtype) cycle = tf.floor(1 + step / (2 * step_size)) x = tf.abs(step / step_size - 2 * cycle + 1) mode_step = cycle if self.scale_mode == "cycle" else step return initial_learning_rate + ( maximal_learning_rate - initial_learning_rate ) * tf.maximum(tf.cast(0, dtype), (1 - x)) * self.scale_fn(mode_step) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "maximal_learning_rate": self.maximal_learning_rate, "step_size": self.step_size, "scale_mode": self.scale_mode, } @tf.keras.utils.register_keras_serializable(package="Addons") class TriangularCyclicalLearningRate(CyclicalLearningRate): def __init__( self, initial_learning_rate, maximal_learning_rate, step_size, scale_mode="cycle", name="TriangularCyclicalLearningRate", ): """Applies triangular cyclical schedule to the learning rate. See Cyclical Learning Rates for Training Neural Networks. https://arxiv.org/abs/1506.01186 ```python from tf.keras.optimizers import schedules lr_schedule = schedules.TriangularCyclicalLearningRate( initial_learning_rate=1e-4, maximal_learning_rate=1e-2, step_size=2000, scale_mode="cycle", name="MyCyclicScheduler") model.compile(optimizer=tf.keras.optimizers.SGD( learning_rate=lr_schedule), loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels, epochs=5) ``` You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` as the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The initial learning rate. maximal_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The maximum learning rate. step_size: A scalar `float32` or `float64` `Tensor` or a Python number. Step size. scale_fn: A function. Scheduling function applied in cycle scale_mode: ['cycle', 'iterations']. Mode to apply during cyclic schedule name: (Optional) Name for the operation. Returns: Updated learning rate value. """ super().__init__( initial_learning_rate=initial_learning_rate, maximal_learning_rate=maximal_learning_rate, step_size=step_size, scale_fn=lambda x: 1.0, scale_mode=scale_mode, name=name, ) @tf.keras.utils.register_keras_serializable(package="Addons") class Triangular2CyclicalLearningRate(CyclicalLearningRate): def __init__( self, initial_learning_rate, maximal_learning_rate, step_size, scale_mode="cycle", name="Triangular2CyclicalLearningRate", ): """Applies triangular2 cyclical schedule to the learning rate. See Cyclical Learning Rates for Training Neural Networks. https://arxiv.org/abs/1506.01186 ```python from tf.keras.optimizers import schedules lr_schedule = schedules.Triangular2CyclicalLearningRate( initial_learning_rate=1e-4, maximal_learning_rate=1e-2, step_size=2000, scale_mode="cycle", name="MyCyclicScheduler") model.compile(optimizer=tf.keras.optimizers.SGD( learning_rate=lr_schedule), loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels, epochs=5) ``` You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` as the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The initial learning rate. maximal_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The maximum learning rate. step_size: A scalar `float32` or `float64` `Tensor` or a Python number. Step size. scale_fn: A function. Scheduling function applied in cycle scale_mode: ['cycle', 'iterations']. Mode to apply during cyclic schedule name: (Optional) Name for the operation. Returns: Updated learning rate value. """ super().__init__( initial_learning_rate=initial_learning_rate, maximal_learning_rate=maximal_learning_rate, step_size=step_size, scale_fn=lambda x: 1 / (2.0 ** (x - 1)), scale_mode=scale_mode, name=name, ) @tf.keras.utils.register_keras_serializable(package="Addons") class ExponentialCyclicalLearningRate(CyclicalLearningRate): def __init__( self, initial_learning_rate, maximal_learning_rate, step_size, scale_mode="iterations", gamma=1.0, name="ExponentialCyclicalLearningRate", ): """Applies exponential cyclical schedule to the learning rate. See Cyclical Learning Rates for Training Neural Networks. https://arxiv.org/abs/1506.01186 ```python from tf.keras.optimizers import schedules lr_schedule = ExponentialCyclicalLearningRate( initial_learning_rate=1e-4, maximal_learning_rate=1e-2, step_size=2000, scale_mode="cycle", gamma=0.96, name="MyCyclicScheduler") model.compile(optimizer=tf.keras.optimizers.SGD( learning_rate=lr_schedule), loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels, epochs=5) ``` You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` as the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The initial learning rate. maximal_learning_rate: A scalar `float32` or `float64` `Tensor` or a Python number. The maximum learning rate. step_size: A scalar `float32` or `float64` `Tensor` or a Python number. Step size. scale_fn: A function. Scheduling function applied in cycle scale_mode: ['cycle', 'iterations']. Mode to apply during cyclic schedule gamma: A scalar `float32` or `float64` `Tensor` or a Python number. Gamma value. name: (Optional) Name for the operation. Returns: Updated learning rate value. """ super().__init__( initial_learning_rate=initial_learning_rate, maximal_learning_rate=maximal_learning_rate, step_size=step_size, scale_fn=lambda x: gamma ** x, scale_mode=scale_mode, name=name, )
[ "tensorflow.convert_to_tensor", "tensorflow.cast", "tensorflow.floor", "tensorflow.keras.utils.register_keras_serializable", "tensorflow.name_scope", "tensorflow.abs" ]
tensorflow_addons/optimizers/cyclical_learning_rate.py
[(20, 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""Addons"""'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""Addons"""'}), True, 'import tensorflow as tf\n'), (168, 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""Addons"""'}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.keras.utils.register_keras_serializable', 'tf.keras.utils.register_keras_serializable', ([], {'package': '"""Addons"""'}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.name_scope', 'tf.name_scope', (["(self.name or 'CyclicalLearningRate')"], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['self.initial_learning_rate'], {'name': '"""initial_learning_rate"""'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.cast', 'tf.cast', (['self.maximal_learning_rate', 'dtype'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.cast', 'tf.cast', (['self.step_size', 'dtype'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.floor', 'tf.floor', (['(1 + step / (2 * step_size))'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.abs', 'tf.abs', (['(step / step_size - 2 * cycle + 1)'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.cast', 'tf.cast', (['(0)', 'dtype'], {}), True, 'import tensorflow as tf\n')]
mgelbart/ray
4cec2286572e368a4bd64aae467751a384eff62d
import numpy as np import os import scipy.optimize import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import ray import ray.experimental.tf_utils class LinearModel(object): """Simple class for a one layer neural network. Note that this code does not initialize the network weights. Instead weights are set via self.variables.set_weights. Example: net = LinearModel([10, 10]) weights = [np.random.normal(size=[10, 10]), np.random.normal(size=[10])] variable_names = [v.name for v in net.variables] net.variables.set_weights(dict(zip(variable_names, weights))) Attributes: x (tf.placeholder): Input vector. w (tf.Variable): Weight matrix. b (tf.Variable): Bias vector. y_ (tf.placeholder): Input result vector. cross_entropy (tf.Operation): Final layer of network. cross_entropy_grads (tf.Operation): Gradient computation. sess (tf.Session): Session used for training. variables (TensorFlowVariables): Extracted variables and methods to manipulate them. """ def __init__(self, shape): """Creates a LinearModel object.""" x = tf.placeholder(tf.float32, [None, shape[0]]) w = tf.Variable(tf.zeros(shape)) b = tf.Variable(tf.zeros(shape[1])) self.x = x self.w = w self.b = b y = tf.nn.softmax(tf.matmul(x, w) + b) y_ = tf.placeholder(tf.float32, [None, shape[1]]) self.y_ = y_ cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) ) self.cross_entropy = cross_entropy self.cross_entropy_grads = tf.gradients(cross_entropy, [w, b]) self.sess = tf.Session() # In order to get and set the weights, we pass in the loss function to # Ray's TensorFlowVariables to automatically create methods to modify # the weights. self.variables = ray.experimental.tf_utils.TensorFlowVariables( cross_entropy, self.sess ) def loss(self, xs, ys): """Computes the loss of the network.""" return float( self.sess.run(self.cross_entropy, feed_dict={self.x: xs, self.y_: ys}) ) def grad(self, xs, ys): """Computes the gradients of the network.""" return self.sess.run( self.cross_entropy_grads, feed_dict={self.x: xs, self.y_: ys} ) @ray.remote class NetActor(object): def __init__(self, xs, ys): os.environ["CUDA_VISIBLE_DEVICES"] = "" with tf.device("/cpu:0"): self.net = LinearModel([784, 10]) self.xs = xs self.ys = ys # Compute the loss on a batch of data. def loss(self, theta): net = self.net net.variables.set_flat(theta) return net.loss(self.xs, self.ys) # Compute the gradient of the loss on a batch of data. def grad(self, theta): net = self.net net.variables.set_flat(theta) gradients = net.grad(self.xs, self.ys) return np.concatenate([g.flatten() for g in gradients]) def get_flat_size(self): return self.net.variables.get_flat_size() # Compute the loss on the entire dataset. def full_loss(theta): theta_id = ray.put(theta) loss_ids = [actor.loss.remote(theta_id) for actor in actors] return sum(ray.get(loss_ids)) # Compute the gradient of the loss on the entire dataset. def full_grad(theta): theta_id = ray.put(theta) grad_ids = [actor.grad.remote(theta_id) for actor in actors] # The float64 conversion is necessary for use with fmin_l_bfgs_b. return sum(ray.get(grad_ids)).astype("float64") if __name__ == "__main__": ray.init() # From the perspective of scipy.optimize.fmin_l_bfgs_b, full_loss is simply # a function which takes some parameters theta, and computes a loss. # Similarly, full_grad is a function which takes some parameters theta, and # computes the gradient of the loss. Internally, these functions use Ray to # distribute the computation of the loss and the gradient over the data # that is represented by the remote object refs x_batches and y_batches and # which is potentially distributed over a cluster. However, these details # are hidden from scipy.optimize.fmin_l_bfgs_b, which simply uses it to run # the L-BFGS algorithm. # Load the mnist data and turn the data into remote objects. print("Downloading the MNIST dataset. This may take a minute.") mnist = input_data.read_data_sets("MNIST_data", one_hot=True) num_batches = 10 batch_size = mnist.train.num_examples // num_batches batches = [mnist.train.next_batch(batch_size) for _ in range(num_batches)] print("Putting MNIST in the object store.") actors = [NetActor.remote(xs, ys) for (xs, ys) in batches] # Initialize the weights for the network to the vector of all zeros. dim = ray.get(actors[0].get_flat_size.remote()) theta_init = 1e-2 * np.random.normal(size=dim) # Use L-BFGS to minimize the loss function. print("Running L-BFGS.") result = scipy.optimize.fmin_l_bfgs_b( full_loss, theta_init, maxiter=10, fprime=full_grad, disp=True )
[ "tensorflow.device", "tensorflow.matmul", "tensorflow.zeros", "tensorflow.gradients", "tensorflow.placeholder", "numpy.random.normal", "tensorflow.log", "tensorflow.Session", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ]
doc/source/ray-core/examples/lbfgs/driver.py
[(102, 'ray.put', 'ray.put', (['theta'], {}), False, 'import ray\n'), (109, 'ray.put', 'ray.put', (['theta'], {}), False, 'import ray\n'), (116, 'ray.init', 'ray.init', ([], {}), False, 'import ray\n'), (130, 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""MNIST_data"""'], {'one_hot': '(True)'}), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), (39, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, shape[0]]'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, shape[1]]'], {}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.gradients', 'tf.gradients', (['cross_entropy', '[w, b]'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (57, 'ray.experimental.tf_utils.TensorFlowVariables', 'ray.experimental.tf_utils.TensorFlowVariables', (['cross_entropy', 'self.sess'], {}), False, 'import ray\n'), (104, 'ray.get', 'ray.get', (['loss_ids'], {}), False, 'import ray\n'), (138, 'numpy.random.normal', 'np.random.normal', ([], {'size': 'dim'}), True, 'import numpy as np\n'), (40, 'tensorflow.zeros', 'tf.zeros', (['shape'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.zeros', 'tf.zeros', (['shape[1]'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), True, 'import tensorflow as tf\n'), (112, 'ray.get', 'ray.get', (['grad_ids'], {}), False, 'import ray\n'), (49, 'tensorflow.log', 'tf.log', (['y'], {}), True, 'import tensorflow as tf\n')]
ProjetEtudeMLFI/TensorFI
961a0205ec90935a238c58112e8119c34a70ba7c
#!/usr/bin/python ''' A nearest neighbor learning algorithm example using TensorFlow library. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/) Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' from __future__ import print_function import numpy as np import tensorflow as tf import TensorFI as ti # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # In this example, we limit mnist data Xtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates) Xte, Yte = mnist.test.next_batch(200) #200 for testing # tf Graph Input xtr = tf.placeholder("float", [None, 784]) xte = tf.placeholder("float", [784]) # Nearest Neighbor calculation using L1 Distance # Calculate L1 Distance distance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))), reduction_indices=1) # Prediction: Get min distance index (Nearest neighbor) pred = tf.arg_min(distance, 0) accuracy = 0. # Initialize the variables (i.e. assign their default value) init = tf.global_variables_initializer() # Start training with tf.compat.v1.Session() as sess: # Run the initializer sess.run(init) # Add the fault injection code here to instrument the graph # We start injecting the fault right away here unlike earlier fi = ti.TensorFI(sess, name="NearestNeighbor", logLevel=50) # loop over test data for i in range(len(Xte)): # Get nearest neighbor nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]}) # Get nearest neighbor class label and compare it to its true label print("Test", i, "Prediction:", np.argmax(Ytr[nn_index]), \ "True Class:", np.argmax(Yte[i])) # Calculate accuracy if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]): accuracy += 1. / len(Xte) print("Accuracy:", accuracy) # Make the log files in TensorBoard logs_path = "./logs" logWriter = tf.summary.FileWriter(logs_path, sess.graph)
[ "tensorflow.negative", "tensorflow.summary.FileWriter", "tensorflow.arg_min", "tensorflow.placeholder", "tensorflow.compat.v1.Session", "tensorflow.global_variables_initializer", "numpy.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ]
Tests/nearest_neighbor.py
[(19, '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'), (26, 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[None, 784]'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""', '[784]'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.arg_min', 'tf.arg_min', (['distance', '(0)'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {}), True, 'import tensorflow as tf\n'), (49, 'TensorFI.TensorFI', 'ti.TensorFI', (['sess'], {'name': '"""NearestNeighbor"""', 'logLevel': '(50)'}), True, 'import TensorFI as ti\n'), (65, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['logs_path', 'sess.graph'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.negative', 'tf.negative', (['xte'], {}), True, 'import tensorflow as tf\n'), (56, 'numpy.argmax', 'np.argmax', (['Ytr[nn_index]'], {}), True, 'import numpy as np\n'), (57, 'numpy.argmax', 'np.argmax', (['Yte[i]'], {}), True, 'import numpy as np\n'), (59, 'numpy.argmax', 'np.argmax', (['Ytr[nn_index]'], {}), True, 'import numpy as np\n'), (59, 'numpy.argmax', 'np.argmax', (['Yte[i]'], {}), True, 'import numpy as np\n')]
gourav108/coreml
6bc2d494dff23cff923368e735992a4f4a47483c
# 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. # ============================================================================== """Utils used to manipulate tensor shapes.""" import tensorflow as tf from utils import static_shape def _is_tensor(t): """Returns a boolean indicating whether the input is a tensor. Args: t: the input to be tested. Returns: a boolean that indicates whether t is a tensor. """ return isinstance(t, (tf.Tensor, tf.SparseTensor, tf.Variable)) def _set_dim_0(t, d0): """Sets the 0-th dimension of the input tensor. Args: t: the input tensor, assuming the rank is at least 1. d0: an integer indicating the 0-th dimension of the input tensor. Returns: the tensor t with the 0-th dimension set. """ t_shape = t.get_shape().as_list() t_shape[0] = d0 t.set_shape(t_shape) return t def pad_tensor(t, length): """Pads the input tensor with 0s along the first dimension up to the length. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after padding, assuming length <= t.shape[0]. Returns: padded_t: the padded tensor, whose first dimension is length. If the length is an integer, the first dimension of padded_t is set to length statically. """ t_rank = tf.rank(t) t_shape = tf.shape(t) t_d0 = t_shape[0] pad_d0 = tf.expand_dims(length - t_d0, 0) pad_shape = tf.cond( tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0), lambda: tf.expand_dims(length - t_d0, 0)) padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0) if not _is_tensor(length): padded_t = _set_dim_0(padded_t, length) return padded_t def clip_tensor(t, length): """Clips the input tensor along the first dimension up to the length. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after clipping, assuming length <= t.shape[0]. Returns: clipped_t: the clipped tensor, whose first dimension is length. If the length is an integer, the first dimension of clipped_t is set to length statically. """ clipped_t = tf.gather(t, tf.range(length)) if not _is_tensor(length): clipped_t = _set_dim_0(clipped_t, length) return clipped_t def pad_or_clip_tensor(t, length): """Pad or clip the input tensor along the first dimension. Args: t: the input tensor, assuming the rank is at least 1. length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after processing. Returns: processed_t: the processed tensor, whose first dimension is length. If the length is an integer, the first dimension of the processed tensor is set to length statically. """ processed_t = tf.cond( tf.greater(tf.shape(t)[0], length), lambda: clip_tensor(t, length), lambda: pad_tensor(t, length)) if not _is_tensor(length): processed_t = _set_dim_0(processed_t, length) return processed_t def combined_static_and_dynamic_shape(tensor): """Returns a list containing static and dynamic values for the dimensions. Returns a list of static and dynamic values for shape dimensions. This is useful to preserve static shapes when available in reshape operation. Args: tensor: A tensor of any type. Returns: A list of size tensor.shape.ndims containing integers or a scalar tensor. """ static_tensor_shape = tensor.shape.as_list() dynamic_tensor_shape = tf.shape(tensor) combined_shape = [] for index, dim in enumerate(static_tensor_shape): if dim is not None: combined_shape.append(dim) else: combined_shape.append(dynamic_tensor_shape[index]) return combined_shape def static_or_dynamic_map_fn(fn, elems, dtype=None, parallel_iterations=32, back_prop=True): """Runs map_fn as a (static) for loop when possible. This function rewrites the map_fn as an explicit unstack input -> for loop over function calls -> stack result combination. This allows our graphs to be acyclic when the batch size is static. For comparison, see https://www.tensorflow.org/api_docs/python/tf/map_fn. Note that `static_or_dynamic_map_fn` currently is not *fully* interchangeable with the default tf.map_fn function as it does not accept nested inputs (only Tensors or lists of Tensors). Likewise, the output of `fn` can only be a Tensor or list of Tensors. TODO(jonathanhuang): make this function fully interchangeable with tf.map_fn. Args: fn: The callable to be performed. It accepts one argument, which will have the same structure as elems. Its output must have the same structure as elems. elems: A tensor or list of tensors, each of which will be unpacked along their first dimension. The sequence of the resulting slices will be applied to fn. dtype: (optional) The output type(s) of fn. If fn returns a structure of Tensors differing from the structure of elems, then dtype is not optional and must have the same structure as the output of fn. parallel_iterations: (optional) number of batch items to process in parallel. This flag is only used if the native tf.map_fn is used and defaults to 32 instead of 10 (unlike the standard tf.map_fn default). back_prop: (optional) True enables support for back propagation. This flag is only used if the native tf.map_fn is used. Returns: A tensor or sequence of tensors. Each tensor packs the results of applying fn to tensors unpacked from elems along the first dimension, from first to last. Raises: ValueError: if `elems` a Tensor or a list of Tensors. ValueError: if `fn` does not return a Tensor or list of Tensors """ if isinstance(elems, list): for elem in elems: if not isinstance(elem, tf.Tensor): raise ValueError('`elems` must be a Tensor or list of Tensors.') elem_shapes = [elem.shape.as_list() for elem in elems] # Fall back on tf.map_fn if shapes of each entry of `elems` are None or fail # to all be the same size along the batch dimension. for elem_shape in elem_shapes: if (not elem_shape or not elem_shape[0] or elem_shape[0] != elem_shapes[0][0]): return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop) arg_tuples = zip(*[tf.unstack(elem) for elem in elems]) outputs = [fn(arg_tuple) for arg_tuple in arg_tuples] else: if not isinstance(elems, tf.Tensor): raise ValueError('`elems` must be a Tensor or list of Tensors.') elems_shape = elems.shape.as_list() if not elems_shape or not elems_shape[0]: return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop) outputs = [fn(arg) for arg in tf.unstack(elems)] # Stack `outputs`, which is a list of Tensors or list of lists of Tensors if all([isinstance(output, tf.Tensor) for output in outputs]): return tf.stack(outputs) else: if all([isinstance(output, list) for output in outputs]): if all([all( [isinstance(entry, tf.Tensor) for entry in output_list]) for output_list in outputs]): return [tf.stack(output_tuple) for output_tuple in zip(*outputs)] raise ValueError('`fn` should return a Tensor or a list of Tensors.') def check_min_image_dim(min_dim, image_tensor): """Checks that the image width/height are greater than some number. This function is used to check that the width and height of an image are above a certain value. If the image shape is static, this function will perform the check at graph construction time. Otherwise, if the image shape varies, an Assertion control dependency will be added to the graph. Args: min_dim: The minimum number of pixels along the width and height of the image. image_tensor: The image tensor to check size for. Returns: If `image_tensor` has dynamic size, return `image_tensor` with a Assert control dependency. Otherwise returns image_tensor. Raises: ValueError: if `image_tensor`'s' width or height is smaller than `min_dim`. """ image_shape = image_tensor.get_shape() image_height = static_shape.get_height(image_shape) image_width = static_shape.get_width(image_shape) if image_height is None or image_width is None: shape_assert = tf.Assert( tf.logical_and(tf.greater_equal(tf.shape(image_tensor)[1], min_dim), tf.greater_equal(tf.shape(image_tensor)[2], min_dim)), ['image size must be >= {} in both height and width.'.format(min_dim)]) with tf.control_dependencies([shape_assert]): return tf.identity(image_tensor) if image_height < min_dim or image_width < min_dim: raise ValueError( 'image size must be >= %d in both height and width; image dim = %d,%d' % (min_dim, image_height, image_width)) return image_tensor def assert_shape_equal(shape_a, shape_b): """Asserts that shape_a and shape_b are equal. If the shapes are static, raises a ValueError when the shapes mismatch. If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes mismatch. Args: shape_a: a list containing shape of the first tensor. shape_b: a list containing shape of the second tensor. Returns: Either a tf.no_op() when shapes are all static and a tf.assert_equal() op when the shapes are dynamic. Raises: ValueError: When shapes are both static and unequal. """ if (all(isinstance(dim, int) for dim in shape_a) and all(isinstance(dim, int) for dim in shape_b)): if shape_a != shape_b: raise ValueError('Unequal shapes {}, {}'.format(shape_a, shape_b)) else: return tf.no_op() else: return tf.assert_equal(shape_a, shape_b) def assert_shape_equal_along_first_dimension(shape_a, shape_b): """Asserts that shape_a and shape_b are the same along the 0th-dimension. If the shapes are static, raises a ValueError when the shapes mismatch. If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes mismatch. Args: shape_a: a list containing shape of the first tensor. shape_b: a list containing shape of the second tensor. Returns: Either a tf.no_op() when shapes are all static and a tf.assert_equal() op when the shapes are dynamic. Raises: ValueError: When shapes are both static and unequal. """ if isinstance(shape_a[0], int) and isinstance(shape_b[0], int): if shape_a[0] != shape_b[0]: raise ValueError('Unequal first dimension {}, {}'.format( shape_a[0], shape_b[0])) else: return tf.no_op() else: return tf.assert_equal(shape_a[0], shape_b[0])
[ "tensorflow.concat", "tensorflow.range", "tensorflow.greater", "tensorflow.shape", "tensorflow.stack", "tensorflow.zeros", "tensorflow.control_dependencies", "tensorflow.identity", "tensorflow.expand_dims", "tensorflow.assert_equal", "tensorflow.unstack", "tensorflow.map_fn", "tensorflow.no_op", "tensorflow.rank" ]
object_detection/utils/shape_utils.py
[(64, 'tensorflow.rank', 'tf.rank', (['t'], {}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.shape', 'tf.shape', (['t'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.expand_dims', 'tf.expand_dims', (['(length - t_d0)', '(0)'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.shape', 'tf.shape', (['tensor'], {}), True, 'import tensorflow as tf\n'), (235, 'utils.static_shape.get_height', 'static_shape.get_height', (['image_shape'], {}), False, 'from utils import static_shape\n'), (236, 'utils.static_shape.get_width', 'static_shape.get_width', (['image_shape'], {}), False, 'from utils import static_shape\n'), (69, 'tensorflow.greater', 'tf.greater', (['t_rank', '(1)'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.range', 'tf.range', (['length'], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.stack', 'tf.stack', (['outputs'], {}), True, 'import tensorflow as tf\n'), (279, 'tensorflow.assert_equal', 'tf.assert_equal', (['shape_a', 'shape_b'], {}), True, 'import tensorflow as tf\n'), (308, 'tensorflow.assert_equal', 'tf.assert_equal', (['shape_a[0]', 'shape_b[0]'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.concat', 'tf.concat', (['[pad_d0, t_shape[1:]]', '(0)'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.expand_dims', 'tf.expand_dims', (['(length - t_d0)', '(0)'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.zeros', 'tf.zeros', (['pad_shape'], {'dtype': 't.dtype'}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.map_fn', 'tf.map_fn', (['fn', 'elems', 'dtype', 'parallel_iterations', 'back_prop'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[shape_assert]'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.identity', 'tf.identity', (['image_tensor'], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (306, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.shape', 'tf.shape', (['t'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.map_fn', 'tf.map_fn', (['fn', 'elems', 'dtype', 'parallel_iterations', 'back_prop'], {}), True, 'import tensorflow as tf\n'), (201, 'tensorflow.unstack', 'tf.unstack', (['elems'], {}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.unstack', 'tf.unstack', (['elem'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.stack', 'tf.stack', (['output_tuple'], {}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.shape', 'tf.shape', (['image_tensor'], {}), True, 'import tensorflow as tf\n'), (240, 'tensorflow.shape', 'tf.shape', (['image_tensor'], {}), True, 'import tensorflow as tf\n')]
myelintek/tensorpack
8d5ae5cc2cfcf2e4e53b4d1064ac9e727f736d09
#!/usr/bin/env python # -*- coding: UTF-8 -*- # File: load-cpm.py # Author: Yuxin Wu <[email protected]> import cv2 import tensorflow as tf import numpy as np import argparse from tensorpack import * from tensorpack.utils import viz from tensorpack.utils.argtools import memoized """ 15 channels: 0-1 head, neck 2-4 right shoulder, right elbow, right wrist 5-7 left shoulder, left elbow, left wrist 8-10 right hip, right knee, right ankle 11-13 left hip, left knee, left ankle 14: background """ def colorize(img, heatmap): """ img: bgr, [0,255] heatmap: [0,1] """ heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1] return img * 0.5 + heatmap * 0.5 @memoized def get_gaussian_map(): gaussian_map = np.zeros((368, 368), dtype='float32') for x_p in range(368): for y_p in range(368): dist_sq = (x_p - 368 / 2) * (x_p - 368 / 2) + \ (y_p - 368 / 2) * (y_p - 368 / 2) exponent = dist_sq / 2.0 / (21**2) gaussian_map[y_p, x_p] = np.exp(-exponent) return gaussian_map.reshape((1, 368, 368, 1)) def CPM(image): image = image / 256.0 - 0.5 gmap = tf.constant(get_gaussian_map()) gmap = tf.pad(gmap, [[0, 0], [0, 1], [0, 1], [0, 0]]) pool_center = AvgPooling('mappool', gmap, 9, stride=8, padding='VALID') with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, W_init=tf.random_normal_initializer(stddev=0.01)): shared = (LinearWrap(image) .Conv2D('conv1_1', 64) .Conv2D('conv1_2', 64) .MaxPooling('pool1', 2) # 184 .Conv2D('conv2_1', 128) .Conv2D('conv2_2', 128) .MaxPooling('pool2', 2) # 92 .Conv2D('conv3_1', 256) .Conv2D('conv3_2', 256) .Conv2D('conv3_3', 256) .Conv2D('conv3_4', 256) .MaxPooling('pool3', 2) # 46 .Conv2D('conv4_1', 512) .Conv2D('conv4_2', 512) .Conv2D('conv4_3_CPM', 256) .Conv2D('conv4_4_CPM', 256) .Conv2D('conv4_5_CPM', 256) .Conv2D('conv4_6_CPM', 256) .Conv2D('conv4_7_CPM', 128)()) def add_stage(stage, l): l = tf.concat([l, shared, pool_center], 3, name='concat_stage{}'.format(stage)) for i in range(1, 6): l = Conv2D('Mconv{}_stage{}'.format(i, stage), l, 128) l = Conv2D('Mconv6_stage{}'.format(stage), l, 128, kernel_shape=1) l = Conv2D('Mconv7_stage{}'.format(stage), l, 15, kernel_shape=1, nl=tf.identity) return l with argscope(Conv2D, kernel_shape=7, nl=tf.nn.relu): out1 = (LinearWrap(shared) .Conv2D('conv5_1_CPM', 512, kernel_shape=1) .Conv2D('conv5_2_CPM', 15, kernel_shape=1, nl=tf.identity)()) out2 = add_stage(2, out1) out3 = add_stage(3, out2) out4 = add_stage(4, out3) out5 = add_stage(5, out4) out6 = add_stage(6, out5) tf.image.resize_bilinear(out6, [368, 368], name='resized_map') def run_test(model_path, img_file): param_dict = np.load(model_path, encoding='latin1').item() predict_func = OfflinePredictor(PredictConfig( inputs_desc=[InputDesc(tf.float32, (None, 368, 368, 3), 'input')], tower_func=CPM, session_init=DictRestore(param_dict), input_names=['input'], output_names=['resized_map'] )) im = cv2.imread(img_file, cv2.IMREAD_COLOR).astype('float32') im = cv2.resize(im, (368, 368)) out = predict_func(im[None, :, :, :])[0][0] hm = out[:, :, :14].sum(axis=2) viz = colorize(im, hm) cv2.imwrite("output.jpg", viz) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--load', required=True, help='.npy model file') parser.add_argument('--input', required=True, help='input image') args = parser.parse_args() run_test(args.load, args.input)
[ "tensorflow.image.resize_bilinear", "tensorflow.random_normal_initializer", "tensorflow.pad", "numpy.load", "numpy.exp", "numpy.zeros" ]
examples/ConvolutionalPoseMachines/load-cpm.py
[(36, 'numpy.zeros', 'np.zeros', (['(368, 368)'], {'dtype': '"""float32"""'}), True, 'import numpy as np\n'), (50, 'tensorflow.pad', 'tf.pad', (['gmap', '[[0, 0], [0, 1], [0, 1], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (110, 'cv2.resize', 'cv2.resize', (['im', '(368, 368)'], {}), False, 'import cv2\n'), (114, 'cv2.imwrite', 'cv2.imwrite', (['"""output.jpg"""', 'viz'], {}), False, 'import cv2\n'), (118, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (96, 'tensorflow.image.resize_bilinear', 'tf.image.resize_bilinear', (['out6', '[368, 368]'], {'name': '"""resized_map"""'}), True, 'import tensorflow as tf\n'), (42, 'numpy.exp', 'np.exp', (['(-exponent)'], {}), True, 'import numpy as np\n'), (100, 'numpy.load', 'np.load', (['model_path'], {'encoding': '"""latin1"""'}), True, 'import numpy as np\n'), (109, 'cv2.imread', 'cv2.imread', (['img_file', 'cv2.IMREAD_COLOR'], {}), False, 'import cv2\n'), (53, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': '(0.01)'}), True, 'import tensorflow as tf\n')]
myelintek/tensorpack
8d5ae5cc2cfcf2e4e53b4d1064ac9e727f736d09
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: CycleGAN.py # Author: Yuxin Wu <[email protected]> import os import argparse import glob from six.moves import range from tensorpack import * from tensorpack.tfutils.summary import add_moving_summary from tensorpack.tfutils.scope_utils import auto_reuse_variable_scope import tensorflow as tf from GAN import GANTrainer, GANModelDesc """ 1. Download the dataset following the original project: https://github.com/junyanz/CycleGAN#train 2. ./CycleGAN.py --data /path/to/datasets/horse2zebra Training and testing visualizations will be in tensorboard. This implementation doesn't use fake sample buffer. It's not hard to add but I didn't observe any difference with it. """ SHAPE = 256 BATCH = 1 TEST_BATCH = 32 NF = 64 # channel size def INReLU(x, name=None): x = InstanceNorm('inorm', x) return tf.nn.relu(x, name=name) def INLReLU(x, name=None): x = InstanceNorm('inorm', x) return LeakyReLU(x, name=name) class Model(GANModelDesc): def _get_inputs(self): return [InputDesc(tf.float32, (None, SHAPE, SHAPE, 3), 'inputA'), InputDesc(tf.float32, (None, SHAPE, SHAPE, 3), 'inputB')] @staticmethod def build_res_block(x, name, chan, first=False): with tf.variable_scope(name): input = x return (LinearWrap(x) .tf.pad([[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC') .Conv2D('conv0', chan, padding='VALID') .tf.pad([[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC') .Conv2D('conv1', chan, padding='VALID', nl=tf.identity) .InstanceNorm('inorm')()) + input @auto_reuse_variable_scope def generator(self, img): assert img is not None with argscope([Conv2D, Deconv2D], nl=INReLU, kernel_shape=3): l = (LinearWrap(img) .tf.pad([[0, 0], [0, 0], [3, 3], [3, 3]], mode='SYMMETRIC') .Conv2D('conv0', NF, kernel_shape=7, padding='VALID') .Conv2D('conv1', NF * 2, stride=2) .Conv2D('conv2', NF * 4, stride=2)()) for k in range(9): l = Model.build_res_block(l, 'res{}'.format(k), NF * 4, first=(k == 0)) l = (LinearWrap(l) .Deconv2D('deconv0', NF * 2, stride=2) .Deconv2D('deconv1', NF * 1, stride=2) .tf.pad([[0, 0], [0, 0], [3, 3], [3, 3]], mode='SYMMETRIC') .Conv2D('convlast', 3, kernel_shape=7, padding='VALID', nl=tf.tanh, use_bias=True)()) return l @auto_reuse_variable_scope def discriminator(self, img): with argscope(Conv2D, nl=INLReLU, kernel_shape=4, stride=2): l = (LinearWrap(img) .Conv2D('conv0', NF, nl=LeakyReLU) .Conv2D('conv1', NF * 2) .Conv2D('conv2', NF * 4) .Conv2D('conv3', NF * 8, stride=1) .Conv2D('conv4', 1, stride=1, nl=tf.identity, use_bias=True)()) return l def _build_graph(self, inputs): A, B = inputs with tf.name_scope('preprocess'): A = tf.transpose(A / 128.0 - 1.0, [0, 3, 1, 2]) B = tf.transpose(B / 128.0 - 1.0, [0, 3, 1, 2]) def viz3(name, a, b, c): with tf.name_scope(name): im = tf.concat([a, b, c], axis=3) im = tf.transpose(im, [0, 2, 3, 1]) im = (im + 1.0) * 128 im = tf.clip_by_value(im, 0, 255) im = tf.cast(im, tf.uint8, name='viz') tf.summary.image(name, im, max_outputs=50) # use the initializers from torch with argscope([Conv2D, Deconv2D], use_bias=False, W_init=tf.random_normal_initializer(stddev=0.02)), \ argscope([Conv2D, Deconv2D, InstanceNorm], data_format='NCHW'), \ argscope(LeakyReLU, alpha=0.2): with tf.variable_scope('gen'): with tf.variable_scope('B'): AB = self.generator(A) with tf.variable_scope('A'): BA = self.generator(B) ABA = self.generator(AB) with tf.variable_scope('B'): BAB = self.generator(BA) viz3('A_recon', A, AB, ABA) viz3('B_recon', B, BA, BAB) with tf.variable_scope('discrim'): with tf.variable_scope('A'): A_dis_real = self.discriminator(A) A_dis_fake = self.discriminator(BA) with tf.variable_scope('B'): B_dis_real = self.discriminator(B) B_dis_fake = self.discriminator(AB) def LSGAN_losses(real, fake): d_real = tf.reduce_mean(tf.squared_difference(real, 1), name='d_real') d_fake = tf.reduce_mean(tf.square(fake), name='d_fake') d_loss = tf.multiply(d_real + d_fake, 0.5, name='d_loss') g_loss = tf.reduce_mean(tf.squared_difference(fake, 1), name='g_loss') add_moving_summary(g_loss, d_loss) return g_loss, d_loss with tf.name_scope('losses'): with tf.name_scope('LossA'): # reconstruction loss recon_loss_A = tf.reduce_mean(tf.abs(A - ABA), name='recon_loss') # gan loss G_loss_A, D_loss_A = LSGAN_losses(A_dis_real, A_dis_fake) with tf.name_scope('LossB'): recon_loss_B = tf.reduce_mean(tf.abs(B - BAB), name='recon_loss') G_loss_B, D_loss_B = LSGAN_losses(B_dis_real, B_dis_fake) LAMBDA = 10.0 self.g_loss = tf.add((G_loss_A + G_loss_B), (recon_loss_A + recon_loss_B) * LAMBDA, name='G_loss_total') self.d_loss = tf.add(D_loss_A, D_loss_B, name='D_loss_total') self.collect_variables('gen', 'discrim') add_moving_summary(recon_loss_A, recon_loss_B, self.g_loss, self.d_loss) def _get_optimizer(self): lr = tf.get_variable('learning_rate', initializer=2e-4, trainable=False) return tf.train.AdamOptimizer(lr, beta1=0.5, epsilon=1e-3) def get_data(datadir, isTrain=True): if isTrain: augs = [ imgaug.Resize(int(SHAPE * 1.12)), imgaug.RandomCrop(SHAPE), imgaug.Flip(horiz=True), ] else: augs = [imgaug.Resize(SHAPE)] def get_image_pairs(dir1, dir2): def get_df(dir): files = sorted(glob.glob(os.path.join(dir, '*.jpg'))) df = ImageFromFile(files, channel=3, shuffle=isTrain) return AugmentImageComponent(df, augs) return JoinData([get_df(dir1), get_df(dir2)]) names = ['trainA', 'trainB'] if isTrain else ['testA', 'testB'] df = get_image_pairs(*[os.path.join(datadir, n) for n in names]) df = BatchData(df, BATCH if isTrain else TEST_BATCH) df = PrefetchDataZMQ(df, 2 if isTrain else 1) return df class VisualizeTestSet(Callback): def _setup_graph(self): self.pred = self.trainer.get_predictor( ['inputA', 'inputB'], ['A_recon/viz', 'B_recon/viz']) def _before_train(self): global args self.val_ds = get_data(args.data, isTrain=False) self.val_ds.reset_state() def _trigger(self): idx = 0 for iA, iB in self.val_ds.get_data(): vizA, vizB = self.pred(iA, iB) self.trainer.monitors.put_image('testA-{}'.format(idx), vizA) self.trainer.monitors.put_image('testB-{}'.format(idx), vizB) idx += 1 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--data', required=True, help='the image directory. should contain trainA/trainB/testA/testB') parser.add_argument('--load', help='load model') args = parser.parse_args() logger.auto_set_dir() data = get_data(args.data) data = PrintData(data) GANTrainer(QueueInput(data), Model()).train_with_defaults( callbacks=[ ModelSaver(), ScheduledHyperParamSetter( 'learning_rate', [(100, 2e-4), (200, 0)], interp='linear'), PeriodicTrigger(VisualizeTestSet(), every_k_epochs=3), ], max_epoch=195, steps_per_epoch=data.size(), session_init=SaverRestore(args.load) if args.load else None )
[ "tensorflow.clip_by_value", "tensorflow.nn.relu", "tensorflow.get_variable", "tensorflow.multiply", "tensorflow.transpose", "tensorflow.concat", "tensorflow.summary.image", "tensorflow.cast", "tensorflow.add", "tensorflow.name_scope", "tensorflow.train.AdamOptimizer", "tensorflow.square", "tensorflow.variable_scope", "tensorflow.random_normal_initializer", "tensorflow.squared_difference", "tensorflow.abs" ]
examples/GAN/CycleGAN.py
[(35, 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (206, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (155, 'tensorpack.tfutils.summary.add_moving_summary', 'add_moving_summary', (['recon_loss_A', 'recon_loss_B', 'self.g_loss', 'self.d_loss'], {}), False, 'from tensorpack.tfutils.summary import add_moving_summary\n'), (158, 'tensorflow.get_variable', 'tf.get_variable', (['"""learning_rate"""'], {'initializer': '(0.0002)', 'trainable': '(False)'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['lr'], {'beta1': '(0.5)', 'epsilon': '(0.001)'}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (68, 'six.moves.range', 'range', (['(9)'], {}), False, 'from six.moves import range\n'), (90, 'tensorflow.name_scope', 'tf.name_scope', (['"""preprocess"""'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.transpose', 'tf.transpose', (['(A / 128.0 - 1.0)', '[0, 3, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.transpose', 'tf.transpose', (['(B / 128.0 - 1.0)', '[0, 3, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.summary.image', 'tf.summary.image', (['name', 'im'], {'max_outputs': '(50)'}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.multiply', 'tf.multiply', (['(d_real + d_fake)', '(0.5)'], {'name': '"""d_loss"""'}), True, 'import tensorflow as tf\n'), (135, 'tensorpack.tfutils.summary.add_moving_summary', 'add_moving_summary', (['g_loss', 'd_loss'], {}), False, 'from tensorpack.tfutils.summary import add_moving_summary\n'), (138, 'tensorflow.name_scope', 'tf.name_scope', (['"""losses"""'], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.add', 'tf.add', (['(G_loss_A + G_loss_B)', '((recon_loss_A + recon_loss_B) * LAMBDA)'], {'name': '"""G_loss_total"""'}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.add', 'tf.add', (['D_loss_A', 'D_loss_B'], {'name': '"""D_loss_total"""'}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.concat', 'tf.concat', (['[a, b, c]'], {'axis': '(3)'}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.transpose', 'tf.transpose', (['im', '[0, 2, 3, 1]'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['im', '(0)', '(255)'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.cast', 'tf.cast', (['im', 'tf.uint8'], {'name': '"""viz"""'}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""gen"""'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""discrim"""'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.squared_difference', 'tf.squared_difference', (['real', '(1)'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.square', 'tf.square', (['fake'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.squared_difference', 'tf.squared_difference', (['fake', '(1)'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.name_scope', 'tf.name_scope', (['"""LossA"""'], {}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.name_scope', 'tf.name_scope', (['"""LossB"""'], {}), True, 'import tensorflow as tf\n'), (180, 'os.path.join', 'os.path.join', (['datadir', 'n'], {}), False, 'import os\n'), (105, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': '(0.02)'}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""B"""'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""A"""'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""B"""'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""A"""'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""B"""'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.abs', 'tf.abs', (['(A - ABA)'], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.abs', 'tf.abs', (['(B - BAB)'], {}), True, 'import tensorflow as tf\n'), (174, 'os.path.join', 'os.path.join', (['dir', '"""*.jpg"""'], {}), False, 'import os\n')]
ryangillard/artificial_intelligence
f7c21af221f366b075d351deeeb00a1b266ac3e3
import tensorflow as tf from . import regularization from .print_object import print_obj class Discriminator(object): """Discriminator that takes image input and outputs logits. Fields: name: str, name of `Discriminator`. kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. from_rgb_conv_layers: list, fromRGB 1x1 `Conv2D` layers. conv_layer_blocks: list, lists of `Conv2D` block layers for each block. transition_downsample_layers: list, `AveragePooling2D` layers for downsampling shrinking transition paths. flatten_layer: `Flatten` layer prior to logits layer. logits_layer: `Dense` layer for logits. build_discriminator_tensors: list, tensors used to build layer internals. """ def __init__(self, kernel_regularizer, bias_regularizer, params, name): """Instantiates and builds discriminator network. Args: kernel_regularizer: `l1_l2_regularizer` object, regularizar for kernel variables. bias_regularizer: `l1_l2_regularizer` object, regularizar for bias variables. params: dict, user passed parameters. name: str, name of discriminator. """ # Set name of discriminator. self.name = name # Regularizer for kernel weights. self.kernel_regularizer = kernel_regularizer # Regularizer for bias weights. self.bias_regularizer = bias_regularizer # Instantiate discriminator layers. (self.from_rgb_conv_layers, self.conv_layer_blocks, self.transition_downsample_layers, self.flatten_layer, self.logits_layer) = self.instantiate_discriminator_layers( params ) # Build discriminator layer internals. self.build_discriminator_tensors = self.build_discriminator_layers( params ) def instantiate_discriminator_from_rgb_layers(self, params): """Instantiates discriminator fromRGB layers of 1x1 convs. Args: params: dict, user passed parameters. Returns: List of fromRGB 1x1 Conv2D layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get fromRGB layer properties. from_rgb = [ params["discriminator_from_rgb_layers"][i][0][:] for i in range(len(params["discriminator_from_rgb_layers"])) ] # Create list to hold toRGB 1x1 convs. from_rgb_conv_layers = [ tf.layers.Conv2D( filters=from_rgb[i][3], kernel_size=from_rgb[i][0:2], strides=from_rgb[i][4:6], padding="same", activation=tf.nn.leaky_relu, kernel_initializer="he_normal", kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, name="{}_from_rgb_layers_conv2d_{}_{}x{}_{}_{}".format( self.name, i, from_rgb[i][0], from_rgb[i][1], from_rgb[i][2], from_rgb[i][3] ) ) for i in range(len(from_rgb)) ] print_obj( "\ninstantiate_discriminator_from_rgb_layers", "from_rgb_conv_layers", from_rgb_conv_layers ) return from_rgb_conv_layers def instantiate_discriminator_base_conv_layer_block(self, params): """Instantiates discriminator base conv layer block. Args: params: dict, user passed parameters. Returns: List of base conv layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get conv block layer properties. conv_block = params["discriminator_base_conv_blocks"][0] # Create list of base conv layers. base_conv_layers = [ tf.layers.Conv2D( filters=conv_block[i][3], kernel_size=conv_block[i][0:2], strides=conv_block[i][4:6], padding="same", activation=tf.nn.leaky_relu, kernel_initializer="he_normal", kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, name="{}_base_layers_conv2d_{}_{}x{}_{}_{}".format( self.name, i, conv_block[i][0], conv_block[i][1], conv_block[i][2], conv_block[i][3] ) ) for i in range(len(conv_block) - 1) ] # Have valid padding for layer just before flatten and logits. base_conv_layers.append( tf.layers.Conv2D( filters=conv_block[-1][3], kernel_size=conv_block[-1][0:2], strides=conv_block[-1][4:6], padding="valid", activation=tf.nn.leaky_relu, kernel_initializer="he_normal", kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, name="{}_base_layers_conv2d_{}_{}x{}_{}_{}".format( self.name, len(conv_block) - 1, conv_block[-1][0], conv_block[-1][1], conv_block[-1][2], conv_block[-1][3] ) ) ) print_obj( "\ninstantiate_discriminator_base_conv_layer_block", "base_conv_layers", base_conv_layers ) return base_conv_layers def instantiate_discriminator_growth_layer_block(self, params, block_idx): """Instantiates discriminator growth block layers. Args: params: dict, user passed parameters. block_idx: int, the current growth block's index. Returns: List of growth block layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get conv block layer properties. conv_block = params["discriminator_growth_conv_blocks"][block_idx] # Create new inner convolutional layers. conv_layers = [ tf.layers.Conv2D( filters=conv_block[i][3], kernel_size=conv_block[i][0:2], strides=conv_block[i][4:6], padding="same", activation=tf.nn.leaky_relu, kernel_initializer="he_normal", kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, name="{}_growth_layers_conv2d_{}_{}_{}x{}_{}_{}".format( self.name, block_idx, i, conv_block[i][0], conv_block[i][1], conv_block[i][2], conv_block[i][3] ) ) for i in range(len(conv_block)) ] print_obj( "\ninstantiate_discriminator_growth_layer_block", "conv_layers", conv_layers ) # Down sample from 2s X 2s to s X s image. downsampled_image_layer = tf.layers.AveragePooling2D( pool_size=(2, 2), strides=(2, 2), name="{}_growth_downsampled_image_{}".format( self.name, block_idx ) ) print_obj( "instantiate_discriminator_growth_layer_block", "downsampled_image_layer", downsampled_image_layer ) return conv_layers + [downsampled_image_layer] def instantiate_discriminator_growth_transition_downsample_layers( self, params): """Instantiates discriminator growth transition downsample layers. Args: params: dict, user passed parameters. Returns: List of growth transition downsample layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Down sample from 2s X 2s to s X s image. downsample_layers = [ tf.layers.AveragePooling2D( pool_size=(2, 2), strides=(2, 2), name="{}_growth_transition_downsample_layer_{}".format( self.name, layer_idx ) ) for layer_idx in range( 1 + len(params["discriminator_growth_conv_blocks"]) ) ] print_obj( "\ninstantiate_discriminator_growth_transition_downsample_layers", "downsample_layers", downsample_layers ) return downsample_layers def instantiate_discriminator_logits_layer(self): """Instantiates discriminator flatten and logits layers. Returns: Flatten and logits layers of discriminator. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Flatten layer to ready final block conv tensor for dense layer. flatten_layer = tf.layers.Flatten( name="{}_flatten_layer".format(self.name) ) print_obj( "\ncreate_discriminator_logits_layer", "flatten_layer", flatten_layer ) # Final linear layer for logits. logits_layer = tf.layers.Dense( units=1, activation=None, kernel_regularizer=self.kernel_regularizer, bias_regularizer=self.bias_regularizer, name="{}_layers_dense_logits".format(self.name) ) print_obj( "create_growth_transition_discriminator_network", "logits_layer", logits_layer ) return flatten_layer, logits_layer def instantiate_discriminator_layers(self, params): """Instantiates layers of discriminator network. Args: params: dict, user passed parameters. Returns: from_rgb_conv_layers: list, fromRGB 1x1 `Conv2D` layers. conv_layer_blocks: list, lists of `Conv2D` block layers for each block. transition_downsample_layers: list, `AveragePooling2D` layers for downsampling shrinking transition paths. flatten_layer: `Flatten` layer prior to logits layer. logits_layer: `Dense` layer for logits. """ # Instantiate fromRGB 1x1 `Conv2D` layers. from_rgb_conv_layers = self.instantiate_discriminator_from_rgb_layers( params=params ) print_obj( "instantiate_discriminator_layers", "from_rgb_conv_layers", from_rgb_conv_layers ) # Instantiate base conv block's `Conv2D` layers, for post-growth. conv_layer_blocks = [ self.instantiate_discriminator_base_conv_layer_block( params=params ) ] # Instantiate growth `Conv2D` layer blocks. conv_layer_blocks.extend( [ self.instantiate_discriminator_growth_layer_block( params=params, block_idx=block_idx ) for block_idx in range( len(params["discriminator_growth_conv_blocks"]) ) ] ) print_obj( "instantiate_discriminator_layers", "conv_layer_blocks", conv_layer_blocks ) # Instantiate transition downsample `AveragePooling2D` layers. transition_downsample_layers = ( self.instantiate_discriminator_growth_transition_downsample_layers( params=params ) ) print_obj( "instantiate_discriminator_layers", "transition_downsample_layers", transition_downsample_layers ) # Instantiate `Flatten` and `Dense` logits layers. (flatten_layer, logits_layer) = self.instantiate_discriminator_logits_layer() print_obj( "instantiate_discriminator_layers", "flatten_layer", flatten_layer ) print_obj( "instantiate_discriminator_layers", "logits_layer", logits_layer ) return (from_rgb_conv_layers, conv_layer_blocks, transition_downsample_layers, flatten_layer, logits_layer) ########################################################################## ########################################################################## ########################################################################## def build_discriminator_from_rgb_layers(self, params): """Creates discriminator fromRGB layers of 1x1 convs. Args: params: dict, user passed parameters. Returns: List of tensors from fromRGB 1x1 `Conv2D` layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get fromRGB layer properties. from_rgb = [ params["discriminator_from_rgb_layers"][i][0][:] for i in range(len(params["discriminator_from_rgb_layers"])) ] # Create list to hold fromRGB 1x1 convs. from_rgb_conv_tensors = [ self.from_rgb_conv_layers[i]( inputs=tf.zeros( shape=[1] + from_rgb[i][0:3], dtype=tf.float32 ) ) for i in range(len(from_rgb)) ] print_obj( "\nbuild_discriminator_from_rgb_layers", "from_rgb_conv_tensors", from_rgb_conv_tensors ) return from_rgb_conv_tensors def build_discriminator_base_conv_layer_block(self, params): """Creates discriminator base conv layer block. Args: params: dict, user passed parameters. Returns: List of tensors from base `Conv2D` layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get conv block layer properties. conv_block = params["discriminator_base_conv_blocks"][0] # The base conv block is always the 0th one. base_conv_layer_block = self.conv_layer_blocks[0] # Minibatch stddev comes before first base conv layer, # creating 1 extra feature map. if params["use_minibatch_stddev"]: # Therefore, the number of input channels will be 1 higher # for first base conv block. num_in_channels = conv_block[0][3] + 1 else: num_in_channels = conv_block[0][3] # Get first base conv layer from list. first_base_conv_layer = base_conv_layer_block[0] # Build first layer with bigger tensor. base_conv_tensors = [ first_base_conv_layer( inputs=tf.zeros( shape=[1] + conv_block[0][0:2] + [num_in_channels], dtype=tf.float32 ) ) ] # Now build the rest of the base conv block layers, store in list. base_conv_tensors.extend( [ base_conv_layer_block[i]( inputs=tf.zeros( shape=[1] + conv_block[i][0:3], dtype=tf.float32 ) ) for i in range(1, len(conv_block)) ] ) print_obj( "\nbuild_discriminator_base_conv_layer_block", "base_conv_tensors", base_conv_tensors ) return base_conv_tensors def build_discriminator_growth_layer_block(self, params, block_idx): """Creates discriminator growth block. Args: params: dict, user passed parameters. block_idx: int, the current growth block's index. Returns: List of tensors from growth block `Conv2D` layers. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Get conv block layer properties. conv_block = params["discriminator_growth_conv_blocks"][block_idx] # Create new inner convolutional layers. conv_tensors = [ self.conv_layer_blocks[1 + block_idx][i]( inputs=tf.zeros( shape=[1] + conv_block[i][0:3], dtype=tf.float32 ) ) for i in range(len(conv_block)) ] print_obj( "\nbuild_discriminator_growth_layer_block", "conv_tensors", conv_tensors ) return conv_tensors def build_discriminator_logits_layer(self, params): """Builds flatten and logits layer internals using call. Args: params: dict, user passed parameters. Returns: Final logits tensor of discriminator. """ with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): block_conv_size = params["discriminator_base_conv_blocks"][-1][-1][3] # Flatten final block conv tensor. block_conv_flat = self.flatten_layer( inputs=tf.zeros( shape=[1, 1, 1, block_conv_size], dtype=tf.float32 ) ) print_obj( "\nbuild_discriminator_logits_layer", "block_conv_flat", block_conv_flat ) # Final linear layer for logits. logits = self.logits_layer(inputs=block_conv_flat) print_obj("build_discriminator_logits_layer", "logits", logits) return logits def build_discriminator_layers(self, params): """Builds discriminator layer internals. Args: params: dict, user passed parameters. Returns: Logits tensor. """ # Build fromRGB 1x1 `Conv2D` layers internals through call. from_rgb_conv_tensors = self.build_discriminator_from_rgb_layers( params=params ) print_obj( "\nbuild_discriminator_layers", "from_rgb_conv_tensors", from_rgb_conv_tensors ) with tf.control_dependencies(control_inputs=from_rgb_conv_tensors): # Create base convolutional block's layer internals using call. conv_block_tensors = [ self.build_discriminator_base_conv_layer_block( params=params ) ] # Build growth `Conv2D` layer block internals through call. conv_block_tensors.extend( [ self.build_discriminator_growth_layer_block( params=params, block_idx=block_idx ) for block_idx in range( len(params["discriminator_growth_conv_blocks"]) ) ] ) # Flatten conv block tensor lists of lists into list. conv_block_tensors = [ item for sublist in conv_block_tensors for item in sublist ] print_obj( "build_discriminator_layers", "conv_block_tensors", conv_block_tensors ) with tf.control_dependencies(control_inputs=conv_block_tensors): # Build logits layer internals using call. logits_tensor = self.build_discriminator_logits_layer( params=params ) print_obj( "build_discriminator_layers", "logits_tensor", logits_tensor ) return logits_tensor ########################################################################## ########################################################################## ########################################################################## def minibatch_stddev_common( self, variance, tile_multiples, params, caller): """Adds minibatch stddev feature map to image using grouping. This is the code that is common between the grouped and ungroup minibatch stddev functions. Args: variance: tensor, variance of minibatch or minibatch groups. tile_multiples: list, length 4, used to tile input to final shape input_dims[i] * mutliples[i]. params: dict, user passed parameters. caller: str, name of the calling function. Returns: Minibatch standard deviation feature map image added to channels of shape [cur_batch_size, image_size, image_size, 1]. """ with tf.variable_scope( "{}/{}_minibatch_stddev".format(self.name, caller)): # Calculate standard deviation over the group plus small epsilon. # shape = ( # {"grouped": cur_batch_size / group_size, "ungrouped": 1}, # image_size, # image_size, # num_channels # ) stddev = tf.sqrt( x=variance + 1e-8, name="{}_stddev".format(caller) ) print_obj( "minibatch_stddev_common", "{}_stddev".format(caller), stddev ) # Take average over feature maps and pixels. if params["minibatch_stddev_averaging"]: # grouped shape = (cur_batch_size / group_size, 1, 1, 1) # ungrouped shape = (1, 1, 1, 1) stddev = tf.reduce_mean( input_tensor=stddev, axis=[1, 2, 3], keepdims=True, name="{}_stddev_average".format(caller) ) print_obj( "minibatch_stddev_common", "{}_stddev_average".format(caller), stddev ) # Replicate over group and pixels. # shape = ( # cur_batch_size, # image_size, # image_size, # 1 # ) stddev_feature_map = tf.tile( input=stddev, multiples=tile_multiples, name="{}_stddev_feature_map".format(caller) ) print_obj( "minibatch_stddev_common", "{}_stddev_feature_map".format(caller), stddev_feature_map ) return stddev_feature_map def grouped_minibatch_stddev( self, X, cur_batch_size, static_image_shape, params, group_size): """Adds minibatch stddev feature map to image using grouping. Args: X: tf.float32 tensor, image of shape [cur_batch_size, image_size, image_size, num_channels]. cur_batch_size: tf.int64 tensor, the dynamic batch size (in case of partial batch). static_image_shape: list, the static shape of each image. params: dict, user passed parameters. group_size: int, size of image groups. Returns: Minibatch standard deviation feature map image added to channels of shape [cur_batch_size, image_size, image_size, 1]. """ with tf.variable_scope( "{}/grouped_minibatch_stddev".format(self.name)): # The group size should be less than or equal to the batch size. # shape = () group_size = tf.minimum( x=group_size, y=cur_batch_size, name="group_size" ) print_obj("grouped_minibatch_stddev", "group_size", group_size) # Split minibatch into M groups of size group_size, rank 5 tensor. # shape = ( # group_size, # cur_batch_size / group_size, # image_size, # image_size, # num_channels # ) grouped_image = tf.reshape( tensor=X, shape=[group_size, -1] + static_image_shape, name="grouped_image" ) print_obj( "grouped_minibatch_stddev", "grouped_image", grouped_image ) # Find the mean of each group. # shape = ( # 1, # cur_batch_size / group_size, # image_size, # image_size, # num_channels # ) grouped_mean = tf.reduce_mean( input_tensor=grouped_image, axis=0, keepdims=True, name="grouped_mean" ) print_obj( "grouped_minibatch_stddev", "grouped_mean", grouped_mean ) # Center each group using the mean. # shape = ( # group_size, # cur_batch_size / group_size, # image_size, # image_size, # num_channels # ) centered_grouped_image = tf.subtract( x=grouped_image, y=grouped_mean, name="centered_grouped_image" ) print_obj( "grouped_minibatch_stddev", "centered_grouped_image", centered_grouped_image ) # Calculate variance over group. # shape = ( # cur_batch_size / group_size, # image_size, # image_size, # num_channels # ) grouped_variance = tf.reduce_mean( input_tensor=tf.square(x=centered_grouped_image), axis=0, name="grouped_variance" ) print_obj( "grouped_minibatch_stddev", "grouped_variance", grouped_variance ) # Get stddev image using ops common to both grouped & ungrouped. stddev_feature_map = self.minibatch_stddev_common( variance=grouped_variance, tile_multiples=[group_size] + static_image_shape[0:2] + [1], params=params, caller="grouped" ) print_obj( "grouped_minibatch_stddev", "stddev_feature_map", stddev_feature_map ) return stddev_feature_map def ungrouped_minibatch_stddev( self, X, cur_batch_size, static_image_shape, params): """Adds minibatch stddev feature map added to image channels. Args: X: tensor, image of shape [cur_batch_size, image_size, image_size, num_channels]. cur_batch_size: tf.int64 tensor, the dynamic batch size (in case of partial batch). static_image_shape: list, the static shape of each image. params: dict, user passed parameters. Returns: Minibatch standard deviation feature map image added to channels of shape [cur_batch_size, image_size, image_size, 1]. """ with tf.variable_scope( "{}/ungrouped_minibatch_stddev".format(self.name)): # Find the mean of each group. # shape = ( # 1, # image_size, # image_size, # num_channels # ) mean = tf.reduce_mean( input_tensor=X, axis=0, keepdims=True, name="mean" ) print_obj("ungrouped_minibatch_stddev", "mean", mean) # Center each group using the mean. # shape = ( # cur_batch_size, # image_size, # image_size, # num_channels # ) centered_image = tf.subtract( x=X, y=mean, name="centered_image" ) print_obj( "ungrouped_minibatch_stddev", "centered_image", centered_image ) # Calculate variance over group. # shape = ( # 1, # image_size, # image_size, # num_channels # ) variance = tf.reduce_mean( input_tensor=tf.square(x=centered_image), axis=0, keepdims=True, name="variance" ) print_obj( "ungrouped_minibatch_stddev", "variance", variance ) # Get stddev image using ops common to both grouped & ungrouped. stddev_feature_map = self.minibatch_stddev_common( variance=variance, tile_multiples=[cur_batch_size] + static_image_shape[0:2] + [1], params=params, caller="ungrouped" ) print_obj( "ungrouped_minibatch_stddev", "stddev_feature_map", stddev_feature_map ) return stddev_feature_map def minibatch_stddev(self, X, params, group_size=4): """Adds minibatch stddev feature map added to image. Args: X: tensor, image of shape [cur_batch_size, image_size, image_size, num_channels]. params: dict, user passed parameters. group_size: int, size of image groups. Returns: Image with minibatch standard deviation feature map added to channels of shape [cur_batch_size, image_size, image_size, num_channels + 1]. """ with tf.variable_scope("{}/minibatch_stddev".format(self.name)): # Get dynamic shape of image. # shape = (4,) dynamic_image_shape = tf.shape( input=X, name="dynamic_image_shape" ) print_obj( "\nminibatch_stddev", "dynamic_image_shape", dynamic_image_shape ) # Extract current batch size (in case this is a partial batch). cur_batch_size = dynamic_image_shape[0] # Get static shape of image. # shape = (3,) static_image_shape = params["generator_projection_dims"] print_obj( "minibatch_stddev", "static_image_shape", static_image_shape ) # cur_batch_size must be divisible by or smaller than group_size. divisbility_condition = tf.equal( x=tf.mod(x=cur_batch_size, y=group_size), y=0, name="divisbility_condition" ) less_than_condition = tf.less( x=cur_batch_size, y=group_size, name="less_than_condition" ) any_condition = tf.reduce_any( input_tensor=[divisbility_condition, less_than_condition], name="any_condition" ) # Get minibatch stddev feature map image from grouped or # ungrouped branch. stddev_feature_map = tf.cond( pred=any_condition, true_fn=lambda: self.grouped_minibatch_stddev( X=X, cur_batch_size=cur_batch_size, static_image_shape=static_image_shape, params=params, group_size=group_size ), false_fn=lambda: self.ungrouped_minibatch_stddev( X=X, cur_batch_size=cur_batch_size, static_image_shape=static_image_shape, params=params ), name="stddev_feature_map_cond" ) # Append to image as new feature map. # shape = ( # cur_batch_size, # image_size, # image_size, # num_channels + 1 # ) appended_image = tf.concat( values=[X, stddev_feature_map], axis=-1, name="appended_image" ) print_obj( "minibatch_stddev_common", "appended_image", appended_image ) return appended_image def use_discriminator_logits_layer(self, block_conv, params): """Uses flatten and logits layers to get logits tensor. Args: block_conv: tensor, output of last conv layer of discriminator. flatten_layer: `Flatten` layer. logits_layer: `Dense` layer for logits. params: dict, user passed parameters. Returns: Final logits tensor of discriminator. """ print_obj( "\nuse_discriminator_logits_layer", "block_conv", block_conv ) # Set shape to remove ambiguity for dense layer. height, width = params["generator_projection_dims"][0:2] valid_kernel_size = ( params["discriminator_base_conv_blocks"][0][-1][0] ) block_conv.set_shape( [ block_conv.get_shape()[0], height - valid_kernel_size + 1, width - valid_kernel_size + 1, block_conv.get_shape()[-1]] ) print_obj("use_discriminator_logits_layer", "block_conv", block_conv) with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Flatten final block conv tensor. block_conv_flat = self.flatten_layer(inputs=block_conv) print_obj( "use_discriminator_logits_layer", "block_conv_flat", block_conv_flat ) # Final linear layer for logits. logits = self.logits_layer(inputs=block_conv_flat) print_obj("use_discriminator_logits_layer", "logits", logits) return logits def create_base_discriminator_network(self, X, params): """Creates base discriminator network. Args: X: tensor, input image to discriminator. params: dict, user passed parameters. Returns: Final logits tensor of discriminator. """ print_obj("\ncreate_base_discriminator_network", "X", X) with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Only need the first fromRGB conv layer & block for base network. from_rgb_conv_layer = self.from_rgb_conv_layers[0] block_layers = self.conv_layer_blocks[0] # Pass inputs through layer chain. from_rgb_conv = from_rgb_conv_layer(inputs=X) print_obj( "create_base_discriminator_network", "from_rgb_conv", from_rgb_conv ) if params["use_minibatch_stddev"]: block_conv = self.minibatch_stddev( X=from_rgb_conv, params=params, group_size=params["minibatch_stddev_group_size"] ) else: block_conv = from_rgb_conv for i in range(len(block_layers)): block_conv = block_layers[i](inputs=block_conv) print_obj( "create_base_discriminator_network", "block_conv", block_conv ) # Get logits now. logits = self.use_discriminator_logits_layer( block_conv=block_conv, params=params ) print_obj("create_base_discriminator_network", "logits", logits) return logits def create_growth_transition_discriminator_network( self, X, alpha_var, params, trans_idx): """Creates growth transition discriminator network. Args: X: tensor, input image to discriminator. alpha_var: variable, alpha for weighted sum of fade-in of layers. params: dict, user passed parameters. trans_idx: int, index of current growth transition. Returns: Final logits tensor of discriminator. """ print_obj( "\nEntered create_growth_transition_discriminator_network", "trans_idx", trans_idx ) print_obj("create_growth_transition_discriminator_network", "X", X) with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Growing side chain. growing_from_rgb_conv_layer = self.from_rgb_conv_layers[trans_idx + 1] growing_block_layers = self.conv_layer_blocks[trans_idx + 1] # Pass inputs through layer chain. growing_block_conv = growing_from_rgb_conv_layer(inputs=X) print_obj( "\ncreate_growth_transition_discriminator_network", "growing_block_conv", growing_block_conv ) for i in range(len(growing_block_layers)): growing_block_conv = growing_block_layers[i]( inputs=growing_block_conv ) print_obj( "create_growth_transition_discriminator_network", "growing_block_conv", growing_block_conv ) # Shrinking side chain. transition_downsample_layer = self.transition_downsample_layers[trans_idx] shrinking_from_rgb_conv_layer = self.from_rgb_conv_layers[trans_idx] # Pass inputs through layer chain. transition_downsample = transition_downsample_layer(inputs=X) print_obj( "create_growth_transition_discriminator_network", "transition_downsample", transition_downsample ) shrinking_from_rgb_conv = shrinking_from_rgb_conv_layer( inputs=transition_downsample ) print_obj( "create_growth_transition_discriminator_network", "shrinking_from_rgb_conv", shrinking_from_rgb_conv ) # Weighted sum. weighted_sum = tf.add( x=growing_block_conv * alpha_var, y=shrinking_from_rgb_conv * (1.0 - alpha_var), name="{}_growth_transition_weighted_sum_{}".format( self.name, trans_idx ) ) print_obj( "create_growth_transition_discriminator_network", "weighted_sum", weighted_sum ) # Permanent blocks. permanent_blocks = self.conv_layer_blocks[0:trans_idx + 1] # Reverse order of blocks and flatten. permanent_block_layers = [ item for sublist in permanent_blocks[::-1] for item in sublist ] # Pass inputs through layer chain. block_conv = weighted_sum # Find number of permanent growth conv layers. num_perm_growth_conv_layers = len(permanent_block_layers) num_perm_growth_conv_layers -= len(params["conv_num_filters"][0]) # Loop through only the permanent growth conv layers. for i in range(num_perm_growth_conv_layers): block_conv = permanent_block_layers[i](inputs=block_conv) print_obj( "create_growth_transition_discriminator_network", "block_conv_{}".format(i), block_conv ) if params["use_minibatch_stddev"]: block_conv = self.minibatch_stddev( X=block_conv, params=params, group_size=params["minibatch_stddev_group_size"] ) print_obj( "create_growth_transition_discriminator_network", "minibatch_stddev_block_conv", block_conv ) # Loop through only the permanent base conv layers now. for i in range( num_perm_growth_conv_layers, len(permanent_block_layers)): block_conv = permanent_block_layers[i](inputs=block_conv) print_obj( "create_growth_transition_discriminator_network", "block_conv_{}".format(i), block_conv ) # Get logits now. logits = self.use_discriminator_logits_layer( block_conv=block_conv, params=params ) print_obj( "create_growth_transition_discriminator_network", "logits", logits ) return logits def create_final_discriminator_network(self, X, params): """Creates final discriminator network. Args: X: tensor, input image to discriminator. params: dict, user passed parameters. Returns: Final logits tensor of discriminator. """ print_obj("\ncreate_final_discriminator_network", "X", X) with tf.variable_scope(name_or_scope=self.name, reuse=tf.AUTO_REUSE): # Only need the last fromRGB conv layer. from_rgb_conv_layer = self.from_rgb_conv_layers[-1] # Reverse order of blocks. reversed_blocks = self.conv_layer_blocks[::-1] # Flatten list of lists block layers into list. block_layers = [ item for sublist in reversed_blocks for item in sublist ] # Pass inputs through layer chain. block_conv = from_rgb_conv_layer(inputs=X) print_obj( "\ncreate_final_discriminator_network", "block_conv", block_conv ) # Find number of permanent growth conv layers. num_growth_conv_layers = len(block_layers) num_growth_conv_layers -= len(params["conv_num_filters"][0]) # Loop through only the permanent growth conv layers. for i in range(num_growth_conv_layers): block_conv = block_layers[i](inputs=block_conv) print_obj( "create_final_discriminator_network", "block_conv_{}".format(i), block_conv ) if params["use_minibatch_stddev"]: block_conv = self.minibatch_stddev( X=block_conv, params=params, group_size=params["minibatch_stddev_group_size"] ) print_obj( "create_final_discriminator_network", "minibatch_stddev_block_conv", block_conv ) # Loop through only the permanent base conv layers now. for i in range(num_growth_conv_layers, len(block_layers)): block_conv = block_layers[i](inputs=block_conv) print_obj( "create_final_discriminator_network", "block_conv_{}".format(i), block_conv ) # Get logits now. logits = self.use_discriminator_logits_layer( block_conv=block_conv, params=params ) print_obj("create_final_discriminator_network", "logits", logits) return logits ########################################################################## ########################################################################## ########################################################################## def switch_case_discriminator_logits( self, X, alpha_var, params, growth_index): """Uses switch case to use the correct network to get logits. Args: X: tensor, image tensors of shape [cur_batch_size, image_size, image_size, depth]. alpha_var: variable, alpha for weighted sum of fade-in of layers. params: dict, user passed parameters. growth_index: int, current growth stage. Returns: Logits tensor of shape [cur_batch_size, 1]. """ # Switch to case based on number of steps to get logits. logits = tf.switch_case( branch_index=growth_index, branch_fns=[ # 4x4 lambda: self.create_base_discriminator_network( X=X, params=params ), # 8x8 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(0, len(params["conv_num_filters"]) - 2) ), # 16x16 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(1, len(params["conv_num_filters"]) - 2) ), # 32x32 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(2, len(params["conv_num_filters"]) - 2) ), # 64x64 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(3, len(params["conv_num_filters"]) - 2) ), # 128x128 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(4, len(params["conv_num_filters"]) - 2) ), # 256x256 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(5, len(params["conv_num_filters"]) - 2) ), # 512x512 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(6, len(params["conv_num_filters"]) - 2) ), # 1024x1024 lambda: self.create_growth_transition_discriminator_network( X=X, alpha_var=alpha_var, params=params, trans_idx=min(7, len(params["conv_num_filters"]) - 2) ), # 1024x1024 lambda: self.create_final_discriminator_network( X=X, params=params ) ], name="{}_switch_case_logits".format(self.name) ) return logits ########################################################################## ########################################################################## ########################################################################## def get_discriminator_logits(self, X, alpha_var, params): """Uses discriminator network and returns logits for train/eval. Args: X: tensor, image tensors of shape [cur_batch_size, image_size, image_size, depth]. alpha_var: variable, alpha for weighted sum of fade-in of layers. params: dict, user passed parameters. Returns: Logits tensor of shape [cur_batch_size, 1]. """ print_obj("\nget_discriminator_logits", "X", X) # Get discriminator's logits tensor. train_steps = params["train_steps"] + params["prev_train_steps"] num_steps_until_growth = params["num_steps_until_growth"] num_stages = train_steps // num_steps_until_growth if (num_stages <= 0 or len(params["conv_num_filters"]) == 1): print( "\nget_discriminator_logits: NOT GOING TO GROW, SKIP SWITCH CASE!" ) # If never going to grow, no sense using the switch case. # 4x4 logits = self.create_base_discriminator_network( X=X, params=params ) else: # Find growth index based on global step and growth frequency. growth_index = tf.cast( x=tf.floordiv( x=tf.train.get_or_create_global_step(), y=params["num_steps_until_growth"], name="{}_global_step_floordiv".format(self.name) ), dtype=tf.int32, name="{}_growth_index".format(self.name) ) # Switch to case based on number of steps for logits. logits = self.switch_case_discriminator_logits( X=X, alpha_var=alpha_var, params=params, growth_index=growth_index ) print_obj( "\nget_discriminator_logits", "logits", logits ) # Wrap logits in a control dependency for the build discriminator # tensors to ensure discriminator internals are built. with tf.control_dependencies( control_inputs=[self.build_discriminator_tensors]): logits = tf.identity( input=logits, name="{}_logits_identity".format(self.name) ) return logits ########################################################################## ########################################################################## ########################################################################## def get_gradient_penalty_loss( self, cur_batch_size, fake_images, real_images, alpha_var, params): """Gets discriminator gradient penalty loss. Args: cur_batch_size: tensor, in case of a partial batch instead of using the user passed int. fake_images: tensor, images generated by the generator from random noise of shape [cur_batch_size, image_size, image_size, 3]. real_images: tensor, real images from input of shape [cur_batch_size, image_size, image_size, 3]. alpha_var: variable, alpha for weighted sum of fade-in of layers. params: dict, user passed parameters. Returns: Discriminator's gradient penalty loss of shape []. """ func_name = "get_gradient_penalty_loss" with tf.name_scope(name="{}/gradient_penalty".format(self.name)): # Get a random uniform number rank 4 tensor. random_uniform_num = tf.random.uniform( shape=[cur_batch_size, 1, 1, 1], minval=0., maxval=1., dtype=tf.float32, name="random_uniform_num" ) print_obj( "\n" + func_name, "random_uniform_num", random_uniform_num ) # Find the element-wise difference between images. image_difference = fake_images - real_images print_obj(func_name, "image_difference", image_difference) # Get random samples from this mixed image distribution. mixed_images = random_uniform_num * image_difference mixed_images += real_images print_obj(func_name, "mixed_images", mixed_images) # Send to the discriminator to get logits. mixed_logits = self.get_discriminator_logits( X=mixed_images, alpha_var=alpha_var, params=params ) print_obj(func_name, "mixed_logits", mixed_logits) # Get the mixed loss. mixed_loss = tf.reduce_sum( input_tensor=mixed_logits, name="mixed_loss" ) print_obj(func_name, "mixed_loss", mixed_loss) # Get gradient from returned list of length 1. mixed_gradients = tf.gradients( ys=mixed_loss, xs=[mixed_images], name="gradients" )[0] print_obj(func_name, "mixed_gradients", mixed_gradients) # Get gradient's L2 norm. mixed_norms = tf.sqrt( x=tf.reduce_sum( input_tensor=tf.square( x=mixed_gradients, name="squared_grads" ), axis=[1, 2, 3] ) + 1e-8 ) print_obj(func_name, "mixed_norms", mixed_norms) # Get squared difference from target of 1.0. squared_difference = tf.square( x=mixed_norms - 1.0, name="squared_difference" ) print_obj(func_name, "squared_difference", squared_difference) # Get gradient penalty scalar. gradient_penalty = tf.reduce_mean( input_tensor=squared_difference, name="gradient_penalty" ) print_obj(func_name, "gradient_penalty", gradient_penalty) # Multiply with lambda to get gradient penalty loss. gradient_penalty_loss = tf.multiply( x=params["discriminator_gradient_penalty_coefficient"], y=gradient_penalty, name="gradient_penalty_loss" ) return gradient_penalty_loss def get_discriminator_loss( self, cur_batch_size, fake_images, real_images, fake_logits, real_logits, alpha_var, params): """Gets discriminator loss. Args: cur_batch_size: tensor, in case of a partial batch instead of using the user passed int. fake_images: tensor, images generated by the generator from random noise of shape [cur_batch_size, image_size, image_size, 3]. real_images: tensor, real images from input of shape [cur_batch_size, image_size, image_size, 3]. fake_logits: tensor, shape of [cur_batch_size, 1] that came from discriminator having processed generator's output image. fake_logits: tensor, shape of [cur_batch_size, 1] that came from discriminator having processed real image. alpha_var: variable, alpha for weighted sum of fade-in of layers. params: dict, user passed parameters. Returns: Discriminator's total loss tensor of shape []. """ # Calculate base discriminator loss. discriminator_real_loss = tf.reduce_mean( input_tensor=real_logits, name="{}_real_loss".format(self.name) ) print_obj( "\nget_discriminator_loss", "discriminator_real_loss", discriminator_real_loss ) discriminator_generated_loss = tf.reduce_mean( input_tensor=fake_logits, name="{}_generated_loss".format(self.name) ) print_obj( "get_discriminator_loss", "discriminator_generated_loss", discriminator_generated_loss ) discriminator_loss = tf.add( x=discriminator_real_loss, y=-discriminator_generated_loss, name="{}_loss".format(self.name) ) print_obj( "get_discriminator_loss", "discriminator_loss", discriminator_loss ) # Get discriminator gradient penalty loss. discriminator_gradient_penalty = self.get_gradient_penalty_loss( cur_batch_size=cur_batch_size, fake_images=fake_images, real_images=real_images, alpha_var=alpha_var, params=params ) print_obj( "get_discriminator_loss", "discriminator_gradient_penalty", discriminator_gradient_penalty ) # Get discriminator epsilon drift penalty. epsilon_drift_penalty = tf.multiply( x=params["epsilon_drift"], y=tf.reduce_mean(input_tensor=tf.square(x=real_logits)), name="epsilon_drift_penalty" ) print_obj( "get_discriminator_loss", "epsilon_drift_penalty", epsilon_drift_penalty ) # Get discriminator Wasserstein GP loss. discriminator_wasserstein_gp_loss = tf.add_n( inputs=[ discriminator_loss, discriminator_gradient_penalty, epsilon_drift_penalty ], name="{}_wasserstein_gp_loss".format(self.name) ) print_obj( "get_discriminator_loss", "discriminator_wasserstein_gp_loss", discriminator_wasserstein_gp_loss ) # Get discriminator regularization losses. discriminator_reg_loss = regularization.get_regularization_loss( lambda1=params["discriminator_l1_regularization_scale"], lambda2=params["discriminator_l2_regularization_scale"], scope=self.name ) print_obj( "get_discriminator_loss", "discriminator_reg_loss", discriminator_reg_loss ) # Combine losses for total losses. discriminator_total_loss = tf.add( x=discriminator_wasserstein_gp_loss, y=discriminator_reg_loss, name="{}_total_loss".format(self.name) ) print_obj( "get_discriminator_loss", "discriminator_total_loss", discriminator_total_loss ) return discriminator_total_loss
[ "tensorflow.multiply", "tensorflow.concat", "tensorflow.control_dependencies", "tensorflow.reduce_mean", "tensorflow.shape", "tensorflow.less", "tensorflow.reduce_any", "tensorflow.reshape", "tensorflow.minimum", "tensorflow.random.uniform", "tensorflow.reduce_sum", "tensorflow.subtract", "tensorflow.gradients", "tensorflow.zeros", "tensorflow.mod", "tensorflow.train.get_or_create_global_step", "tensorflow.square", "tensorflow.variable_scope" ]
machine_learning/gan/pgan/tf_pgan/pgan_module/trainer/discriminator.py
[(69, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (392, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (425, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (483, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (513, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (554, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'from_rgb_conv_tensors'}), True, 'import tensorflow as tf\n'), (703, 'tensorflow.minimum', 'tf.minimum', ([], {'x': 'group_size', 'y': 'cur_batch_size', 'name': '"""group_size"""'}), True, 'import tensorflow as tf\n'), (716, 'tensorflow.reshape', 'tf.reshape', ([], {'tensor': 'X', 'shape': '([group_size, -1] + static_image_shape)', 'name': '"""grouped_image"""'}), True, 'import tensorflow as tf\n'), (735, 'tensorflow.reduce_mean', 'tf.reduce_mean', ([], {'input_tensor': 'grouped_image', 'axis': '(0)', 'keepdims': '(True)', 'name': '"""grouped_mean"""'}), True, 'import tensorflow as tf\n'), (753, 'tensorflow.subtract', 'tf.subtract', ([], {'x': 'grouped_image', 'y': 'grouped_mean', 'name': '"""centered_grouped_image"""'}), True, 'import tensorflow as tf\n'), (825, 'tensorflow.reduce_mean', 'tf.reduce_mean', ([], {'input_tensor': 'X', 'axis': '(0)', 'keepdims': '(True)', 'name': '"""mean"""'}), True, 'import tensorflow as tf\n'), (837, 'tensorflow.subtract', 'tf.subtract', ([], {'x': 'X', 'y': 'mean', 'name': '"""centered_image"""'}), True, 'import tensorflow as tf\n'), (897, 'tensorflow.shape', 'tf.shape', ([], {'input': 'X', 'name': '"""dynamic_image_shape"""'}), True, 'import tensorflow as tf\n'), (923, 'tensorflow.less', 'tf.less', ([], {'x': 'cur_batch_size', 'y': 'group_size', 'name': '"""less_than_condition"""'}), True, 'import tensorflow as tf\n'), (927, 'tensorflow.reduce_any', 'tf.reduce_any', ([], {'input_tensor': '[divisbility_condition, less_than_condition]', 'name': '"""any_condition"""'}), True, 'import tensorflow as tf\n'), (959, 'tensorflow.concat', 'tf.concat', ([], {'values': '[X, stddev_feature_map]', 'axis': '(-1)', 'name': '"""appended_image"""'}), True, 'import tensorflow as tf\n'), (1001, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (1027, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (1085, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (1210, 'tensorflow.variable_scope', 'tf.variable_scope', ([], {'name_or_scope': 'self.name', 'reuse': 'tf.AUTO_REUSE'}), True, 'import tensorflow as tf\n'), (1422, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': '[self.build_discriminator_tensors]'}), True, 'import tensorflow as tf\n'), (1460, 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[cur_batch_size, 1, 1, 1]', 'minval': '(0.0)', 'maxval': '(1.0)', 'dtype': 'tf.float32', 'name': '"""random_uniform_num"""'}), True, 'import tensorflow as tf\n'), (1486, 'tensorflow.reduce_sum', 'tf.reduce_sum', ([], {'input_tensor': 'mixed_logits', 'name': '"""mixed_loss"""'}), True, 'import tensorflow as tf\n'), (1513, 'tensorflow.square', 'tf.square', ([], {'x': '(mixed_norms - 1.0)', 'name': '"""squared_difference"""'}), True, 'import tensorflow as tf\n'), (1520, 'tensorflow.reduce_mean', 'tf.reduce_mean', ([], {'input_tensor': 'squared_difference', 'name': '"""gradient_penalty"""'}), True, 'import tensorflow as tf\n'), (1526, 'tensorflow.multiply', 'tf.multiply', ([], {'x': "params['discriminator_gradient_penalty_coefficient']", 'y': 'gradient_penalty', 'name': '"""gradient_penalty_loss"""'}), True, 'import tensorflow as tf\n'), (584, 'tensorflow.control_dependencies', 'tf.control_dependencies', ([], {'control_inputs': 'conv_block_tensors'}), True, 'import tensorflow as tf\n'), (1493, 'tensorflow.gradients', 'tf.gradients', ([], {'ys': 'mixed_loss', 'xs': '[mixed_images]', 'name': '"""gradients"""'}), True, 'import tensorflow as tf\n'), (518, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '[1, 1, 1, block_conv_size]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (770, 'tensorflow.square', 'tf.square', ([], {'x': 'centered_grouped_image'}), True, 'import tensorflow as tf\n'), (854, 'tensorflow.square', 'tf.square', ([], {'x': 'centered_image'}), True, 'import tensorflow as tf\n'), (918, 'tensorflow.mod', 'tf.mod', ([], {'x': 'cur_batch_size', 'y': 'group_size'}), True, 'import tensorflow as tf\n'), (402, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '([1] + from_rgb[i][0:3])', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (447, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '([1] + conv_block[0][0:2] + [num_in_channels])', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (490, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '([1] + conv_block[i][0:3])', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (1610, 'tensorflow.square', 'tf.square', ([], {'x': 'real_logits'}), True, 'import tensorflow as tf\n'), (458, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '([1] + conv_block[i][0:3])', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (1400, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (1503, 'tensorflow.square', 'tf.square', ([], {'x': 'mixed_gradients', 'name': '"""squared_grads"""'}), True, 'import tensorflow as tf\n')]
ValentinMouret/probability
7ea6cc55e5b3fed04372cd188cd0764e92fd3cf4
# 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. # ============================================================================ """Multivariate Normal distribution class initialized with a full covariance.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_probability.python.distributions import mvn_tril from tensorflow_probability.python.internal import dtype_util from tensorflow.python.ops import control_flow_ops __all__ = [ "MultivariateNormalFullCovariance", ] class MultivariateNormalFullCovariance(mvn_tril.MultivariateNormalTriL): """The multivariate normal distribution on `R^k`. The Multivariate Normal distribution is defined over `R^k` and parameterized by a (batch of) length-`k` `loc` vector (aka "mu") and a (batch of) `k x k` `covariance_matrix` matrices that are the covariance. This is different than the other multivariate normals, which are parameterized by a matrix more akin to the standard deviation. #### Mathematical Details The probability density function (pdf) is, with `@` as matrix multiplication, ```none pdf(x; loc, covariance_matrix) = exp(-0.5 y) / Z, y = (x - loc)^T @ inv(covariance_matrix) @ (x - loc) Z = (2 pi)**(0.5 k) |det(covariance_matrix)|**(0.5). ``` where: * `loc` is a vector in `R^k`, * `covariance_matrix` is an `R^{k x k}` symmetric positive definite matrix, * `Z` denotes the normalization constant. Additional leading dimensions (if any) in `loc` and `covariance_matrix` allow for batch dimensions. The MultivariateNormal distribution is a member of the [location-scale family](https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed e.g. as, ```none X ~ MultivariateNormal(loc=0, scale=1) # Identity scale, zero shift. scale = Cholesky(covariance_matrix) Y = scale @ X + loc ``` #### Examples ```python tfd = tfp.distributions # Initialize a single 3-variate Gaussian. mu = [1., 2, 3] cov = [[ 0.36, 0.12, 0.06], [ 0.12, 0.29, -0.13], [ 0.06, -0.13, 0.26]] mvn = tfd.MultivariateNormalFullCovariance( loc=mu, covariance_matrix=cov) mvn.mean().eval() # ==> [1., 2, 3] # Covariance agrees with covariance_matrix. mvn.covariance().eval() # ==> [[ 0.36, 0.12, 0.06], # [ 0.12, 0.29, -0.13], # [ 0.06, -0.13, 0.26]] # Compute the pdf of an observation in `R^3` ; return a scalar. mvn.prob([-1., 0, 1]).eval() # shape: [] # Initialize a 2-batch of 3-variate Gaussians. mu = [[1., 2, 3], [11, 22, 33]] # shape: [2, 3] covariance_matrix = ... # shape: [2, 3, 3], symmetric, positive definite. mvn = tfd.MultivariateNormalFullCovariance( loc=mu, covariance=covariance_matrix) # Compute the pdf of two `R^3` observations; return a length-2 vector. x = [[-0.9, 0, 0.1], [-10, 0, 9]] # shape: [2, 3] mvn.prob(x).eval() # shape: [2] ``` """ def __init__(self, loc=None, covariance_matrix=None, validate_args=False, allow_nan_stats=True, name="MultivariateNormalFullCovariance"): """Construct Multivariate Normal distribution on `R^k`. The `batch_shape` is the broadcast shape between `loc` and `covariance_matrix` arguments. The `event_shape` is given by last dimension of the matrix implied by `covariance_matrix`. The last dimension of `loc` (if provided) must broadcast with this. A non-batch `covariance_matrix` matrix is a `k x k` symmetric positive definite matrix. In other words it is (real) symmetric with all eigenvalues strictly positive. Additional leading dimensions (if any) will index batches. Args: loc: Floating-point `Tensor`. If this is set to `None`, `loc` is implicitly `0`. When specified, may have shape `[B1, ..., Bb, k]` where `b >= 0` and `k` is the event size. covariance_matrix: Floating-point, symmetric positive definite `Tensor` of same `dtype` as `loc`. The strict upper triangle of `covariance_matrix` is ignored, so if `covariance_matrix` is not symmetric no error will be raised (unless `validate_args is True`). `covariance_matrix` has shape `[B1, ..., Bb, k, k]` where `b >= 0` and `k` is the event size. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: ValueError: if neither `loc` nor `covariance_matrix` are specified. """ parameters = dict(locals()) # Convert the covariance_matrix up to a scale_tril and call MVNTriL. with tf.name_scope(name) as name: with tf.name_scope("init", values=[loc, covariance_matrix]): dtype = dtype_util.common_dtype([loc, covariance_matrix], tf.float32) loc = loc if loc is None else tf.convert_to_tensor( loc, name="loc", dtype=dtype) if covariance_matrix is None: scale_tril = None else: covariance_matrix = tf.convert_to_tensor( covariance_matrix, name="covariance_matrix", dtype=dtype) if validate_args: covariance_matrix = control_flow_ops.with_dependencies([ tf.assert_near( covariance_matrix, tf.matrix_transpose(covariance_matrix), message="Matrix was not symmetric") ], covariance_matrix) # No need to validate that covariance_matrix is non-singular. # LinearOperatorLowerTriangular has an assert_non_singular method that # is called by the Bijector. # However, cholesky() ignores the upper triangular part, so we do need # to separately assert symmetric. scale_tril = tf.cholesky(covariance_matrix) super(MultivariateNormalFullCovariance, self).__init__( loc=loc, scale_tril=scale_tril, validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=name) self._parameters = parameters
[ "tensorflow.convert_to_tensor", "tensorflow.matrix_transpose", "tensorflow.name_scope", "tensorflow.cholesky" ]
tensorflow_probability/python/distributions/mvn_full_covariance.py
[(159, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.name_scope', 'tf.name_scope', (['"""init"""'], {'values': '[loc, covariance_matrix]'}), True, 'import tensorflow as tf\n'), (161, 'tensorflow_probability.python.internal.dtype_util.common_dtype', 'dtype_util.common_dtype', (['[loc, covariance_matrix]', 'tf.float32'], {}), False, 'from tensorflow_probability.python.internal import dtype_util\n'), (162, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['loc'], {'name': '"""loc"""', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['covariance_matrix'], {'name': '"""covariance_matrix"""', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.cholesky', 'tf.cholesky', (['covariance_matrix'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.matrix_transpose', 'tf.matrix_transpose', (['covariance_matrix'], {}), True, 'import tensorflow as tf\n')]
rmunoz12/tensorpack
60f4c6df7c4a27b553469352dd6ce73333db1ec6
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: tower.py import tensorflow as tf from six.moves import zip from ..utils import logger from ..utils.argtools import call_only_once from ..utils.naming import MOVING_SUMMARY_OPS_KEY from ..utils.develop import HIDE_DOC from .collection import CollectionGuard from .common import get_tf_version_number, get_op_or_tensor_by_name, get_op_tensor_name __all__ = ['get_current_tower_context', 'TowerContext', 'TowerFuncWrapper', 'TowerTensorHandle', 'TowerTensorHandles'] _CurrentTowerContext = None class TowerContext(object): """ A context where the current model is being built in. """ def __init__(self, tower_name, is_training, index=0, vs_name=''): """ Args: tower_name (str): The name scope of the tower. is_training (bool): index (int): index of this tower, only used in training. vs_name (str): Open a new variable scope with this name. """ self._name = tower_name self._is_training = bool(is_training) if not self._is_training: assert index == 0, \ "TowerContext(index) is only valid in training!" self._index = int(index) self._vs_name = vs_name if len(vs_name): assert len(tower_name), "TowerContext(vs_name) cannot be used with an empty tower_name!" self._initial_vs_reuse = tf.get_variable_scope().reuse if self.has_own_variables: assert not self._initial_vs_reuse, \ "Cannot create tower {} with reuse=True!".format(tower_name) self._collection_guard = CollectionGuard( self._name, check_diff=not self.is_main_training_tower, freeze_keys=self._keys_to_freeze()) @property def is_main_training_tower(self): return self.is_training and self._index == 0 @property def is_training(self): return self._is_training @property def has_own_variables(self): """ Whether this tower is supposed to have its own variables. """ return self.is_main_training_tower or \ (self.is_training and len(self._vs_name) > 0) or \ (not self.is_training and not self._initial_vs_reuse) @property def name(self): return self._name @property def vs_name(self): return self._vs_name @property def ns_name(self): return self._name def get_collection_in_tower(self, key): """ Get items from this collection that are added in the current tower. """ return self._collection_guard.get_collection_in_tower(key) # TODO currently only used in StagingInput @property def index(self): return self._index @call_only_once def _get_scopes(self): if not len(self._name): # work around https://github.com/tensorflow/tensorflow/issues/14703 return [tf.variable_scope(tf.get_variable_scope())] ret = [] # either the Tower was originally created with reuse, # or a training tower without vs has to use reuse. reuse = (self.is_training and self._index > 0 and not self.has_own_variables) or self._initial_vs_reuse if len(self._vs_name): ret.append(tf.variable_scope(self._vs_name, reuse=reuse)) else: if reuse: ret.append(tf.variable_scope( tf.get_variable_scope(), reuse=True)) else: # work around https://github.com/tensorflow/tensorflow/issues/14703 ret.append(tf.variable_scope(tf.get_variable_scope())) # always clear existing ns # TODO check existing ns if len(self._name) and self._name != self._vs_name: ret.append(tf.name_scope(self._name + '/')) return ret def _keys_to_freeze(self): if self.is_main_training_tower: return [] if self.is_training: return [tf.GraphKeys.SUMMARIES, MOVING_SUMMARY_OPS_KEY] # freeze UPDATE_OPS during inference because they should never be used return [tf.GraphKeys.SUMMARIES, MOVING_SUMMARY_OPS_KEY, tf.GraphKeys.UPDATE_OPS] def __enter__(self): global _CurrentTowerContext assert _CurrentTowerContext is None, "Cannot nest TowerContext!" _CurrentTowerContext = self if self.is_training: curr_vs = tf.get_variable_scope() assert curr_vs.name == '', "In training, cannot nest TowerContext with an existing variable scope!" self._ctxs = self._get_scopes() self._ctxs.append(self._collection_guard) for c in self._ctxs: c.__enter__() if get_tf_version_number() >= 1.2: # check that ns_name is always the same as _name ns = tf.get_default_graph().get_name_scope() assert ns == self._name, \ "Name conflict: name_scope inside tower '{}' becomes '{}'!".format(self._name, ns) \ + " You may need a different name for the tower!" return self def __exit__(self, exc_type, exc_val, exc_tb): global _CurrentTowerContext _CurrentTowerContext = None if not self.has_own_variables: diff_trainable_vars = self._collection_guard.get_collection_in_tower(tf.GraphKeys.TRAINABLE_VARIABLES) assert len(diff_trainable_vars) == 0, \ "New TRAINABLE_VARIABLES shouldn't be created in {}: ".format( self._name) + ', '.join([k.name for k in diff_trainable_vars]) for c in self._ctxs[::-1]: c.__exit__(exc_type, exc_val, exc_tb) return False def __str__(self): return "TowerContext(name={}, is_training={})".format( self._name, self._is_training) def get_current_tower_context(): return _CurrentTowerContext class TowerFuncWrapper(object): """ A wrapper around a tower function (function which builds one tower, i.e. one replicate of the model). It keeps track of the name scope, variable scope and input/output tensors each time the function is called. :class:`TowerTrainer` needs this so that it knows how to build a predictor. """ def __init__(self, tower_fn, inputs_desc): """ Args: tower_func: a function which builds one tower in the graph. It takes several input tensors and could return anything. inputs_desc ([InputDesc]): use this to figure out the right name for the input tensors. """ assert callable(tower_fn), tower_fn inputs_desc_names = [k.name for k in inputs_desc] assert len(set(inputs_desc_names)) == len(inputs_desc_names), \ "Duplicated names in inputs_desc! " + str(inputs_desc_names) self._tower_fn = tower_fn self._inputs_desc = inputs_desc self._handles = [] def __new__(cls, tower_fn, inputs_desc): # to avoid double-wrapping a function if isinstance(tower_fn, TowerFuncWrapper): return tower_fn else: return super(TowerFuncWrapper, cls).__new__(cls) def __call__(self, *args): ctx = get_current_tower_context() assert ctx is not None, "Function must be called under TowerContext!" output = self._tower_fn(*args) handle = TowerTensorHandle(ctx, args, output, self._inputs_desc) self._handles.append(handle) return output @property def towers(self): """ Returns: a :class:`TowerTensorHandles` object, that can access the tower handles by either indices or names. """ return TowerTensorHandles(self._handles) @property def inputs_desc(self): return self._inputs_desc class TowerTensorHandles(object): """ Wrap a list of :class:`TowerTensorHandle`, to support access to them by index or names. """ def __init__(self, handles): self._handles = handles self._name_to_handle = {k.ns_name: k for k in handles} def __getitem__(self, name_or_index): """ Args: name_or_index (str or int): Returns: a :class:`TowerTensorHandle`. """ if isinstance(name_or_index, int): return self._handles[name_or_index] return self._name_to_handle[name_or_index] def training(self): """ Returns: A :class:`TowerTensorHandles`, containing only the training towers. """ handles = [h for h in self._handles if h.is_training] return TowerTensorHandles(handles) def inference(self): """ Returns: A :class:`TowerTensorHandles`, containing only the inference towers. """ handles = [h for h in self._handles if not h.is_training] return TowerTensorHandles(handles) class TowerTensorHandle(object): """ When a function is called multiple times under each tower, it becomes hard to keep track of the scope and access those tensors in each tower. This class provides easy access to the tensors as well as the inputs/outputs created in each tower. """ @HIDE_DOC def __init__(self, ctx, input, output, inputs_desc=None): self._ctx = ctx self._extra_tensor_names = {} if inputs_desc is not None: assert len(inputs_desc) == len(input) self._extra_tensor_names = { get_op_tensor_name(x.name)[1]: y for x, y in zip(inputs_desc, input)} self._input = input self._output = output @property def vs_name(self): return self._ctx.vs_name @property def ns_name(self): return self._ctx.ns_name def get_tensor(self, name): """ Get a tensor in this tower. The name can be: 1. The name of the tensor without any tower prefix. 2. The name of an :class:`InputDesc`, if it is used when building the tower. """ name = get_op_tensor_name(name)[1] if len(self.ns_name): name_with_ns = self.ns_name + "/" + name else: name_with_ns = name try: ret = get_op_or_tensor_by_name(name_with_ns) except KeyError: if name in self._extra_tensor_names: return self._extra_tensor_names[name] raise else: if name in self._extra_tensor_names: logger.warn( "'{}' may refer to both the tensor '{}' or the input '{}'.".format( name, ret.name, self._extra_tensor_names[name].name) + "Assuming it is the tensor '{}'.".format(ret.name)) return ret def get_tensors(self, names): return [self.get_tensor(name) for name in names] def __getitem__(self, name): return self.get_tensor(name) def get_variable(self, name): """ Get a variable used in this tower. """ name = get_op_tensor_name(name)[1] if len(self.vs_name): name_with_vs = self.vs_name + "/" + name else: name_with_vs = name return get_op_or_tensor_by_name(name_with_vs) @property def input(self): """ The list of input tensors used to build the tower. """ return self._input @property def output(self): """ The output returned by the tower function. """ return self._output @property def is_training(self): return self._ctx.is_training
[ "tensorflow.variable_scope", "tensorflow.get_default_graph", "tensorflow.get_variable_scope", "tensorflow.name_scope" ]
tensorpack/tfutils/tower.py
[(45, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.variable_scope', 'tf.variable_scope', (['self._vs_name'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.name_scope', 'tf.name_scope', (["(self._name + '/')"], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (281, 'six.moves.zip', 'zip', (['inputs_desc', 'input'], {}), False, 'from six.moves import zip\n'), (112, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n')]
Soum-Soum/Tensorflow_Face_Finder
fec6c15d2df7012608511ad87f4b55731bf99478
# 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. # ============================================================================== """Utility for batching remote OPs together to reduce RPC overhead.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops class ScheduledOp(object): """Represents a scheduled remote operation.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def batching_key(self): """Returns the key for batching operations.""" @abc.abstractmethod def batch_runner_fn(self): """Returns the function that executes the operation on the batch.""" class ScheduledStampedResourceOp(ScheduledOp): """Wrapper class for batched operations on stamped resources.""" def __init__(self, resource_handle, op, **kwargs): self.resource_handle = resource_handle self.op = op self.args = kwargs def batching_key(self): # We want to group the same operations on the same device and run them in # one batch. So we use (device, operation) as the key. return self.resource_handle.device, self.op def batch_runner_fn(self): return _scheduled_stamp_resource_op_runner def _move_tensors(tensors, device): """Moves a list of tensors to a device by concatenating/splitting them.""" # Reset the device setting to avoid weird interactions with device merging # logic. with ops.device(None): if all(tensor.shape == tensor_shape.scalar() for tensor in tensors): with ops.device(tensors[0].device): values = array_ops.stack(tensors) with ops.device(device): return array_ops.unstack(values) else: with ops.device(tensors[0].device): sizes = array_ops.stack( [array_ops.shape(tensor)[0] for tensor in tensors]) values = array_ops.concat(tensors, axis=0) with ops.device(device): sizes = array_ops.unstack(sizes) return list(array_ops.split(values, sizes, axis=0)) def _scheduled_stamp_resource_op_runner(batch, stamp): """Runs a batch operation on a stamped resource.""" if not batch: return arg_keys = set(batch[0].args.keys()) grouped_args = collections.OrderedDict() resource_handles = [] # Check that the set of arguments is the same across all the scheduled ops. for op in batch: if set(op.args.keys()) != arg_keys: raise ValueError("Mismatching arguments: %s, %s.", op.args, arg_keys) for key in arg_keys: grouped_args.setdefault(key, []).append(op.args[key]) resource_handles.append(op.resource_handle) # Move all the inputs to the op device in one RPC. grouped_args = collections.OrderedDict( (k, _move_tensors(v, resource_handles[0].device)) for k, v in sorted(grouped_args.items())) with ops.device(resource_handles[0].device): return batch[0].op(resource_handles, stamp, **grouped_args) def run_handler_scheduled_ops(per_handler_ops, stamp, worker_device): """Given a dictionary of ops for each handler, runs them in batch.""" batched_ops = collections.OrderedDict() # Group the ops by their batching_key. Ops that share the same batching key # can be executed together. for handler in per_handler_ops.keys(): for op in per_handler_ops[handler]: key = (op.batching_key(), op.batch_runner_fn()) batched_ops.setdefault(key, []).append(op) op_results = {} for batch in batched_ops.values(): # Run each of the batched ops using its runner. results = batch[0].batch_runner_fn()(batch, stamp) # If the result is a tuple, move each entry in the tuple in one RPC. if isinstance(results, tuple): results = tuple( _move_tensors(result, worker_device) for result in results) # Once all the results are on the worker, create individual tuple for # each scheduled op request. for i in range(len(batch)): op_results[batch[i]] = tuple(result[i] for result in results) # If the result is a tuple, it didn't have any outputs, so use the # `ops.Operation` as the result for all the scheduled ops. elif isinstance(results, ops.Operation): for i in range(len(batch)): op_results[batch[i]] = results else: raise ValueError("Unknown type of result %s.", results) handler_results = collections.defaultdict(list) # Dispatch the results of the ScheduledOps to the handlers that requested # them. for handler in per_handler_ops.keys(): for op in per_handler_ops[handler]: handler_results[handler].append(op_results[op]) return handler_results
[ "tensorflow.python.framework.tensor_shape.scalar", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.split", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.array_ops.stack" ]
venv1/Lib/site-packages/tensorflow/contrib/boosted_trees/python/ops/batch_ops_utils.py
[(84, 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), False, 'import collections\n'), (103, 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), False, 'import collections\n'), (129, 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), False, 'import collections\n'), (63, 'tensorflow.python.framework.ops.device', 'ops.device', (['None'], {}), False, 'from tensorflow.python.framework import ops\n'), (97, 'tensorflow.python.framework.ops.device', 'ops.device', (['resource_handles[0].device'], {}), False, 'from tensorflow.python.framework import ops\n'), (65, 'tensorflow.python.framework.ops.device', 'ops.device', (['tensors[0].device'], {}), False, 'from tensorflow.python.framework import ops\n'), (66, 'tensorflow.python.ops.array_ops.stack', 'array_ops.stack', (['tensors'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (67, 'tensorflow.python.framework.ops.device', 'ops.device', (['device'], {}), False, 'from tensorflow.python.framework import ops\n'), (68, 'tensorflow.python.ops.array_ops.unstack', 'array_ops.unstack', (['values'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (70, 'tensorflow.python.framework.ops.device', 'ops.device', (['tensors[0].device'], {}), False, 'from tensorflow.python.framework import ops\n'), (73, 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['tensors'], {'axis': '(0)'}), False, 'from tensorflow.python.ops import array_ops\n'), (74, 'tensorflow.python.framework.ops.device', 'ops.device', (['device'], {}), False, 'from tensorflow.python.framework import ops\n'), (75, 'tensorflow.python.ops.array_ops.unstack', 'array_ops.unstack', (['sizes'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (64, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (76, 'tensorflow.python.ops.array_ops.split', 'array_ops.split', (['values', 'sizes'], {'axis': '(0)'}), False, 'from tensorflow.python.ops import array_ops\n'), (72, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['tensor'], {}), False, 'from tensorflow.python.ops import array_ops\n')]
Soum-Soum/Tensorflow_Face_Finder
fec6c15d2df7012608511ad87f4b55731bf99478
# 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. # ============================================================================== """TargetColumn abstract a single head in the model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.contrib.framework import deprecated from tensorflow.contrib.losses.python.losses import loss_ops from tensorflow.contrib.metrics.python.ops import metric_ops from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def regression_target(label_name=None, weight_column_name=None, label_dimension=1): """Creates a _TargetColumn for linear regression. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). 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. label_dimension: dimension of the target for multilabels. Returns: An instance of _TargetColumn """ return _RegressionTargetColumn( loss_fn=_mean_squared_loss, label_name=label_name, weight_column_name=weight_column_name, label_dimension=label_dimension) # TODO(zakaria): Add logistic_regression_target @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def multi_class_target(n_classes, label_name=None, weight_column_name=None): """Creates a _TargetColumn for multi class single label classification. The target column uses softmax cross entropy loss. Args: n_classes: Integer, number of classes, must be >= 2 label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). 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. Returns: An instance of _MultiClassTargetColumn. Raises: ValueError: if n_classes is < 2 """ if n_classes < 2: raise ValueError("n_classes must be > 1 for classification.") if n_classes == 2: loss_fn = _log_loss_with_two_classes else: loss_fn = _softmax_cross_entropy_loss return _MultiClassTargetColumn( loss_fn=loss_fn, n_classes=n_classes, label_name=label_name, weight_column_name=weight_column_name) @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def binary_svm_target(label_name=None, weight_column_name=None): """Creates a _TargetColumn for binary classification with SVMs. The target column uses binary hinge loss. Args: label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). 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. Returns: An instance of _TargetColumn. """ return _BinarySvmTargetColumn( label_name=label_name, weight_column_name=weight_column_name) @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") class ProblemType(object): UNSPECIFIED = 0 CLASSIFICATION = 1 LINEAR_REGRESSION = 2 LOGISTIC_REGRESSION = 3 class _TargetColumn(object): """_TargetColumn is the abstraction for a single head in a model. Args: loss_fn: a function that returns the loss tensor. num_label_columns: Integer, number of label columns. label_name: String, name of the key in label dict. Can be null if label is a tensor (single headed models). 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. Raises: ValueError: if loss_fn or n_classes are missing. """ def __init__(self, loss_fn, num_label_columns, label_name, weight_column_name, problem_type): if not loss_fn: raise ValueError("loss_fn must be provided") if num_label_columns is None: # n_classes can be 0 raise ValueError("num_label_columns must be provided") self._loss_fn = loss_fn self._num_label_columns = num_label_columns self._label_name = label_name self._weight_column_name = weight_column_name self._problem_type = problem_type def logits_to_predictions(self, logits, proba=False): # Abstrat, Subclasses must implement. raise NotImplementedError() def get_eval_ops(self, features, logits, labels, metrics=None): """Returns eval op.""" raise NotImplementedError @property def label_name(self): return self._label_name @property def weight_column_name(self): return self._weight_column_name @property def num_label_columns(self): return self._num_label_columns def get_weight_tensor(self, features): if not self._weight_column_name: return None else: return array_ops.reshape( math_ops.to_float(features[self._weight_column_name]), shape=(-1,)) @property def problem_type(self): return self._problem_type def _weighted_loss(self, loss, weight_tensor): """Returns cumulative weighted loss.""" unweighted_loss = array_ops.reshape(loss, shape=(-1,)) weighted_loss = math_ops.multiply(unweighted_loss, array_ops.reshape( weight_tensor, shape=(-1,))) return weighted_loss def training_loss(self, logits, target, features, name="training_loss"): """Returns training loss tensor for this head. Training loss is different from the loss reported on the tensorboard as we should respect the example weights when computing the gradient. L = sum_{i} w_{i} * l_{i} / B where B is the number of examples in the batch, l_{i}, w_{i} are individual losses, and example weight. Args: logits: logits, a float tensor. target: either a tensor for labels or in multihead case, a dict of string to target tensor. features: features dict. name: Op name. Returns: Loss tensor. """ target = target[self.name] if isinstance(target, dict) else target loss_unweighted = self._loss_fn(logits, target) weight_tensor = self.get_weight_tensor(features) if weight_tensor is None: return math_ops.reduce_mean(loss_unweighted, name=name) loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor) return math_ops.reduce_mean(loss_weighted, name=name) def loss(self, logits, target, features): """Returns loss tensor for this head. The loss returned is the weighted average. L = sum_{i} w_{i} * l_{i} / sum_{i} w_{i} Args: logits: logits, a float tensor. target: either a tensor for labels or in multihead case, a dict of string to target tensor. features: features dict. Returns: Loss tensor. """ target = target[self.name] if isinstance(target, dict) else target loss_unweighted = self._loss_fn(logits, target) weight_tensor = self.get_weight_tensor(features) if weight_tensor is None: return math_ops.reduce_mean(loss_unweighted, name="loss") loss_weighted = self._weighted_loss(loss_unweighted, weight_tensor) return math_ops.div(math_ops.reduce_sum(loss_weighted), math_ops.to_float(math_ops.reduce_sum(weight_tensor)), name="loss") class _RegressionTargetColumn(_TargetColumn): """_TargetColumn for regression.""" def __init__(self, loss_fn, label_name, weight_column_name, label_dimension): super(_RegressionTargetColumn, self).__init__( loss_fn=loss_fn, num_label_columns=label_dimension, label_name=label_name, weight_column_name=weight_column_name, problem_type=ProblemType.LINEAR_REGRESSION) def logits_to_predictions(self, logits, proba=False): if self.num_label_columns == 1: return array_ops.squeeze(logits, squeeze_dims=[1]) return logits def get_eval_ops(self, features, logits, labels, metrics=None): loss = self.loss(logits, labels, features) result = {"loss": metric_ops.streaming_mean(loss)} if metrics: predictions = self.logits_to_predictions(logits, proba=False) result.update( _run_metrics(predictions, labels, metrics, self.get_weight_tensor(features))) return result class _MultiClassTargetColumn(_TargetColumn): """_TargetColumn for classification.""" # TODO(zakaria): support multilabel. def __init__(self, loss_fn, n_classes, label_name, weight_column_name): if n_classes < 2: raise ValueError("n_classes must be >= 2") super(_MultiClassTargetColumn, self).__init__( loss_fn=loss_fn, num_label_columns=1 if n_classes == 2 else n_classes, label_name=label_name, weight_column_name=weight_column_name, problem_type=ProblemType.CLASSIFICATION) def logits_to_predictions(self, logits, proba=False): if self.num_label_columns == 1: logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1) if proba: return nn.softmax(logits) else: return math_ops.argmax(logits, 1) def _default_eval_metrics(self): if self._num_label_columns == 1: return get_default_binary_metrics_for_eval(thresholds=[.5]) return {} def get_eval_ops(self, features, logits, labels, metrics=None): loss = self.loss(logits, labels, features) result = {"loss": metric_ops.streaming_mean(loss)} # Adds default metrics. if metrics is None: # TODO(b/29366811): This currently results in both an "accuracy" and an # "accuracy/threshold_0.500000_mean" metric for binary classification. metrics = {("accuracy", "classes"): metric_ops.streaming_accuracy} predictions = math_ops.sigmoid(logits) labels_float = math_ops.to_float(labels) default_metrics = self._default_eval_metrics() for metric_name, metric_op in default_metrics.items(): result[metric_name] = metric_op(predictions, labels_float) class_metrics = {} proba_metrics = {} for name, metric_op in six.iteritems(metrics): if isinstance(name, tuple): if len(name) != 2: raise ValueError("Ignoring metric {}. It returned a tuple with " "len {}, expected 2.".format(name, len(name))) else: if name[1] not in ["classes", "probabilities"]: raise ValueError("Ignoring metric {}. The 2nd element of its " "name should be either 'classes' or " "'probabilities'.".format(name)) elif name[1] == "classes": class_metrics[name[0]] = metric_op else: proba_metrics[name[0]] = metric_op elif isinstance(name, str): class_metrics[name] = metric_op else: raise ValueError("Ignoring metric {}. Its name is not in the correct " "form.".format(name)) if class_metrics: class_predictions = self.logits_to_predictions(logits, proba=False) result.update( _run_metrics(class_predictions, labels, class_metrics, self.get_weight_tensor(features))) if proba_metrics: predictions = self.logits_to_predictions(logits, proba=True) result.update( _run_metrics(predictions, labels, proba_metrics, self.get_weight_tensor(features))) return result class _BinarySvmTargetColumn(_MultiClassTargetColumn): """_TargetColumn for binary classification using SVMs.""" def __init__(self, label_name, weight_column_name): def loss_fn(logits, target): check_shape_op = control_flow_ops.Assert( math_ops.less_equal(array_ops.rank(target), 2), ["target's shape should be either [batch_size, 1] or [batch_size]"]) with ops.control_dependencies([check_shape_op]): target = array_ops.reshape( target, shape=[array_ops.shape(target)[0], 1]) return loss_ops.hinge_loss(logits, target) super(_BinarySvmTargetColumn, self).__init__( loss_fn=loss_fn, n_classes=2, label_name=label_name, weight_column_name=weight_column_name) def logits_to_predictions(self, logits, proba=False): if proba: raise ValueError( "logits to probabilities is not supported for _BinarySvmTargetColumn") logits = array_ops.concat([array_ops.zeros_like(logits), logits], 1) return math_ops.argmax(logits, 1) # TODO(zakaria): use contrib losses. def _mean_squared_loss(logits, target): # To prevent broadcasting inside "-". if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) logits.get_shape().assert_is_compatible_with(target.get_shape()) return math_ops.square(logits - math_ops.to_float(target)) def _log_loss_with_two_classes(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) loss_vec = nn.sigmoid_cross_entropy_with_logits( labels=math_ops.to_float(target), logits=logits) return loss_vec def _softmax_cross_entropy_loss(logits, target): # Check that we got integer for classification. if not target.dtype.is_integer: raise ValueError("Target's dtype should be integer " "Instead got %s." % target.dtype) # sparse_softmax_cross_entropy_with_logits requires [batch_size] target. if len(target.get_shape()) == 2: target = array_ops.squeeze(target, squeeze_dims=[1]) loss_vec = nn.sparse_softmax_cross_entropy_with_logits( labels=target, logits=logits) return loss_vec def _run_metrics(predictions, labels, metrics, weights): result = {} labels = math_ops.cast(labels, predictions.dtype) for name, metric in six.iteritems(metrics or {}): if weights is not None: result[name] = metric(predictions, labels, weights=weights) else: result[name] = metric(predictions, labels) return result @deprecated( "2016-11-12", "This file will be removed after the deprecation date." "Please switch to " "third_party/tensorflow/contrib/learn/python/learn/estimators/head.py") def get_default_binary_metrics_for_eval(thresholds): """Returns a dictionary of basic metrics for logistic regression. Args: thresholds: List of floating point thresholds to use for accuracy, precision, and recall metrics. If None, defaults to [0.5]. Returns: Dictionary mapping metrics string names to metrics functions. """ metrics = {} metrics[_MetricKeys.PREDICTION_MEAN] = _predictions_streaming_mean metrics[_MetricKeys.TARGET_MEAN] = _labels_streaming_mean # Also include the streaming mean of the label as an accuracy baseline, as # a reminder to users. metrics[_MetricKeys.ACCURACY_BASELINE] = _labels_streaming_mean metrics[_MetricKeys.AUC] = _streaming_auc for threshold in thresholds: metrics[_MetricKeys.ACCURACY_MEAN % threshold] = _accuracy_at_threshold(threshold) # Precision for positive examples. metrics[_MetricKeys.PRECISION_MEAN % threshold] = _streaming_at_threshold( metric_ops.streaming_precision_at_thresholds, threshold) # Recall for positive examples. metrics[_MetricKeys.RECALL_MEAN % threshold] = _streaming_at_threshold( metric_ops.streaming_recall_at_thresholds, threshold) return metrics def _float_weights_or_none(weights): if weights is None: return None return math_ops.to_float(weights) def _labels_streaming_mean(unused_predictions, labels, weights=None): return metric_ops.streaming_mean(labels, weights=weights) def _predictions_streaming_mean(predictions, unused_labels, weights=None): return metric_ops.streaming_mean(predictions, weights=weights) def _streaming_auc(predictions, labels, weights=None): return metric_ops.streaming_auc( predictions, labels, weights=_float_weights_or_none(weights)) def _accuracy_at_threshold(threshold): def _accuracy_metric(predictions, labels, weights=None): threshold_predictions = math_ops.to_float( math_ops.greater_equal(predictions, threshold)) return metric_ops.streaming_accuracy( predictions=threshold_predictions, labels=labels, weights=weights) return _accuracy_metric def _streaming_at_threshold(streaming_metrics_fn, threshold): def _streaming_metrics(predictions, labels, weights=None): precision_tensor, update_op = streaming_metrics_fn( predictions, labels=labels, thresholds=[threshold], weights=_float_weights_or_none(weights)) return array_ops.squeeze(precision_tensor), update_op return _streaming_metrics class _MetricKeys(object): AUC = "auc" PREDICTION_MEAN = "labels/prediction_mean" TARGET_MEAN = "labels/actual_target_mean" ACCURACY_BASELINE = "accuracy/baseline_target_mean" ACCURACY_MEAN = "accuracy/threshold_%f_mean" PRECISION_MEAN = "precision/positive_threshold_%f_mean" RECALL_MEAN = "recall/positive_threshold_%f_mean"
[ "tensorflow.python.ops.math_ops.greater_equal", "tensorflow.python.ops.nn.softmax", "tensorflow.python.ops.array_ops.shape", "tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.math_ops.to_float", "tensorflow.contrib.losses.python.losses.loss_ops.hinge_loss", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.math_ops.argmax", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.contrib.metrics.python.ops.metric_ops.streaming_accuracy", "tensorflow.contrib.framework.deprecated", "tensorflow.python.ops.math_ops.sigmoid", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_sum" ]
venv1/Lib/site-packages/tensorflow/contrib/layers/python/layers/target_column.py
[(33, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-12"""', '"""This file will be removed after the deprecation date.Please switch to third_party/tensorflow/contrib/learn/python/learn/estimators/head.py"""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (63, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-12"""', '"""This file will be removed after the deprecation date.Please switch to third_party/tensorflow/contrib/learn/python/learn/estimators/head.py"""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (99, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-12"""', '"""This file will be removed after the deprecation date.Please switch to third_party/tensorflow/contrib/learn/python/learn/estimators/head.py"""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (123, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-12"""', '"""This file will be removed after the deprecation date.Please switch to third_party/tensorflow/contrib/learn/python/learn/estimators/head.py"""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (439, 'tensorflow.contrib.framework.deprecated', 'deprecated', (['"""2016-11-12"""', '"""This file will be removed after the deprecation date.Please switch to third_party/tensorflow/contrib/learn/python/learn/estimators/head.py"""'], {}), False, 'from tensorflow.contrib.framework import deprecated\n'), (422, 'tensorflow.python.ops.nn.sparse_softmax_cross_entropy_with_logits', 'nn.sparse_softmax_cross_entropy_with_logits', ([], {'labels': 'target', 'logits': 'logits'}), False, 'from tensorflow.python.ops import nn\n'), (429, 'tensorflow.python.ops.math_ops.cast', 'math_ops.cast', (['labels', 'predictions.dtype'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (430, 'six.iteritems', 'six.iteritems', (['(metrics or {})'], {}), False, 'import six\n'), (478, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (482, 'tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean', 'metric_ops.streaming_mean', (['labels'], {'weights': 'weights'}), False, 'from tensorflow.contrib.metrics.python.ops import metric_ops\n'), (486, 'tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean', 'metric_ops.streaming_mean', (['predictions'], {'weights': 'weights'}), False, 'from tensorflow.contrib.metrics.python.ops import metric_ops\n'), (196, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['loss'], {'shape': '(-1,)'}), False, 'from tensorflow.python.ops import array_ops\n'), (230, 'tensorflow.python.ops.math_ops.reduce_mean', 'math_ops.reduce_mean', (['loss_weighted'], {'name': 'name'}), False, 'from tensorflow.python.ops import math_ops\n'), (325, 'tensorflow.python.ops.math_ops.sigmoid', 'math_ops.sigmoid', (['logits'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (326, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['labels'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (334, 'six.iteritems', 'six.iteritems', (['metrics'], {}), False, 'import six\n'), (392, 'tensorflow.python.ops.math_ops.argmax', 'math_ops.argmax', (['logits', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (399, 'tensorflow.python.ops.array_ops.expand_dims', 'array_ops.expand_dims', (['target'], {'dim': '[1]'}), False, 'from tensorflow.python.ops import array_ops\n'), (408, 'tensorflow.python.ops.array_ops.expand_dims', 'array_ops.expand_dims', (['target'], {'dim': '[1]'}), False, 'from tensorflow.python.ops import array_ops\n'), (421, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['target'], {'squeeze_dims': '[1]'}), False, 'from tensorflow.python.ops import array_ops\n'), (499, 'tensorflow.contrib.metrics.python.ops.metric_ops.streaming_accuracy', 'metric_ops.streaming_accuracy', ([], {'predictions': 'threshold_predictions', 'labels': 'labels', 'weights': 'weights'}), False, 'from tensorflow.contrib.metrics.python.ops import metric_ops\n'), (198, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['weight_tensor'], {'shape': '(-1,)'}), False, 'from tensorflow.python.ops import array_ops\n'), (228, 'tensorflow.python.ops.math_ops.reduce_mean', 'math_ops.reduce_mean', (['loss_unweighted'], {'name': 'name'}), False, 'from tensorflow.python.ops import math_ops\n'), (253, 'tensorflow.python.ops.math_ops.reduce_mean', 'math_ops.reduce_mean', (['loss_unweighted'], {'name': '"""loss"""'}), False, 'from tensorflow.python.ops import math_ops\n'), (255, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['loss_weighted'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (273, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['logits'], {'squeeze_dims': '[1]'}), False, 'from tensorflow.python.ops import array_ops\n'), (278, 'tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean', 'metric_ops.streaming_mean', (['loss'], {}), False, 'from tensorflow.contrib.metrics.python.ops import metric_ops\n'), (306, 'tensorflow.python.ops.nn.softmax', 'nn.softmax', (['logits'], {}), False, 'from tensorflow.python.ops import nn\n'), (308, 'tensorflow.python.ops.math_ops.argmax', 'math_ops.argmax', (['logits', '(1)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (317, 'tensorflow.contrib.metrics.python.ops.metric_ops.streaming_mean', 'metric_ops.streaming_mean', (['loss'], {}), False, 'from tensorflow.contrib.metrics.python.ops import metric_ops\n'), (378, 'tensorflow.contrib.losses.python.losses.loss_ops.hinge_loss', 'loss_ops.hinge_loss', (['logits', 'target'], {}), False, 'from tensorflow.contrib.losses.python.losses import loss_ops\n'), (402, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['target'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (410, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['target'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (498, 'tensorflow.python.ops.math_ops.greater_equal', 'math_ops.greater_equal', (['predictions', 'threshold'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (513, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['precision_tensor'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (188, 'tensorflow.python.ops.math_ops.to_float', 'math_ops.to_float', (['features[self._weight_column_name]'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (256, 'tensorflow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', (['weight_tensor'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (375, 'tensorflow.python.framework.ops.control_dependencies', 'ops.control_dependencies', (['[check_shape_op]'], {}), False, 'from tensorflow.python.framework import ops\n'), (391, 'tensorflow.python.ops.array_ops.zeros_like', 'array_ops.zeros_like', (['logits'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (303, 'tensorflow.python.ops.array_ops.zeros_like', 'array_ops.zeros_like', (['logits'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (373, 'tensorflow.python.ops.array_ops.rank', 'array_ops.rank', (['target'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (377, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['target'], {}), False, 'from tensorflow.python.ops import array_ops\n')]
clementpoiret/sparseml
8442a6ef8ba11fb02f5e51472dd68b72438539b9
# Copyright (c) 2021 - present / Neuralmagic, 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. """ Utility functions for working with tensorflow_v1 slim's nets_factory """ import functools import logging from typing import Callable, Dict from sparseml.tensorflow_v1.utils import tf_compat as tf try: from nets import cyclegan, dcgan, nets_factory except Exception: nets_factory = None dcgan = None cyclegan = None logging.warning("TensorFlow slim nets not found in system") try: from tensorflow.contrib import layers as contrib_layers from tensorflow.contrib import slim except Exception: slim = None contrib_layers = None logging.warning("TensorFlow slim not found in system") __all__ = [ "get_network_fn", "get_gan_network_fn", "get_model_scope", "mobilenet_v1_arg_scope", ] def _gans_constructors() -> Dict[str, Callable]: return { "cyclegan": cyclegan.cyclegan_generator_resnet, "dcgan_generator": dcgan.generator, "dcgan_discriminator": dcgan.discriminator, } def _check_slim_availability(): if nets_factory is None or slim is None: raise ValueError( "TensorFlow slim not setup in environment, please install first" ) def get_network_fn( name: str, num_classes: int, weight_decay: float = 0.0, is_training: bool = False, arg_scope_vars: Dict = None, ): """ Modified from slim/nets/nets_factory Returns a network_fn such as `logits, end_points = network_fn(images)`. :param name: The name of the network. :param num_classes: The number of classes to use for classification. If 0 or None, the logits layer is omitted and its input features are returned instead. :param weight_decay: The l2 coefficient for the model weights. :param is_training: `True` if the model is being used for training otherwise `False` :param arg_scope_vars: arg_scope_vars to be passed to the slim arg_scope :return network_fn: A function that applies the model to a batch of images. It has the following signature: net, end_points = network_fn(images) The `images` input is a tensor of shape [batch_size, height, width, 3 or 1] with height = width = network_fn.default_image_size. (The permissibility and treatment of other sizes depends on the network_fn.) The returned `end_points` are a dictionary of intermediate activations. The returned `net` is the topmost layer, depending on `num_classes`: If `num_classes` was a non-zero integer, `net` is a logits tensor of shape [batch_size, num_classes]. If `num_classes` was 0 or `None`, `net` is a tensor with the input to the logits layer of shape [batch_size, 1, 1, num_features] or [batch_size, num_features]. Dropout has not been applied to this (even if the network's original classification does); it remains for the caller to do this or not. :raises ValueError: If network `name` is not recognized. """ _check_slim_availability() if not arg_scope_vars: arg_scope_vars = {} if "gan" in name.lower(): return get_gan_network_fn(name, is_training) if name not in nets_factory.networks_map: raise ValueError("Name of network unknown %s" % name) func = nets_factory.networks_map[name] arg_scope_vars["weight_decay"] = weight_decay @functools.wraps(func) def network_fn(images, **kwargs): with slim.arg_scope(get_model_scope(name, arg_scope_vars=arg_scope_vars)): return func( images, num_classes=num_classes, is_training=is_training, **kwargs ) if hasattr(func, "default_image_size"): network_fn.default_image_size = func.default_image_size return network_fn def get_gan_network_fn( name: str, is_training: bool = False, ): """ Returns network_fn for a GAN sub-model :param name: The name of the network. :param is_training: `True` if the model is being used for training otherwise `False` :return network_fn: Function that will run a gan sub-model :raises ValueError: If network `name` is not recognized. """ _check_slim_availability() if name not in _gans_constructors(): raise ValueError("Name of GAN network unknown %s" % name) func = _gans_constructors()[name] def network_fn(inputs, **kwargs): if name == "dcgan_generator": kwargs["final_size"] = 16 return func(inputs, is_training=is_training, **kwargs) return network_fn def get_model_scope(model_name: str, arg_scope_vars: Dict = None): """ :param model_name: name of the model to create an arg scope for :param arg_scope_vars: :return: arg_scope_vars to be passed to the slim arg_scope """ _check_slim_availability() if arg_scope_vars is None: arg_scope_vars = {} arg_scope = nets_factory.arg_scopes_map[model_name](**arg_scope_vars) if model_name == "mobilenet_v1": arg_scope = mobilenet_v1_arg_scope(**arg_scope_vars) return arg_scope def mobilenet_v1_arg_scope( is_training: bool = True, weight_decay: float = 0.00004, stddev: float = 0.09, regularize_depthwise: bool = False, batch_norm_decay: float = 0.9997, batch_norm_epsilon: float = 0.001, batch_norm_updates_collections: tf.GraphKeys = tf.GraphKeys.UPDATE_OPS, normalizer_fn: Callable = slim.batch_norm if slim else None, ): """ Adapted from slim to allow for Xavier initializer Defines the default MobilenetV1 arg scope. :param is_training: Whether or not we're training the model. If this is set to None, the parameter is not added to the batch_norm arg_scope. :param weight_decay: The weight decay to use for regularizing the model. :param stddev: The standard deviation of the trunctated normal weight initializer. :param regularize_depthwise: Whether or not apply regularization on depthwise. :param batch_norm_decay: Decay for batch norm moving average. :param batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. :param batch_norm_updates_collections: Collection for the update ops for batch norm. :param normalizer_fn: Normalization function to apply after convolution. :return: An `arg_scope` to use for the mobilenet v1 model. """ _check_slim_availability() batch_norm_params = { "center": True, "scale": True, "decay": batch_norm_decay, "epsilon": batch_norm_epsilon, "updates_collections": batch_norm_updates_collections, } if is_training is not None: batch_norm_params["is_training"] = is_training # Set weight_decay for weights in Conv and DepthSepConv layers. weights_init = tf.keras.initializers.glorot_normal() regularizer = contrib_layers.l2_regularizer(weight_decay) if regularize_depthwise: depthwise_regularizer = regularizer else: depthwise_regularizer = None with slim.arg_scope( [slim.conv2d, slim.separable_conv2d], weights_initializer=weights_init, activation_fn=tf.nn.relu6, normalizer_fn=normalizer_fn, ): with slim.arg_scope([slim.batch_norm], **batch_norm_params): with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer): with slim.arg_scope( [slim.separable_conv2d], weights_regularizer=depthwise_regularizer ) as sc: return sc
[ "tensorflow.contrib.slim.arg_scope", "tensorflow.contrib.layers.l2_regularizer" ]
src/sparseml/tensorflow_v1/utils/nets_utils.py
[(111, 'functools.wraps', 'functools.wraps', (['func'], {}), False, 'import functools\n'), (208, 'sparseml.tensorflow_v1.utils.tf_compat.keras.initializers.glorot_normal', 'tf.keras.initializers.glorot_normal', ([], {}), True, 'from sparseml.tensorflow_v1.utils import tf_compat as tf\n'), (209, 'tensorflow.contrib.layers.l2_regularizer', 'contrib_layers.l2_regularizer', (['weight_decay'], {}), True, 'from tensorflow.contrib import layers as contrib_layers\n'), (32, 'logging.warning', 'logging.warning', (['"""TensorFlow slim nets not found in system"""'], {}), False, 'import logging\n'), (40, 'logging.warning', 'logging.warning', (['"""TensorFlow slim not found in system"""'], {}), False, 'import logging\n'), (214, 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d, slim.separable_conv2d]'], {'weights_initializer': 'weights_init', 'activation_fn': 'tf.nn.relu6', 'normalizer_fn': 'normalizer_fn'}), False, 'from tensorflow.contrib import slim\n'), (220, 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.batch_norm]'], {}), False, 'from tensorflow.contrib import slim\n'), (221, 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d]'], {'weights_regularizer': 'regularizer'}), False, 'from tensorflow.contrib import slim\n'), (222, 'tensorflow.contrib.slim.arg_scope', 'slim.arg_scope', (['[slim.separable_conv2d]'], {'weights_regularizer': 'depthwise_regularizer'}), False, 'from tensorflow.contrib import slim\n')]
GeniusDog/Intelligent-Projects-Using-Python
ca4650abb0c477b28a5698032835ea993cb08bd4
from __future__ import print_function, division #import scipy import tensorflow as tf import datetime import matplotlib.pyplot as plt #import sys #from data_loader import DataLoader import numpy as np import os import time import glob from scipy.misc import imread,imresize,imsave import copy import fire from elapsedtimer import ElapsedTimer def load_train_data(image_path, load_size=64,fine_size=64, is_testing=False): img_A = imread(image_path[0]) img_B = imread(image_path[1]) if not is_testing: img_A = imresize(img_A, [load_size, load_size]) img_B = imresize(img_B, [load_size, load_size]) # h1 = int(np.ceil(np.random.uniform(1e-2, load_size-fine_size))) # w1 = int(np.ceil(np.random.uniform(1e-2, load_size-fine_size))) # img_A = img_A[h1:h1+fine_size, w1:w1+fine_size] # img_B = img_B[h1:h1+fine_size, w1:w1+fine_size] if np.random.random() > 0.5: img_A = np.fliplr(img_A) img_B = np.fliplr(img_B) else: img_A = imresize(img_A, [fine_size, fine_size]) img_B = imresize(img_B, [fine_size, fine_size]) img_A = img_A/127.5 - 1 img_B = img_B/127.5 - 1 img_AB = np.concatenate((img_A, img_B), axis=2) return img_AB def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 3)) for idx, image in enumerate(images): i = idx % size[1] j = idx // size[1] img[j*h:j*h+h, i*w:i*w+w, :] = image return img def image_save(images, size, path): return imsave(path, merge(images, size)) def save_images(images, size, image_path): return image_save(inverse_transform(images),size, image_path) def inverse_transform(images): return (images + 1)*127.5 class ImagePool(object): def __init__(self, maxsize=50): self.maxsize = maxsize self.num_img = 0 self.images = [] def __call__(self, image): if self.maxsize <= 0: return image if self.num_img < self.maxsize: self.images.append(image) self.num_img += 1 return image if np.random.rand() > 0.5: idx = int(np.random.rand()*self.maxsize) tmp1 = copy.copy(self.images[idx])[0] self.images[idx][0] = image[0] idx = int(np.random.rand()*self.maxsize) tmp2 = copy.copy(self.images[idx])[1] self.images[idx][1] = image[1] return [tmp1, tmp2] else: return image class DiscoGAN(): def __init__(self,dataset_dir,epochs=200): # Input shape self.dataset_dir = dataset_dir self.lambda_l2 = 1.0 self.image_size = 64 self.input_dim = 3 self.output_dim = 3 self.batch_size = 64 self.df = 64 self.gf = 64 self.channels = 3 self.output_c_dim = 3 self.l_r = 2e-4 self.beta1 = 0.5 self.beta2 = 0.99 self.weight_decay = 0.00001 self.epoch = epochs self.train_size = 10000 self.epoch_step = 10 self.load_size = 64 self.fine_size = 64 self.checkpoint_dir = 'checkpoint' self.sample_dir = 'sample' self.print_freq = 5 self.save_freq = 10 self.pool = ImagePool() return None def build_generator(self,image,reuse=False,name='generator'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False """U-Net Generator""" def lrelu(x, alpha,name='lrelu'): with tf.variable_scope(name): return tf.nn.relu(x) - alpha * tf.nn.relu(-x) def instance_norm(x,name='instance_norm'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable('scale',[x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)) offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0)) out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset return out def common_conv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',norm=True,name='common_conv2d'): """Layers used during downsampling""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=stride,padding=padding) if norm: d = tf.contrib.layers.batch_norm(d) d = lrelu(d,alpha=0.2) return d #def common_deconv2d(layer_input,skip_input, filters,f_size=4,stride=2,dropout_rate=0,name='common_deconv2d'): def common_deconv2d(layer_input,filters,f_size=4,stride=2,padding='SAME',dropout_rate=0,name='common_deconv2d'): """Layers used during upsampling""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False u = tf.contrib.layers.conv2d_transpose(layer_input,filters,f_size,stride=stride,padding=padding) if dropout_rate: u = tf.contrib.layers.dropout(u,keep_prob=dropout_rate) u = tf.contrib.layers.batch_norm(u) u = tf.nn.relu(u) # u = tf.contrib.keras.layers.concatenate([skip_input,u]) return u # Downsampling dwn1 = common_conv2d(image,self.gf,stride=2,norm=False,name='dwn1') # 64x64 -> 32x32 #print('dwn1',np.shape(dwn1)) dwn2 = common_conv2d(dwn1,self.gf*2,stride=2,name='dwn2') # 32x32 -> 16x16 #print('dwn2',np.shape(dwn2)) dwn3 = common_conv2d(dwn2,self.gf*4,stride=2,name='dwn3') # 16x16 -> 8x8 # print('dwn3',np.shape(dwn3)) dwn4 = common_conv2d(dwn3,self.gf*8,stride=2,name='dwn4') # 8x8 -> 4x4 # print('dwn4',np.shape(dwn4)) dwn5 = common_conv2d(dwn4,100,stride=1,padding='valid',name='dwn5') # 4x4 -> 1x1 # print('dwn5',np.shape(dwn5)) # Upsampling up1 = common_deconv2d(dwn5,self.gf*8,stride=1,padding='valid',name='up1') # 16x16 -> 16x16 #print(np.shape(up1)) up2 = common_deconv2d(up1,self.gf*4,name='up2') # 16x16 -> 32x32 up3 = common_deconv2d(up2,self.gf*2,name='up3') # 32x32 -> 64x64 up4 = common_deconv2d(up3,self.gf,name='up4') # 64x64 -> 128x128 out_img = tf.contrib.layers.conv2d_transpose(up4,self.channels,kernel_size=4,stride=2,padding='SAME',activation_fn=tf.nn.tanh) # 128x128 -> 256x256 #print('out_img',(np.shape(out_img))) return out_img def build_discriminator(self,image,reuse=False,name='discriminator'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False def lrelu(x, alpha,name='lrelu'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False return tf.nn.relu(x) - alpha * tf.nn.relu(-x) def instance_norm(x,name='instance_norm'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable('scale',[x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)) offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0)) out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset return out def d_layer(layer_input,filters,f_size=4,stride=2,norm=True,name='d_layer'): """Discriminator layer""" with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=2, padding='SAME') if norm: d = tf.contrib.layers.batch_norm(d) d = lrelu(d,alpha=0.2) return d down1 = d_layer(image,self.df, norm=False,name='down1') #256x256 -> 128x128 #rint('down1',np.shape(down1)) down2 = d_layer(down1,self.df*2,name='down2') #128x128 -> 64x64 #rint('down2',np.shape(down2)) down3 = d_layer(down2,self.df*4,name='down3') #64x64 -> 32x32 #rint('down3',np.shape(down3)) down4 = d_layer(down3,self.df*8,name='down4') # 32x32 -> 16x16 #rint('down4',np.shape(down4)) down5 = tf.contrib.layers.conv2d(down4,1,kernel_size=4,stride=1,padding='valid') #rint('down5',np.shape(down5)) #rint(np.shape(down5)) #logits = tf.reduce_mean(down5, [1,2,3]) return down5 def build_network(self): def squared_loss(y_pred,labels): return tf.reduce_mean((y_pred - labels)**2) def abs_loss(y_pred,labels): return tf.reduce_mean(tf.abs(y_pred - labels)) def binary_cross_entropy_loss(logits,labels): return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=labels,logits=logits)) self.images_real = tf.placeholder(tf.float32,[None,self.image_size,self.image_size,self.input_dim + self.output_dim]) self.image_real_A = self.images_real[:,:,:,:self.input_dim] self.image_real_B = self.images_real[:,:,:,self.input_dim:self.input_dim + self.output_dim] self.images_fake_B = self.build_generator(self.image_real_A,reuse=False,name='generator_AB') self.images_fake_A = self.build_generator(self.images_fake_B,reuse=False,name='generator_BA') self.images_fake_A_ = self.build_generator(self.image_real_B,reuse=True,name='generator_BA') self.images_fake_B_ = self.build_generator(self.images_fake_A_,reuse=True,name='generator_AB') self.D_B_fake = self.build_discriminator(self.images_fake_B ,reuse=False, name="discriminatorB") self.D_A_fake = self.build_discriminator(self.images_fake_A_,reuse=False, name="discriminatorA") self.D_B_real = self.build_discriminator(self.image_real_B,reuse=True, name="discriminatorB") self.D_A_real = self.build_discriminator(self.image_real_A,reuse=True, name="discriminatorA") self.loss_GABA = self.lambda_l2*squared_loss(self.images_fake_A,self.image_real_A) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_B_fake),logits=self.D_B_fake) self.loss_GBAB = self.lambda_l2*squared_loss(self.images_fake_B_,self.image_real_B) + binary_cross_entropy_loss(labels=tf.ones_like(self.D_A_fake),logits=self.D_A_fake) self.generator_loss = self.loss_GABA + self.loss_GBAB self.D_B_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_B_real),self.D_B_real) self.D_B_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_B_fake),self.D_B_fake) self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0 self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real) self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake) self.D_A_loss = (self.D_A_loss_real + self.D_A_loss_fake) / 2.0 self.discriminator_loss = self.D_B_loss + self.D_A_loss self.loss_GABA_sum = tf.summary.scalar("g_loss_a2b", self.loss_GABA) self.loss_GBAB_sum = tf.summary.scalar("g_loss_b2a", self.loss_GBAB) self.g_total_loss_sum = tf.summary.scalar("g_loss", self.generator_loss) self.g_sum = tf.summary.merge([self.loss_GABA_sum,self.loss_GBAB_sum,self.g_total_loss_sum]) self.loss_db_sum = tf.summary.scalar("db_loss", self.D_B_loss) self.loss_da_sum = tf.summary.scalar("da_loss", self.D_A_loss) self.loss_d_sum = tf.summary.scalar("d_loss",self.discriminator_loss) self.db_loss_real_sum = tf.summary.scalar("db_loss_real", self.D_B_loss_real) self.db_loss_fake_sum = tf.summary.scalar("db_loss_fake", self.D_B_loss_fake) self.da_loss_real_sum = tf.summary.scalar("da_loss_real", self.D_A_loss_real) self.da_loss_fake_sum = tf.summary.scalar("da_loss_fake", self.D_A_loss_fake) self.d_sum = tf.summary.merge( [self.loss_da_sum, self.da_loss_real_sum, self.da_loss_fake_sum, self.loss_db_sum, self.db_loss_real_sum, self.db_loss_fake_sum, self.loss_d_sum] ) trainable_variables = tf.trainable_variables() self.d_variables = [var for var in trainable_variables if 'discriminator' in var.name] self.g_variables = [var for var in trainable_variables if 'generator' in var.name] print ('Variable printing start :' ) for var in self.d_variables: print(var.name) self.test_image_A = tf.placeholder(tf.float32,[None, self.image_size,self.image_size,self.input_dim], name='test_A') self.test_image_B = tf.placeholder(tf.float32,[None, self.image_size, self.image_size,self.output_c_dim], name='test_B') self.saver = tf.train.Saver() def train_network(self): self.learning_rate = tf.placeholder(tf.float32) self.d_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.discriminator_loss,var_list=self.d_variables) self.g_optimizer = tf.train.AdamOptimizer(self.learning_rate,beta1=self.beta1,beta2=self.beta2).minimize(self.generator_loss,var_list=self.g_variables) self.init_op = tf.global_variables_initializer() self.sess = tf.Session() self.sess.run(self.init_op) #self.dataset_dir = '/home/santanu/Downloads/DiscoGAN/edges2handbags/train/' self.writer = tf.summary.FileWriter("./logs", self.sess.graph) count = 1 start_time = time.time() for epoch in range(self.epoch): data_A = os.listdir(self.dataset_dir + 'trainA/') data_B = os.listdir(self.dataset_dir + 'trainB/') data_A = [ (self.dataset_dir + 'trainA/' + str(file_name)) for file_name in data_A ] data_B = [ (self.dataset_dir + 'trainB/' + str(file_name)) for file_name in data_B ] np.random.shuffle(data_A) np.random.shuffle(data_B) batch_ids = min(min(len(data_A), len(data_B)), self.train_size) // self.batch_size # lr = self.l_r if epoch < self.epoch_step else self.l_r*(self.epoch-epoch)/(self.epoch-self.epoch_step) lr = self.l_r if epoch < self.epoch_step else self.l_r*(self.epoch-epoch)/(self.epoch-self.epoch_step) for id_ in range(0, batch_ids): batch_files = list(zip(data_A[id_ * self.batch_size:(id_ + 1) * self.batch_size], data_B[id_ * self.batch_size:(id_ + 1) * self.batch_size])) batch_images = [load_train_data(batch_file, self.load_size, self.fine_size) for batch_file in batch_files] batch_images = np.array(batch_images).astype(np.float32) # Update G network and record fake outputs fake_A, fake_B, _, summary_str = self.sess.run( [self.images_fake_A_,self.images_fake_B,self.g_optimizer,self.g_sum], feed_dict={self.images_real: batch_images, self.learning_rate:lr}) self.writer.add_summary(summary_str, count) [fake_A,fake_B] = self.pool([fake_A, fake_B]) # Update D network _, summary_str = self.sess.run( [self.d_optimizer,self.d_sum], feed_dict={self.images_real: batch_images, # self.fake_A_sample: fake_A, # self.fake_B_sample: fake_B, self.learning_rate: lr}) self.writer.add_summary(summary_str, count) count += 1 print(("Epoch: [%2d] [%4d/%4d] time: %4.4f" % ( epoch, id_, batch_ids, time.time() - start_time))) if count % self.print_freq == 1: self.sample_model(self.sample_dir, epoch, id_) if count % self.save_freq == 2: self.save_model(self.checkpoint_dir, count) def save_model(self,checkpoint_dir,step): model_name = "cyclegan.model" model_dir = "%s_%s" % (self.dataset_dir, self.image_size) checkpoint_dir = os.path.join(checkpoint_dir, model_dir) if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) self.saver.save(self.sess, os.path.join(checkpoint_dir, model_name), global_step=step) def load_model(self,checkpoint_dir): print(" [*] Reading checkpoint...") model_dir = "%s_%s" % (self.dataset_dir, self.image_size) checkpoint_dir = os.path.join(checkpoint_dir, model_dir) ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: ckpt_name = os.path.basename(ckpt.model_checkpoint_path) self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name)) return True else: return False def sample_model(self, sample_dir, epoch, id_): if not os.path.exists(sample_dir): os.makedirs(sample_dir) data_A = os.listdir(self.dataset_dir + 'trainA/') data_B = os.listdir(self.dataset_dir + 'trainB/') data_A = [ (self.dataset_dir + 'trainA/' + str(file_name)) for file_name in data_A ] data_B = [ (self.dataset_dir + 'trainB/' + str(file_name)) for file_name in data_B ] np.random.shuffle(data_A) np.random.shuffle(data_B) batch_files = list(zip(data_A[:self.batch_size], data_B[:self.batch_size])) sample_images = [load_train_data(batch_file, is_testing=True) for batch_file in batch_files] sample_images = np.array(sample_images).astype(np.float32) fake_A, fake_B = self.sess.run( [self.images_fake_A_,self.images_fake_B], feed_dict={self.images_real: sample_images} ) save_images(fake_A, [self.batch_size, 1], './{}/A_{:02d}_{:04d}.jpg'.format(sample_dir, epoch, id_)) save_images(fake_B, [self.batch_size, 1], './{}/B_{:02d}_{:04d}.jpg'.format(sample_dir, epoch, id_)) def process_main(self): self.build_network() self.train_network() if __name__ == '__main__': with ElapsedTimer('DiscoGAN'): fire.Fire(DiscoGAN)
[ "numpy.concatenate", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.contrib.layers.conv2d_transpose", "numpy.fliplr", "tensorflow.nn.moments", "tensorflow.truncated_normal_initializer", "tensorflow.Session", "tensorflow.trainable_variables", "tensorflow.train.Saver", "numpy.zeros", "tensorflow.placeholder", "tensorflow.contrib.layers.dropout", "tensorflow.global_variables_initializer", "tensorflow.zeros_like", "tensorflow.contrib.layers.conv2d", "numpy.random.rand", "tensorflow.contrib.layers.batch_norm", "numpy.array", "tensorflow.summary.merge", "tensorflow.train.get_checkpoint_state", "tensorflow.nn.relu", "scipy.misc.imresize", "tensorflow.summary.FileWriter", "numpy.random.random", "tensorflow.reduce_mean", "tensorflow.ones_like", "numpy.random.shuffle", "tensorflow.constant_initializer", "scipy.misc.imread", "tensorflow.variable_scope", "tensorflow.sqrt", "tensorflow.get_variable_scope", "tensorflow.abs" ]
Chapter04/cycledGAN_edges_to_bags.py
[(19, 'scipy.misc.imread', 'imread', (['image_path[0]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (20, 'scipy.misc.imread', 'imread', (['image_path[1]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (40, 'numpy.concatenate', 'np.concatenate', (['(img_A, img_B)'], {'axis': '(2)'}), True, 'import numpy as np\n'), (46, 'numpy.zeros', 'np.zeros', (['(h * size[0], w * size[1], 3)'], {}), True, 'import numpy as np\n'), (23, 'scipy.misc.imresize', 'imresize', (['img_A', '[load_size, load_size]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (24, 'scipy.misc.imresize', 'imresize', (['img_B', '[load_size, load_size]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (34, 'scipy.misc.imresize', 'imresize', (['img_A', '[fine_size, fine_size]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (35, 'scipy.misc.imresize', 'imresize', (['img_B', '[fine_size, fine_size]'], {}), False, 'from scipy.misc import imread, imresize, imsave\n'), (294, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.image_size, self.image_size, self.input_dim + self.output_dim]'], {}), True, 'import tensorflow as tf\n'), (327, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""g_loss_a2b"""', 'self.loss_GABA'], {}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""g_loss_b2a"""', 'self.loss_GBAB'], {}), True, 'import tensorflow as tf\n'), (329, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""g_loss"""', 'self.generator_loss'], {}), True, 'import tensorflow as tf\n'), (330, 'tensorflow.summary.merge', 'tf.summary.merge', (['[self.loss_GABA_sum, self.loss_GBAB_sum, self.g_total_loss_sum]'], {}), True, 'import tensorflow as tf\n'), (332, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""db_loss"""', 'self.D_B_loss'], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""da_loss"""', 'self.D_A_loss'], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""d_loss"""', 'self.discriminator_loss'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""db_loss_real"""', 'self.D_B_loss_real'], {}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""db_loss_fake"""', 'self.D_B_loss_fake'], {}), True, 'import tensorflow as tf\n'), (338, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""da_loss_real"""', 'self.D_A_loss_real'], {}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""da_loss_fake"""', 'self.D_A_loss_fake'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.summary.merge', 'tf.summary.merge', (['[self.loss_da_sum, self.da_loss_real_sum, self.da_loss_fake_sum, self.\n loss_db_sum, self.db_loss_real_sum, self.db_loss_fake_sum, self.loss_d_sum]'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (356, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.image_size, self.image_size, self.input_dim]'], {'name': '"""test_A"""'}), True, 'import tensorflow as tf\n'), (357, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, self.image_size, self.image_size, self.output_c_dim]'], {'name': '"""test_B"""'}), True, 'import tensorflow as tf\n'), (358, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (367, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (368, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""./logs"""', 'self.sess.graph'], {}), True, 'import tensorflow as tf\n'), (373, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (424, 'os.path.join', 'os.path.join', (['checkpoint_dir', 'model_dir'], {}), False, 'import os\n'), (438, 'os.path.join', 'os.path.join', (['checkpoint_dir', 'model_dir'], {}), False, 'import os\n'), (440, 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['checkpoint_dir'], {}), True, 'import tensorflow as tf\n'), (455, 'os.listdir', 'os.listdir', (["(self.dataset_dir + 'trainA/')"], {}), False, 'import os\n'), (456, 'os.listdir', 'os.listdir', (["(self.dataset_dir + 'trainB/')"], {}), False, 'import os\n'), (461, 'numpy.random.shuffle', 'np.random.shuffle', (['data_A'], {}), True, 'import numpy as np\n'), (462, 'numpy.random.shuffle', 'np.random.shuffle', (['data_B'], {}), True, 'import numpy as np\n'), (482, 'elapsedtimer.ElapsedTimer', 'ElapsedTimer', (['"""DiscoGAN"""'], {}), False, 'from elapsedtimer import ElapsedTimer\n'), (483, 'fire.Fire', 'fire.Fire', (['DiscoGAN'], {}), False, 'import fire\n'), (30, 'numpy.random.random', 'np.random.random', ([], {}), True, 'import numpy as np\n'), (31, 'numpy.fliplr', 'np.fliplr', (['img_A'], {}), True, 'import numpy as np\n'), (32, 'numpy.fliplr', 'np.fliplr', (['img_B'], {}), True, 'import numpy as np\n'), (77, 'numpy.random.rand', 'np.random.rand', ([], {}), True, 'import numpy as np\n'), (123, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.contrib.layers.conv2d_transpose', 'tf.contrib.layers.conv2d_transpose', (['up4', 'self.channels'], {'kernel_size': '(4)', 'stride': '(2)', 'padding': '"""SAME"""', 'activation_fn': 'tf.nn.tanh'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.contrib.layers.conv2d', 'tf.contrib.layers.conv2d', (['down4', '(1)'], {'kernel_size': '(4)', 'stride': '(1)', 'padding': '"""valid"""'}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((y_pred - labels) ** 2)'], {}), True, 'import tensorflow as tf\n'), (316, 'tensorflow.ones_like', 'tf.ones_like', (['self.D_B_real'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.zeros_like', 'tf.zeros_like', (['self.D_B_fake'], {}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.ones_like', 'tf.ones_like', (['self.D_A_real'], {}), True, 'import tensorflow as tf\n'), (322, 'tensorflow.zeros_like', 'tf.zeros_like', (['self.D_A_fake'], {}), True, 'import tensorflow as tf\n'), (376, 'os.listdir', 'os.listdir', (["(self.dataset_dir + 'trainA/')"], {}), False, 'import os\n'), (377, 'os.listdir', 'os.listdir', (["(self.dataset_dir + 'trainB/')"], {}), False, 'import os\n'), (381, 'numpy.random.shuffle', 'np.random.shuffle', (['data_A'], {}), True, 'import numpy as np\n'), (382, 'numpy.random.shuffle', 'np.random.shuffle', (['data_B'], {}), True, 'import numpy as np\n'), (426, 'os.path.exists', 'os.path.exists', (['checkpoint_dir'], {}), False, 'import os\n'), (427, 'os.makedirs', 'os.makedirs', (['checkpoint_dir'], {}), False, 'import os\n'), (430, 'os.path.join', 'os.path.join', (['checkpoint_dir', 'model_name'], {}), False, 'import os\n'), (442, 'os.path.basename', 'os.path.basename', (['ckpt.model_checkpoint_path'], {}), False, 'import os\n'), (451, 'os.path.exists', 'os.path.exists', (['sample_dir'], {}), False, 'import os\n'), (452, 'os.makedirs', 'os.makedirs', (['sample_dir'], {}), False, 'import os\n'), (79, 'copy.copy', 'copy.copy', (['self.images[idx]'], {}), False, 'import copy\n'), (82, 'copy.copy', 'copy.copy', (['self.images[idx]'], {}), False, 'import copy\n'), (288, 'tensorflow.abs', 'tf.abs', (['(y_pred - labels)'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'labels', 'logits': 'logits'}), True, 'import tensorflow as tf\n'), (364, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.learning_rate'], {'beta1': 'self.beta1', 'beta2': 'self.beta2'}), True, 'import tensorflow as tf\n'), (365, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.learning_rate'], {'beta1': 'self.beta1', 'beta2': 'self.beta2'}), True, 'import tensorflow as tf\n'), (443, 'os.path.join', 'os.path.join', (['checkpoint_dir', 'ckpt_name'], {}), False, 'import os\n'), (465, 'numpy.array', 'np.array', (['sample_images'], {}), True, 'import numpy as np\n'), (78, 'numpy.random.rand', 'np.random.rand', ([], {}), True, 'import numpy as np\n'), (81, 'numpy.random.rand', 'np.random.rand', ([], {}), True, 'import numpy as np\n'), (131, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[1, 2]'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.contrib.layers.conv2d', 'tf.contrib.layers.conv2d', (['layer_input', 'filters'], {'kernel_size': 'f_size', 'stride': 'stride', 'padding': 'padding'}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.contrib.layers.conv2d_transpose', 'tf.contrib.layers.conv2d_transpose', (['layer_input', 'filters', 'f_size'], {'stride': 'stride', 'padding': 'padding'}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['u'], {}), True, 'import tensorflow as tf\n'), (183, 'tensorflow.nn.relu', 'tf.nn.relu', (['u'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[1, 2]'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.contrib.layers.conv2d', 'tf.contrib.layers.conv2d', (['layer_input', 'filters'], {'kernel_size': 'f_size', 'stride': '(2)', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (311, 'tensorflow.ones_like', 'tf.ones_like', (['self.D_B_fake'], {}), True, 'import tensorflow as tf\n'), (312, 'tensorflow.ones_like', 'tf.ones_like', (['self.D_A_fake'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['d'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.contrib.layers.dropout', 'tf.contrib.layers.dropout', (['u'], {'keep_prob': 'dropout_rate'}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['d'], {}), True, 'import tensorflow as tf\n'), (391, 'numpy.array', 'np.array', (['batch_images'], {}), True, 'import numpy as np\n'), (132, 'tensorflow.nn.relu', 'tf.nn.relu', (['(-x)'], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'mean': '(1.0)', 'stddev': '(0.02)'}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.nn.relu', 'tf.nn.relu', (['(-x)'], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'mean': '(1.0)', 'stddev': '(0.02)'}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.sqrt', 'tf.sqrt', (['(var + epsilon)'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.sqrt', 'tf.sqrt', (['(var + epsilon)'], {}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (411, 'time.time', 'time.time', ([], {}), False, 'import time\n')]
SebastianJia/e2e-coref
9a68d6816cfb4ac00bca9c83f587891239215dce
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import operator import random import math import json import threading import numpy as np import tensorflow as tf import tensorflow_hub as hub import h5py import util import coref_ops import conll import metrics class CorefModel(object): def __init__(self, config): self.config = config self.context_embeddings = util.EmbeddingDictionary(config["context_embeddings"]) self.head_embeddings = util.EmbeddingDictionary(config["head_embeddings"], maybe_cache=self.context_embeddings) self.char_embedding_size = config["char_embedding_size"] self.char_dict = util.load_char_dict(config["char_vocab_path"]) self.max_span_width = config["max_span_width"] self.genres = { g:i for i,g in enumerate(config["genres"]) } if config["lm_path"]: self.lm_file = h5py.File(self.config["lm_path"], "r") else: self.lm_file = None self.lm_layers = self.config["lm_layers"] self.lm_size = self.config["lm_size"] self.eval_data = None # Load eval data lazily. input_props = [] input_props.append((tf.string, [None, None])) # Tokens. input_props.append((tf.float32, [None, None, self.context_embeddings.size])) # Context embeddings. input_props.append((tf.float32, [None, None, self.head_embeddings.size])) # Head embeddings. input_props.append((tf.float32, [None, None, self.lm_size, self.lm_layers])) # LM embeddings. input_props.append((tf.int32, [None, None, None])) # Character indices. input_props.append((tf.int32, [None])) # Text lengths. input_props.append((tf.int32, [None])) # Speaker IDs. input_props.append((tf.int32, [])) # Genre. input_props.append((tf.bool, [])) # Is training. input_props.append((tf.int32, [None])) # Gold starts. input_props.append((tf.int32, [None])) # Gold ends. input_props.append((tf.int32, [None])) # Cluster ids. self.queue_input_tensors = [tf.placeholder(dtype, shape) for dtype, shape in input_props] dtypes, shapes = zip(*input_props) queue = tf.PaddingFIFOQueue(capacity=10, dtypes=dtypes, shapes=shapes) self.enqueue_op = queue.enqueue(self.queue_input_tensors) self.input_tensors = queue.dequeue() self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors) self.global_step = tf.Variable(0, name="global_step", trainable=False) self.reset_global_step = tf.assign(self.global_step, 0) learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step, self.config["decay_frequency"], self.config["decay_rate"], staircase=True) trainable_params = tf.trainable_variables() gradients = tf.gradients(self.loss, trainable_params) gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"]) optimizers = { "adam" : tf.train.AdamOptimizer, "sgd" : tf.train.GradientDescentOptimizer } optimizer = optimizers[self.config["optimizer"]](learning_rate) self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step) def start_enqueue_thread(self, session): with open(self.config["train_path"]) as f: train_examples = [json.loads(jsonline) for jsonline in f.readlines()] def _enqueue_loop(): while True: random.shuffle(train_examples) for example in train_examples: tensorized_example = self.tensorize_example(example, is_training=True) feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) session.run(self.enqueue_op, feed_dict=feed_dict) enqueue_thread = threading.Thread(target=_enqueue_loop) enqueue_thread.daemon = True enqueue_thread.start() def restore(self, session): # Don't try to restore unused variables from the TF-Hub ELMo module. vars_to_restore = [v for v in tf.global_variables() if "module/" not in v.name] saver = tf.train.Saver(vars_to_restore) checkpoint_path = os.path.join(self.config["log_dir"], "model.max.ckpt") print("Restoring from {}".format(checkpoint_path)) session.run(tf.global_variables_initializer()) saver.restore(session, checkpoint_path) def load_lm_embeddings(self, doc_key): if self.lm_file is None: return np.zeros([0, 0, self.lm_size, self.lm_layers]) file_key = doc_key.replace("/", ":") group = self.lm_file[file_key] num_sentences = len(list(group.keys())) sentences = [group[str(i)][...] for i in range(num_sentences)] lm_emb = np.zeros([num_sentences, max(s.shape[0] for s in sentences), self.lm_size, self.lm_layers]) for i, s in enumerate(sentences): lm_emb[i, :s.shape[0], :, :] = s return lm_emb def tensorize_mentions(self, mentions): if len(mentions) > 0: starts, ends = zip(*mentions) else: starts, ends = [], [] return np.array(starts), np.array(ends) def tensorize_span_labels(self, tuples, label_dict): if len(tuples) > 0: starts, ends, labels = zip(*tuples) else: starts, ends, labels = [], [], [] return np.array(starts), np.array(ends), np.array([label_dict[c] for c in labels]) def tensorize_example(self, example, is_training): clusters = example["clusters"] gold_mentions = sorted(tuple(m) for m in util.flatten(clusters)) gold_mention_map = {m:i for i,m in enumerate(gold_mentions)} cluster_ids = np.zeros(len(gold_mentions)) for cluster_id, cluster in enumerate(clusters): for mention in cluster: cluster_ids[gold_mention_map[tuple(mention)]] = cluster_id + 1 sentences = example["sentences"] num_words = sum(len(s) for s in sentences) speakers = util.flatten(example["speakers"]) assert num_words == len(speakers) max_sentence_length = max(len(s) for s in sentences) max_word_length = max(max(max(len(w) for w in s) for s in sentences), max(self.config["filter_widths"])) text_len = np.array([len(s) for s in sentences]) tokens = [[""] * max_sentence_length for _ in sentences] context_word_emb = np.zeros([len(sentences), max_sentence_length, self.context_embeddings.size]) head_word_emb = np.zeros([len(sentences), max_sentence_length, self.head_embeddings.size]) char_index = np.zeros([len(sentences), max_sentence_length, max_word_length]) for i, sentence in enumerate(sentences): for j, word in enumerate(sentence): tokens[i][j] = word context_word_emb[i, j] = self.context_embeddings[word] head_word_emb[i, j] = self.head_embeddings[word] char_index[i, j, :len(word)] = [self.char_dict[c] for c in word] tokens = np.array(tokens) # print(context_word_emb[0][0].shape) # print(head_word_emb[0,0].shape) speaker_dict = { s:i for i,s in enumerate(set(speakers)) } speaker_ids = np.array([speaker_dict[s] for s in speakers]) doc_key = example["doc_key"] genre = self.genres[doc_key[:2]] gold_starts, gold_ends = self.tensorize_mentions(gold_mentions) lm_emb = self.load_lm_embeddings(doc_key) # print(lm_emb.shape) example_tensors = (tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids) if is_training and len(sentences) > self.config["max_training_sentences"]: return self.truncate_example(*example_tensors) else: return example_tensors def truncate_example(self, tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): max_training_sentences = self.config["max_training_sentences"] num_sentences = context_word_emb.shape[0] assert num_sentences > max_training_sentences sentence_offset = random.randint(0, num_sentences - max_training_sentences) word_offset = text_len[:sentence_offset].sum() num_words = text_len[sentence_offset:sentence_offset + max_training_sentences].sum() tokens = tokens[sentence_offset:sentence_offset + max_training_sentences, :] context_word_emb = context_word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :] head_word_emb = head_word_emb[sentence_offset:sentence_offset + max_training_sentences, :, :] lm_emb = lm_emb[sentence_offset:sentence_offset + max_training_sentences, :, :, :] char_index = char_index[sentence_offset:sentence_offset + max_training_sentences, :, :] text_len = text_len[sentence_offset:sentence_offset + max_training_sentences] speaker_ids = speaker_ids[word_offset: word_offset + num_words] gold_spans = np.logical_and(gold_ends >= word_offset, gold_starts < word_offset + num_words) gold_starts = gold_starts[gold_spans] - word_offset gold_ends = gold_ends[gold_spans] - word_offset cluster_ids = cluster_ids[gold_spans] return tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids def get_candidate_labels(self, candidate_starts, candidate_ends, labeled_starts, labeled_ends, labels): same_start = tf.equal(tf.expand_dims(labeled_starts, 1), tf.expand_dims(candidate_starts, 0)) # [num_labeled, num_candidates] same_end = tf.equal(tf.expand_dims(labeled_ends, 1), tf.expand_dims(candidate_ends, 0)) # [num_labeled, num_candidates] same_span = tf.logical_and(same_start, same_end) # [num_labeled, num_candidates] candidate_labels = tf.matmul(tf.expand_dims(labels, 0), tf.to_int32(same_span)) # [1, num_candidates] candidate_labels = tf.squeeze(candidate_labels, 0) # [num_candidates] return candidate_labels def get_dropout(self, dropout_rate, is_training): return 1 - (tf.to_float(is_training) * dropout_rate) def coarse_to_fine_pruning(self, top_span_emb, top_span_mention_scores, c): k = util.shape(top_span_emb, 0) top_span_range = tf.range(k) # [k] antecedent_offsets = tf.expand_dims(top_span_range, 1) - tf.expand_dims(top_span_range, 0) # [k, k] antecedents_mask = antecedent_offsets >= 1 # [k, k] fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.expand_dims(top_span_mention_scores, 0) # [k, k] fast_antecedent_scores += tf.log(tf.to_float(antecedents_mask)) # [k, k] fast_antecedent_scores += self.get_fast_antecedent_scores(top_span_emb) # [k, k] _, top_antecedents = tf.nn.top_k(fast_antecedent_scores, c, sorted=False) # [k, c] top_antecedents_mask = util.batch_gather(antecedents_mask, top_antecedents) # [k, c] top_fast_antecedent_scores = util.batch_gather(fast_antecedent_scores, top_antecedents) # [k, c] top_antecedent_offsets = util.batch_gather(antecedent_offsets, top_antecedents) # [k, c] return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets def distance_pruning(self, top_span_emb, top_span_mention_scores, c): k = util.shape(top_span_emb, 0) top_antecedent_offsets = tf.tile(tf.expand_dims(tf.range(c) + 1, 0), [k, 1]) # [k, c] raw_top_antecedents = tf.expand_dims(tf.range(k), 1) - top_antecedent_offsets # [k, c] top_antecedents_mask = raw_top_antecedents >= 0 # [k, c] top_antecedents = tf.maximum(raw_top_antecedents, 0) # [k, c] top_fast_antecedent_scores = tf.expand_dims(top_span_mention_scores, 1) + tf.gather(top_span_mention_scores, top_antecedents) # [k, c] top_fast_antecedent_scores += tf.log(tf.to_float(top_antecedents_mask)) # [k, c] return top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets def get_predictions_and_loss(self, tokens, context_word_emb, head_word_emb, lm_emb, char_index, text_len, speaker_ids, genre, is_training, gold_starts, gold_ends, cluster_ids): self.dropout = self.get_dropout(self.config["dropout_rate"], is_training) self.lexical_dropout = self.get_dropout(self.config["lexical_dropout_rate"], is_training) self.lstm_dropout = self.get_dropout(self.config["lstm_dropout_rate"], is_training) num_sentences = tf.shape(context_word_emb)[0] max_sentence_length = tf.shape(context_word_emb)[1] context_emb_list = [context_word_emb] head_emb_list = [head_word_emb] if self.config["char_embedding_size"] > 0: char_emb = tf.gather(tf.get_variable("char_embeddings", [len(self.char_dict), self.config["char_embedding_size"]]), char_index) # [num_sentences, max_sentence_length, max_word_length, emb] flattened_char_emb = tf.reshape(char_emb, [num_sentences * max_sentence_length, util.shape(char_emb, 2), util.shape(char_emb, 3)]) # [num_sentences * max_sentence_length, max_word_length, emb] flattened_aggregated_char_emb = util.cnn(flattened_char_emb, self.config["filter_widths"], self.config["filter_size"]) # [num_sentences * max_sentence_length, emb] aggregated_char_emb = tf.reshape(flattened_aggregated_char_emb, [num_sentences, max_sentence_length, util.shape(flattened_aggregated_char_emb, 1)]) # [num_sentences, max_sentence_length, emb] context_emb_list.append(aggregated_char_emb) head_emb_list.append(aggregated_char_emb) if not self.lm_file: elmo_module = hub.Module("https://tfhub.dev/google/elmo/2") lm_embeddings = elmo_module( inputs={"tokens": tokens, "sequence_len": text_len}, signature="tokens", as_dict=True) word_emb = lm_embeddings["word_emb"] # [num_sentences, max_sentence_length, 512] lm_emb = tf.stack([tf.concat([word_emb, word_emb], -1), lm_embeddings["lstm_outputs1"], lm_embeddings["lstm_outputs2"]], -1) # [num_sentences, max_sentence_length, 1024, 3] lm_emb_size = util.shape(lm_emb, 2) lm_num_layers = util.shape(lm_emb, 3) with tf.variable_scope("lm_aggregation"): self.lm_weights = tf.nn.softmax(tf.get_variable("lm_scores", [lm_num_layers], initializer=tf.constant_initializer(0.0))) self.lm_scaling = tf.get_variable("lm_scaling", [], initializer=tf.constant_initializer(1.0)) flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers]) flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_weights, 1)) # [num_sentences * max_sentence_length * emb, 1] aggregated_lm_emb = tf.reshape(flattened_aggregated_lm_emb, [num_sentences, max_sentence_length, lm_emb_size]) aggregated_lm_emb *= self.lm_scaling context_emb_list.append(aggregated_lm_emb) context_emb = tf.concat(context_emb_list, 2) # [num_sentences, max_sentence_length, emb] head_emb = tf.concat(head_emb_list, 2) # [num_sentences, max_sentence_length, emb] context_emb = tf.nn.dropout(context_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb] head_emb = tf.nn.dropout(head_emb, self.lexical_dropout) # [num_sentences, max_sentence_length, emb] text_len_mask = tf.sequence_mask(text_len, maxlen=max_sentence_length) # [num_sentence, max_sentence_length] context_outputs = self.lstm_contextualize(context_emb, text_len, text_len_mask) # [num_words, emb] num_words = util.shape(context_outputs, 0) genre_emb = tf.gather(tf.get_variable("genre_embeddings", [len(self.genres), self.config["feature_size"]]), genre) # [emb] sentence_indices = tf.tile(tf.expand_dims(tf.range(num_sentences), 1), [1, max_sentence_length]) # [num_sentences, max_sentence_length] flattened_sentence_indices = self.flatten_emb_by_sentence(sentence_indices, text_len_mask) # [num_words] flattened_head_emb = self.flatten_emb_by_sentence(head_emb, text_len_mask) # [num_words] candidate_starts = tf.tile(tf.expand_dims(tf.range(num_words), 1), [1, self.max_span_width]) # [num_words, max_span_width] candidate_ends = candidate_starts + tf.expand_dims(tf.range(self.max_span_width), 0) # [num_words, max_span_width] candidate_start_sentence_indices = tf.gather(flattened_sentence_indices, candidate_starts) # [num_words, max_span_width] candidate_end_sentence_indices = tf.gather(flattened_sentence_indices, tf.minimum(candidate_ends, num_words - 1)) # [num_words, max_span_width] candidate_mask = tf.logical_and(candidate_ends < num_words, tf.equal(candidate_start_sentence_indices, candidate_end_sentence_indices)) # [num_words, max_span_width] flattened_candidate_mask = tf.reshape(candidate_mask, [-1]) # [num_words * max_span_width] candidate_starts = tf.boolean_mask(tf.reshape(candidate_starts, [-1]), flattened_candidate_mask) # [num_candidates] candidate_ends = tf.boolean_mask(tf.reshape(candidate_ends, [-1]), flattened_candidate_mask) # [num_candidates] candidate_sentence_indices = tf.boolean_mask(tf.reshape(candidate_start_sentence_indices, [-1]), flattened_candidate_mask) # [num_candidates] candidate_cluster_ids = self.get_candidate_labels(candidate_starts, candidate_ends, gold_starts, gold_ends, cluster_ids) # [num_candidates] candidate_span_emb = self.get_span_emb(flattened_head_emb, context_outputs, candidate_starts, candidate_ends) # [num_candidates, emb] candidate_mention_scores = self.get_mention_scores(candidate_span_emb) # [k, 1] candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [k] k = tf.to_int32(tf.floor(tf.to_float(tf.shape(context_outputs)[0]) * self.config["top_span_ratio"])) top_span_indices = coref_ops.extract_spans(tf.expand_dims(candidate_mention_scores, 0), tf.expand_dims(candidate_starts, 0), tf.expand_dims(candidate_ends, 0), tf.expand_dims(k, 0), util.shape(context_outputs, 0), True) # [1, k] top_span_indices.set_shape([1, None]) top_span_indices = tf.squeeze(top_span_indices, 0) # [k] top_span_starts = tf.gather(candidate_starts, top_span_indices) # [k] top_span_ends = tf.gather(candidate_ends, top_span_indices) # [k] top_span_emb = tf.gather(candidate_span_emb, top_span_indices) # [k, emb] top_span_cluster_ids = tf.gather(candidate_cluster_ids, top_span_indices) # [k] top_span_mention_scores = tf.gather(candidate_mention_scores, top_span_indices) # [k] top_span_sentence_indices = tf.gather(candidate_sentence_indices, top_span_indices) # [k] top_span_speaker_ids = tf.gather(speaker_ids, top_span_starts) # [k] c = tf.minimum(self.config["max_top_antecedents"], k) if self.config["coarse_to_fine"]: top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets = self.coarse_to_fine_pruning(top_span_emb, top_span_mention_scores, c) else: top_antecedents, top_antecedents_mask, top_fast_antecedent_scores, top_antecedent_offsets = self.distance_pruning(top_span_emb, top_span_mention_scores, c) dummy_scores = tf.zeros([k, 1]) # [k, 1] for i in range(self.config["coref_depth"]): with tf.variable_scope("coref_layer", reuse=(i > 0)): top_antecedent_emb = tf.gather(top_span_emb, top_antecedents) # [k, c, emb] top_antecedent_scores = top_fast_antecedent_scores + self.get_slow_antecedent_scores(top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb) # [k, c] top_antecedent_weights = tf.nn.softmax(tf.concat([dummy_scores, top_antecedent_scores], 1)) # [k, c + 1] top_antecedent_emb = tf.concat([tf.expand_dims(top_span_emb, 1), top_antecedent_emb], 1) # [k, c + 1, emb] attended_span_emb = tf.reduce_sum(tf.expand_dims(top_antecedent_weights, 2) * top_antecedent_emb, 1) # [k, emb] with tf.variable_scope("f"): f = tf.sigmoid(util.projection(tf.concat([top_span_emb, attended_span_emb], 1), util.shape(top_span_emb, -1))) # [k, emb] top_span_emb = f * attended_span_emb + (1 - f) * top_span_emb # [k, emb] top_antecedent_scores = tf.concat([dummy_scores, top_antecedent_scores], 1) # [k, c + 1] top_antecedent_cluster_ids = tf.gather(top_span_cluster_ids, top_antecedents) # [k, c] top_antecedent_cluster_ids += tf.to_int32(tf.log(tf.to_float(top_antecedents_mask))) # [k, c] same_cluster_indicator = tf.equal(top_antecedent_cluster_ids, tf.expand_dims(top_span_cluster_ids, 1)) # [k, c] non_dummy_indicator = tf.expand_dims(top_span_cluster_ids > 0, 1) # [k, 1] pairwise_labels = tf.logical_and(same_cluster_indicator, non_dummy_indicator) # [k, c] dummy_labels = tf.logical_not(tf.reduce_any(pairwise_labels, 1, keepdims=True)) # [k, 1] top_antecedent_labels = tf.concat([dummy_labels, pairwise_labels], 1) # [k, c + 1] loss = self.softmax_loss(top_antecedent_scores, top_antecedent_labels) # [k] loss = tf.reduce_sum(loss) # [] return [candidate_starts, candidate_ends, candidate_mention_scores, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores], loss def get_span_emb(self, head_emb, context_outputs, span_starts, span_ends): span_emb_list = [] span_start_emb = tf.gather(context_outputs, span_starts) # [k, emb] span_emb_list.append(span_start_emb) span_end_emb = tf.gather(context_outputs, span_ends) # [k, emb] span_emb_list.append(span_end_emb) span_width = 1 + span_ends - span_starts # [k] if self.config["use_features"]: span_width_index = span_width - 1 # [k] span_width_emb = tf.gather(tf.get_variable("span_width_embeddings", [self.config["max_span_width"], self.config["feature_size"]]), span_width_index) # [k, emb] span_width_emb = tf.nn.dropout(span_width_emb, self.dropout) span_emb_list.append(span_width_emb) if self.config["model_heads"]: span_indices = tf.expand_dims(tf.range(self.config["max_span_width"]), 0) + tf.expand_dims(span_starts, 1) # [k, max_span_width] span_indices = tf.minimum(util.shape(context_outputs, 0) - 1, span_indices) # [k, max_span_width] span_text_emb = tf.gather(head_emb, span_indices) # [k, max_span_width, emb] with tf.variable_scope("head_scores"): self.head_scores = util.projection(context_outputs, 1) # [num_words, 1] span_head_scores = tf.gather(self.head_scores, span_indices) # [k, max_span_width, 1] span_mask = tf.expand_dims(tf.sequence_mask(span_width, self.config["max_span_width"], dtype=tf.float32), 2) # [k, max_span_width, 1] span_head_scores += tf.log(span_mask) # [k, max_span_width, 1] span_attention = tf.nn.softmax(span_head_scores, 1) # [k, max_span_width, 1] span_head_emb = tf.reduce_sum(span_attention * span_text_emb, 1) # [k, emb] span_emb_list.append(span_head_emb) span_emb = tf.concat(span_emb_list, 1) # [k, emb] return span_emb # [k, emb] def get_mention_scores(self, span_emb): with tf.variable_scope("mention_scores"): return util.ffnn(span_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, 1] def softmax_loss(self, antecedent_scores, antecedent_labels): gold_scores = antecedent_scores + tf.log(tf.to_float(antecedent_labels)) # [k, max_ant + 1] marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [k] log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [k] return log_norm - marginalized_gold_scores # [k] def bucket_distance(self, distances): """ Places the given values (designed for distances) into 10 semi-logscale buckets: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+]. """ logspace_idx = tf.to_int32(tf.floor(tf.log(tf.to_float(distances))/math.log(2))) + 3 use_identity = tf.to_int32(distances <= 4) combined_idx = use_identity * distances + (1 - use_identity) * logspace_idx return tf.clip_by_value(combined_idx, 0, 9) def get_slow_antecedent_scores(self, top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb): k = util.shape(top_span_emb, 0) c = util.shape(top_antecedents, 1) feature_emb_list = [] if self.config["use_metadata"]: top_antecedent_speaker_ids = tf.gather(top_span_speaker_ids, top_antecedents) # [k, c] same_speaker = tf.equal(tf.expand_dims(top_span_speaker_ids, 1), top_antecedent_speaker_ids) # [k, c] speaker_pair_emb = tf.gather(tf.get_variable("same_speaker_emb", [2, self.config["feature_size"]]), tf.to_int32(same_speaker)) # [k, c, emb] feature_emb_list.append(speaker_pair_emb) tiled_genre_emb = tf.tile(tf.expand_dims(tf.expand_dims(genre_emb, 0), 0), [k, c, 1]) # [k, c, emb] feature_emb_list.append(tiled_genre_emb) if self.config["use_features"]: antecedent_distance_buckets = self.bucket_distance(top_antecedent_offsets) # [k, c] antecedent_distance_emb = tf.gather(tf.get_variable("antecedent_distance_emb", [10, self.config["feature_size"]]), antecedent_distance_buckets) # [k, c] feature_emb_list.append(antecedent_distance_emb) feature_emb = tf.concat(feature_emb_list, 2) # [k, c, emb] feature_emb = tf.nn.dropout(feature_emb, self.dropout) # [k, c, emb] target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb] similarity_emb = top_antecedent_emb * target_emb # [k, c, emb] target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb] pair_emb = tf.concat([target_emb, top_antecedent_emb, similarity_emb, feature_emb], 2) # [k, c, emb] with tf.variable_scope("slow_antecedent_scores"): slow_antecedent_scores = util.ffnn(pair_emb, self.config["ffnn_depth"], self.config["ffnn_size"], 1, self.dropout) # [k, c, 1] slow_antecedent_scores = tf.squeeze(slow_antecedent_scores, 2) # [k, c] return slow_antecedent_scores # [k, c] def get_fast_antecedent_scores(self, top_span_emb): with tf.variable_scope("src_projection"): source_top_span_emb = tf.nn.dropout(util.projection(top_span_emb, util.shape(top_span_emb, -1)), self.dropout) # [k, emb] target_top_span_emb = tf.nn.dropout(top_span_emb, self.dropout) # [k, emb] return tf.matmul(source_top_span_emb, target_top_span_emb, transpose_b=True) # [k, k] def flatten_emb_by_sentence(self, emb, text_len_mask): num_sentences = tf.shape(emb)[0] max_sentence_length = tf.shape(emb)[1] emb_rank = len(emb.get_shape()) if emb_rank == 2: flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length]) elif emb_rank == 3: flattened_emb = tf.reshape(emb, [num_sentences * max_sentence_length, util.shape(emb, 2)]) else: raise ValueError("Unsupported rank: {}".format(emb_rank)) return tf.boolean_mask(flattened_emb, tf.reshape(text_len_mask, [num_sentences * max_sentence_length])) def lstm_contextualize(self, text_emb, text_len, text_len_mask): num_sentences = tf.shape(text_emb)[0] current_inputs = text_emb # [num_sentences, max_sentence_length, emb] for layer in range(self.config["contextualization_layers"]): with tf.variable_scope("layer_{}".format(layer)): with tf.variable_scope("fw_cell"): cell_fw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout) with tf.variable_scope("bw_cell"): cell_bw = util.CustomLSTMCell(self.config["contextualization_size"], num_sentences, self.lstm_dropout) state_fw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_fw.initial_state.c, [num_sentences, 1]), tf.tile(cell_fw.initial_state.h, [num_sentences, 1])) state_bw = tf.contrib.rnn.LSTMStateTuple(tf.tile(cell_bw.initial_state.c, [num_sentences, 1]), tf.tile(cell_bw.initial_state.h, [num_sentences, 1])) (fw_outputs, bw_outputs), _ = tf.nn.bidirectional_dynamic_rnn( cell_fw=cell_fw, cell_bw=cell_bw, inputs=current_inputs, sequence_length=text_len, initial_state_fw=state_fw, initial_state_bw=state_bw) text_outputs = tf.concat([fw_outputs, bw_outputs], 2) # [num_sentences, max_sentence_length, emb] text_outputs = tf.nn.dropout(text_outputs, self.lstm_dropout) if layer > 0: highway_gates = tf.sigmoid(util.projection(text_outputs, util.shape(text_outputs, 2))) # [num_sentences, max_sentence_length, emb] text_outputs = highway_gates * text_outputs + (1 - highway_gates) * current_inputs current_inputs = text_outputs return self.flatten_emb_by_sentence(text_outputs, text_len_mask) def get_predicted_antecedents(self, antecedents, antecedent_scores): predicted_antecedents = [] for i, index in enumerate(np.argmax(antecedent_scores, axis=1) - 1): if index < 0: predicted_antecedents.append(-1) else: predicted_antecedents.append(antecedents[i, index]) return predicted_antecedents def get_predicted_clusters(self, top_span_starts, top_span_ends, predicted_antecedents): mention_to_predicted = {} predicted_clusters = [] for i, predicted_index in enumerate(predicted_antecedents): if predicted_index < 0: continue assert i > predicted_index predicted_antecedent = (int(top_span_starts[predicted_index]), int(top_span_ends[predicted_index])) if predicted_antecedent in mention_to_predicted: predicted_cluster = mention_to_predicted[predicted_antecedent] else: predicted_cluster = len(predicted_clusters) predicted_clusters.append([predicted_antecedent]) mention_to_predicted[predicted_antecedent] = predicted_cluster mention = (int(top_span_starts[i]), int(top_span_ends[i])) predicted_clusters[predicted_cluster].append(mention) mention_to_predicted[mention] = predicted_cluster predicted_clusters = [tuple(pc) for pc in predicted_clusters] mention_to_predicted = { m:predicted_clusters[i] for m,i in mention_to_predicted.items() } return predicted_clusters, mention_to_predicted def evaluate_coref(self, top_span_starts, top_span_ends, predicted_antecedents, gold_clusters, evaluator): gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters] mention_to_gold = {} for gc in gold_clusters: for mention in gc: mention_to_gold[mention] = gc predicted_clusters, mention_to_predicted = self.get_predicted_clusters(top_span_starts, top_span_ends, predicted_antecedents) evaluator.update(predicted_clusters, gold_clusters, mention_to_predicted, mention_to_gold) return predicted_clusters def load_eval_data(self): if self.eval_data is None: def load_line(line): example = json.loads(line) return self.tensorize_example(example, is_training=False), example with open(self.config["eval_path"]) as f: self.eval_data = [load_line(l) for l in f.readlines()] num_words = sum(tensorized_example[2].sum() for tensorized_example, _ in self.eval_data) print("Loaded {} eval examples.".format(len(self.eval_data))) def evaluate(self, session, official_stdout=False): self.load_eval_data() coref_predictions = {} coref_evaluator = metrics.CorefEvaluator() for example_num, (tensorized_example, example) in enumerate(self.eval_data): _, _, _, _, _, _, _, _, _, gold_starts, gold_ends, _ = tensorized_example feed_dict = {i:t for i,t in zip(self.input_tensors, tensorized_example)} candidate_starts, candidate_ends, candidate_mention_scores, top_span_starts, top_span_ends, top_antecedents, top_antecedent_scores = session.run(self.predictions, feed_dict=feed_dict) predicted_antecedents = self.get_predicted_antecedents(top_antecedents, top_antecedent_scores) coref_predictions[example["doc_key"]] = self.evaluate_coref(top_span_starts, top_span_ends, predicted_antecedents, example["clusters"], coref_evaluator) if example_num % 10 == 0: print("Evaluated {}/{} examples.".format(example_num + 1, len(self.eval_data))) summary_dict = {} conll_results = conll.evaluate_conll(self.config["conll_eval_path"], coref_predictions, official_stdout) average_f1 = sum(results["f"] for results in conll_results.values()) / len(conll_results) summary_dict["Average F1 (conll)"] = average_f1 print("Average F1 (conll): {:.2f}%".format(average_f1)) p,r,f = coref_evaluator.get_prf() summary_dict["Average F1 (py)"] = f print("Average F1 (py): {:.2f}%".format(f * 100)) summary_dict["Average precision (py)"] = p print("Average precision (py): {:.2f}%".format(p * 100)) summary_dict["Average recall (py)"] = r print("Average recall (py): {:.2f}%".format(r * 100)) return util.make_summary(summary_dict), average_f1
[ "tensorflow.get_variable", "tensorflow.concat", "tensorflow.zeros", "tensorflow.reduce_sum", "tensorflow.minimum", "tensorflow.equal", "tensorflow.global_variables", "tensorflow.nn.bidirectional_dynamic_rnn", "tensorflow.to_int32", "tensorflow.reduce_logsumexp", "tensorflow.Variable", "tensorflow.gradients", "tensorflow.squeeze", "tensorflow.train.exponential_decay", "tensorflow.nn.top_k", "tensorflow.gather", "numpy.argmax", "tensorflow.to_float", "tensorflow.trainable_variables", "tensorflow.train.Saver", "numpy.zeros", "tensorflow.tile", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.shape", "tensorflow.reduce_any", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.logical_and", "numpy.array", "tensorflow.sequence_mask", "tensorflow.clip_by_value", "tensorflow.nn.softmax", "tensorflow.range", "tensorflow.maximum", "tensorflow.assign", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.clip_by_global_norm", "tensorflow.log", "tensorflow.PaddingFIFOQueue", "tensorflow.variable_scope", "tensorflow.logical_and" ]
coref_model.py
[(24, 'util.EmbeddingDictionary', 'util.EmbeddingDictionary', (["config['context_embeddings']"], {}), False, 'import util\n'), (25, 'util.EmbeddingDictionary', 'util.EmbeddingDictionary', (["config['head_embeddings']"], {'maybe_cache': 'self.context_embeddings'}), False, 'import util\n'), (27, 'util.load_char_dict', 'util.load_char_dict', (["config['char_vocab_path']"], {}), False, 'import util\n'), (54, 'tensorflow.PaddingFIFOQueue', 'tf.PaddingFIFOQueue', ([], {'capacity': '(10)', 'dtypes': 'dtypes', 'shapes': 'shapes'}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.assign', 'tf.assign', (['self.global_step', '(0)'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (["self.config['learning_rate']", 'self.global_step', "self.config['decay_frequency']", "self.config['decay_rate']"], {'staircase': '(True)'}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.gradients', 'tf.gradients', (['self.loss', 'trainable_params'], {}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['gradients', "self.config['max_gradient_norm']"], {}), True, 'import tensorflow as tf\n'), (83, 'threading.Thread', 'threading.Thread', ([], {'target': '_enqueue_loop'}), False, 'import threading\n'), (90, 'tensorflow.train.Saver', 'tf.train.Saver', (['vars_to_restore'], {}), True, 'import tensorflow as tf\n'), (91, 'os.path.join', 'os.path.join', (["self.config['log_dir']", '"""model.max.ckpt"""'], {}), False, 'import os\n'), (134, 'util.flatten', 'util.flatten', (["example['speakers']"], {}), False, 'import util\n'), (151, 'numpy.array', 'np.array', (['tokens'], {}), True, 'import numpy as np\n'), (156, 'numpy.array', 'np.array', (['[speaker_dict[s] for s in speakers]'], {}), True, 'import numpy as np\n'), (177, 'random.randint', 'random.randint', (['(0)', '(num_sentences - max_training_sentences)'], {}), False, 'import random\n'), (188, 'numpy.logical_and', 'np.logical_and', (['(gold_ends >= word_offset)', '(gold_starts < word_offset + num_words)'], {}), True, 'import numpy as np\n'), (198, 'tensorflow.logical_and', 'tf.logical_and', (['same_start', 'same_end'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.squeeze', 'tf.squeeze', (['candidate_labels', '(0)'], {}), True, 'import tensorflow as tf\n'), (207, 'util.shape', 'util.shape', (['top_span_emb', '(0)'], {}), False, 'import util\n'), (208, 'tensorflow.range', 'tf.range', (['k'], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.nn.top_k', 'tf.nn.top_k', (['fast_antecedent_scores', 'c'], {'sorted': '(False)'}), True, 'import tensorflow as tf\n'), (216, 'util.batch_gather', 'util.batch_gather', (['antecedents_mask', 'top_antecedents'], {}), False, 'import util\n'), (217, 'util.batch_gather', 'util.batch_gather', (['fast_antecedent_scores', 'top_antecedents'], {}), False, 'import util\n'), (218, 'util.batch_gather', 'util.batch_gather', (['antecedent_offsets', 'top_antecedents'], {}), False, 'import util\n'), (222, 'util.shape', 'util.shape', (['top_span_emb', '(0)'], {}), False, 'import util\n'), (226, 'tensorflow.maximum', 'tf.maximum', (['raw_top_antecedents', '(0)'], {}), True, 'import tensorflow as tf\n'), (260, 'util.shape', 'util.shape', (['lm_emb', '(2)'], {}), False, 'import util\n'), (261, 'util.shape', 'util.shape', (['lm_emb', '(3)'], {}), False, 'import util\n'), (265, 'tensorflow.reshape', 'tf.reshape', (['lm_emb', '[num_sentences * max_sentence_length * lm_emb_size, lm_num_layers]'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['flattened_aggregated_lm_emb', '[num_sentences, max_sentence_length, lm_emb_size]'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.concat', 'tf.concat', (['context_emb_list', '(2)'], {}), True, 'import tensorflow as tf\n'), (272, 'tensorflow.concat', 'tf.concat', (['head_emb_list', '(2)'], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['context_emb', 'self.lexical_dropout'], {}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['head_emb', 'self.lexical_dropout'], {}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['text_len'], {'maxlen': 'max_sentence_length'}), True, 'import tensorflow as tf\n'), (279, 'util.shape', 'util.shape', (['context_outputs', '(0)'], {}), False, 'import util\n'), (289, 'tensorflow.gather', 'tf.gather', (['flattened_sentence_indices', 'candidate_starts'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.reshape', 'tf.reshape', (['candidate_mask', '[-1]'], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.squeeze', 'tf.squeeze', (['candidate_mention_scores', '(1)'], {}), True, 'import tensorflow as tf\n'), (311, 'tensorflow.squeeze', 'tf.squeeze', (['top_span_indices', '(0)'], {}), True, 'import tensorflow as tf\n'), (313, 'tensorflow.gather', 'tf.gather', (['candidate_starts', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (314, 'tensorflow.gather', 'tf.gather', (['candidate_ends', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (315, 'tensorflow.gather', 'tf.gather', (['candidate_span_emb', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (316, 'tensorflow.gather', 'tf.gather', (['candidate_cluster_ids', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.gather', 'tf.gather', (['candidate_mention_scores', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (318, 'tensorflow.gather', 'tf.gather', (['candidate_sentence_indices', 'top_span_indices'], {}), True, 'import tensorflow as tf\n'), (319, 'tensorflow.gather', 'tf.gather', (['speaker_ids', 'top_span_starts'], {}), True, 'import tensorflow as tf\n'), (321, 'tensorflow.minimum', 'tf.minimum', (["self.config['max_top_antecedents']", 'k'], {}), True, 'import tensorflow as tf\n'), (328, 'tensorflow.zeros', 'tf.zeros', (['[k, 1]'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.concat', 'tf.concat', (['[dummy_scores, top_antecedent_scores]', '(1)'], {}), True, 'import tensorflow as tf\n'), (342, 'tensorflow.gather', 'tf.gather', (['top_span_cluster_ids', 'top_antecedents'], {}), True, 'import tensorflow as tf\n'), (345, 'tensorflow.expand_dims', 'tf.expand_dims', (['(top_span_cluster_ids > 0)', '(1)'], {}), True, 'import tensorflow as tf\n'), (346, 'tensorflow.logical_and', 'tf.logical_and', (['same_cluster_indicator', 'non_dummy_indicator'], {}), True, 'import tensorflow as tf\n'), (348, 'tensorflow.concat', 'tf.concat', (['[dummy_labels, pairwise_labels]', '(1)'], {}), True, 'import tensorflow as tf\n'), (350, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss'], {}), True, 'import tensorflow as tf\n'), (357, 'tensorflow.gather', 'tf.gather', (['context_outputs', 'span_starts'], {}), True, 'import tensorflow as tf\n'), (360, 'tensorflow.gather', 'tf.gather', (['context_outputs', 'span_ends'], {}), True, 'import tensorflow as tf\n'), (384, 'tensorflow.concat', 'tf.concat', (['span_emb_list', '(1)'], {}), True, 'import tensorflow as tf\n'), (393, 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['gold_scores', '[1]'], {}), True, 'import tensorflow as tf\n'), (394, 'tensorflow.reduce_logsumexp', 'tf.reduce_logsumexp', (['antecedent_scores', '[1]'], {}), True, 'import tensorflow as tf\n'), (403, 'tensorflow.to_int32', 'tf.to_int32', (['(distances <= 4)'], {}), True, 'import tensorflow as tf\n'), (405, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['combined_idx', '(0)', '(9)'], {}), True, 'import tensorflow as tf\n'), (408, 'util.shape', 'util.shape', (['top_span_emb', '(0)'], {}), False, 'import util\n'), (409, 'util.shape', 'util.shape', (['top_antecedents', '(1)'], {}), False, 'import util\n'), (427, 'tensorflow.concat', 'tf.concat', (['feature_emb_list', '(2)'], {}), True, 'import tensorflow as tf\n'), (428, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['feature_emb', 'self.dropout'], {}), True, 'import tensorflow as tf\n'), (430, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_emb', '(1)'], {}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.tile', 'tf.tile', (['target_emb', '[1, c, 1]'], {}), True, 'import tensorflow as tf\n'), (434, 'tensorflow.concat', 'tf.concat', (['[target_emb, top_antecedent_emb, similarity_emb, feature_emb]', '(2)'], {}), True, 'import tensorflow as tf\n'), (438, 'tensorflow.squeeze', 'tf.squeeze', (['slow_antecedent_scores', '(2)'], {}), True, 'import tensorflow as tf\n'), (444, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['top_span_emb', 'self.dropout'], {}), True, 'import tensorflow as tf\n'), (445, 'tensorflow.matmul', 'tf.matmul', (['source_top_span_emb', 'target_top_span_emb'], {'transpose_b': '(True)'}), True, 'import tensorflow as tf\n'), (549, 'metrics.CorefEvaluator', 'metrics.CorefEvaluator', ([], {}), False, 'import metrics\n'), (561, 'conll.evaluate_conll', 'conll.evaluate_conll', (["self.config['conll_eval_path']", 'coref_predictions', 'official_stdout'], {}), False, 'import conll\n'), (31, 'h5py.File', 'h5py.File', (["self.config['lm_path']", '"""r"""'], {}), False, 'import h5py\n'), (52, 'tensorflow.placeholder', 'tf.placeholder', (['dtype', 'shape'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (98, 'numpy.zeros', 'np.zeros', (['[0, 0, self.lm_size, self.lm_layers]'], {}), True, 'import numpy as np\n'), (113, 'numpy.array', 'np.array', (['starts'], {}), True, 'import numpy as np\n'), (113, 'numpy.array', 'np.array', (['ends'], {}), True, 'import numpy as np\n'), (120, 'numpy.array', 'np.array', (['starts'], {}), True, 'import numpy as np\n'), (120, 'numpy.array', 'np.array', (['ends'], {}), True, 'import numpy as np\n'), (120, 'numpy.array', 'np.array', (['[label_dict[c] for c in labels]'], {}), True, 'import numpy as np\n'), (196, 'tensorflow.expand_dims', 'tf.expand_dims', (['labeled_starts', '(1)'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.expand_dims', 'tf.expand_dims', (['candidate_starts', '(0)'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.expand_dims', 'tf.expand_dims', (['labeled_ends', '(1)'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.expand_dims', 'tf.expand_dims', (['candidate_ends', '(0)'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.expand_dims', 'tf.expand_dims', (['labels', '(0)'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.to_int32', 'tf.to_int32', (['same_span'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_range', '(1)'], {}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_range', '(0)'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_mention_scores', '(1)'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_mention_scores', '(0)'], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.to_float', 'tf.to_float', (['antecedents_mask'], {}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_mention_scores', '(1)'], {}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.gather', 'tf.gather', (['top_span_mention_scores', 'top_antecedents'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.to_float', 'tf.to_float', (['top_antecedents_mask'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.shape', 'tf.shape', (['context_word_emb'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.shape', 'tf.shape', (['context_word_emb'], {}), True, 'import tensorflow as tf\n'), (246, 'util.cnn', 'util.cnn', (['flattened_char_emb', "self.config['filter_widths']", "self.config['filter_size']"], {}), False, 'import util\n'), (252, 'tensorflow_hub.Module', 'hub.Module', (['"""https://tfhub.dev/google/elmo/2"""'], {}), True, 'import tensorflow_hub as hub\n'), (262, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""lm_aggregation"""'], {}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.expand_dims', 'tf.expand_dims', (['self.lm_weights', '(1)'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.minimum', 'tf.minimum', (['candidate_ends', '(num_words - 1)'], {}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.equal', 'tf.equal', (['candidate_start_sentence_indices', 'candidate_end_sentence_indices'], {}), True, 'import tensorflow as tf\n'), (293, 'tensorflow.reshape', 'tf.reshape', (['candidate_starts', '[-1]'], {}), True, 'import tensorflow as tf\n'), (294, 'tensorflow.reshape', 'tf.reshape', (['candidate_ends', '[-1]'], {}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.reshape', 'tf.reshape', (['candidate_start_sentence_indices', '[-1]'], {}), True, 'import tensorflow as tf\n'), (304, 'tensorflow.expand_dims', 'tf.expand_dims', (['candidate_mention_scores', '(0)'], {}), True, 'import tensorflow as tf\n'), (305, 'tensorflow.expand_dims', 'tf.expand_dims', (['candidate_starts', '(0)'], {}), True, 'import tensorflow as tf\n'), (306, 'tensorflow.expand_dims', 'tf.expand_dims', (['candidate_ends', '(0)'], {}), True, 'import tensorflow as tf\n'), (307, 'tensorflow.expand_dims', 'tf.expand_dims', (['k', '(0)'], {}), True, 'import tensorflow as tf\n'), (308, 'util.shape', 'util.shape', (['context_outputs', '(0)'], {}), False, 'import util\n'), (344, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_cluster_ids', '(1)'], {}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.reduce_any', 'tf.reduce_any', (['pairwise_labels', '(1)'], {'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (368, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['span_width_emb', 'self.dropout'], {}), True, 'import tensorflow as tf\n'), (374, 'tensorflow.gather', 'tf.gather', (['head_emb', 'span_indices'], {}), True, 'import tensorflow as tf\n'), (377, 'tensorflow.gather', 'tf.gather', (['self.head_scores', 'span_indices'], {}), True, 'import tensorflow as tf\n'), (379, 'tensorflow.log', 'tf.log', (['span_mask'], {}), True, 'import tensorflow as tf\n'), (380, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['span_head_scores', '(1)'], {}), True, 'import tensorflow as tf\n'), (381, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(span_attention * span_text_emb)', '(1)'], {}), True, 'import tensorflow as tf\n'), (388, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""mention_scores"""'], {}), True, 'import tensorflow as tf\n'), (389, 'util.ffnn', 'util.ffnn', (['span_emb', "self.config['ffnn_depth']", "self.config['ffnn_size']", '(1)', 'self.dropout'], {}), False, 'import util\n'), (414, 'tensorflow.gather', 'tf.gather', (['top_span_speaker_ids', 'top_antecedents'], {}), True, 'import tensorflow as tf\n'), (436, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""slow_antecedent_scores"""'], {}), True, 'import tensorflow as tf\n'), (437, 'util.ffnn', 'util.ffnn', (['pair_emb', "self.config['ffnn_depth']", "self.config['ffnn_size']", '(1)', 'self.dropout'], {}), False, 'import util\n'), (442, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""src_projection"""'], {}), True, 'import tensorflow as tf\n'), (448, 'tensorflow.shape', 'tf.shape', (['emb'], {}), True, 'import tensorflow as tf\n'), (449, 'tensorflow.shape', 'tf.shape', (['emb'], {}), True, 'import tensorflow as tf\n'), (453, 'tensorflow.reshape', 'tf.reshape', (['emb', '[num_sentences * max_sentence_length]'], {}), True, 'import tensorflow as tf\n'), (458, 'tensorflow.reshape', 'tf.reshape', (['text_len_mask', '[num_sentences * max_sentence_length]'], {}), True, 'import tensorflow as tf\n'), (461, 'tensorflow.shape', 'tf.shape', (['text_emb'], {}), True, 'import tensorflow as tf\n'), (574, 'util.make_summary', 'util.make_summary', (['summary_dict'], {}), False, 'import util\n'), (75, 'json.loads', 'json.loads', (['jsonline'], {}), False, 'import json\n'), (78, 'random.shuffle', 'random.shuffle', (['train_examples'], {}), False, 'import random\n'), (89, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.to_float', 'tf.to_float', (['is_training'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.range', 'tf.range', (['k'], {}), True, 'import tensorflow as tf\n'), (283, 'tensorflow.range', 'tf.range', (['num_sentences'], {}), True, 'import tensorflow as tf\n'), (287, 'tensorflow.range', 'tf.range', (['num_words'], {}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.range', 'tf.range', (['self.max_span_width'], {}), True, 'import tensorflow as tf\n'), (330, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""coref_layer"""'], {'reuse': '(i > 0)'}), True, 'import tensorflow as tf\n'), (331, 'tensorflow.gather', 'tf.gather', (['top_span_emb', 'top_antecedents'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.to_float', 'tf.to_float', (['top_antecedents_mask'], {}), True, 'import tensorflow as tf\n'), (367, 'tensorflow.get_variable', 'tf.get_variable', (['"""span_width_embeddings"""', "[self.config['max_span_width'], self.config['feature_size']]"], {}), True, 'import tensorflow as tf\n'), (372, 'tensorflow.expand_dims', 'tf.expand_dims', (['span_starts', '(1)'], {}), True, 'import tensorflow as tf\n'), (375, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""head_scores"""'], {}), True, 'import tensorflow as tf\n'), (376, 'util.projection', 'util.projection', (['context_outputs', '(1)'], {}), False, 'import util\n'), (378, 'tensorflow.sequence_mask', 'tf.sequence_mask', (['span_width', "self.config['max_span_width']"], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (392, 'tensorflow.to_float', 'tf.to_float', (['antecedent_labels'], {}), True, 'import tensorflow as tf\n'), (415, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_speaker_ids', '(1)'], {}), True, 'import tensorflow as tf\n'), (416, 'tensorflow.get_variable', 'tf.get_variable', (['"""same_speaker_emb"""', "[2, self.config['feature_size']]"], {}), True, 'import tensorflow as tf\n'), (416, 'tensorflow.to_int32', 'tf.to_int32', (['same_speaker'], {}), True, 'import tensorflow as tf\n'), (424, 'tensorflow.get_variable', 'tf.get_variable', (['"""antecedent_distance_emb"""', "[10, self.config['feature_size']]"], {}), True, 'import tensorflow as tf\n'), (474, 'tensorflow.nn.bidirectional_dynamic_rnn', 'tf.nn.bidirectional_dynamic_rnn', ([], {'cell_fw': 'cell_fw', 'cell_bw': 'cell_bw', 'inputs': 'current_inputs', 'sequence_length': 'text_len', 'initial_state_fw': 'state_fw', 'initial_state_bw': 'state_bw'}), True, 'import tensorflow as tf\n'), (482, 'tensorflow.concat', 'tf.concat', (['[fw_outputs, bw_outputs]', '(2)'], {}), True, 'import tensorflow as tf\n'), (483, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['text_outputs', 'self.lstm_dropout'], {}), True, 'import tensorflow as tf\n'), (493, 'numpy.argmax', 'np.argmax', (['antecedent_scores'], {'axis': '(1)'}), True, 'import numpy as np\n'), (538, 'json.loads', 'json.loads', (['line'], {}), False, 'import json\n'), (125, 'util.flatten', 'util.flatten', (['clusters'], {}), False, 'import util\n'), (223, 'tensorflow.range', 'tf.range', (['c'], {}), True, 'import tensorflow as tf\n'), (245, 'util.shape', 'util.shape', (['char_emb', '(2)'], {}), False, 'import util\n'), (245, 'util.shape', 'util.shape', (['char_emb', '(3)'], {}), False, 'import util\n'), (247, 'util.shape', 'util.shape', (['flattened_aggregated_char_emb', '(1)'], {}), False, 'import util\n'), (257, 'tensorflow.concat', 'tf.concat', (['[word_emb, word_emb]', '(-1)'], {}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.concat', 'tf.concat', (['[dummy_scores, top_antecedent_scores]', '(1)'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""f"""'], {}), True, 'import tensorflow as tf\n'), (372, 'tensorflow.range', 'tf.range', (["self.config['max_span_width']"], {}), True, 'import tensorflow as tf\n'), (373, 'util.shape', 'util.shape', (['context_outputs', '(0)'], {}), False, 'import util\n'), (419, 'tensorflow.expand_dims', 'tf.expand_dims', (['genre_emb', '(0)'], {}), True, 'import tensorflow as tf\n'), (443, 'util.shape', 'util.shape', (['top_span_emb', '(-1)'], {}), False, 'import util\n'), (467, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fw_cell"""'], {}), True, 'import tensorflow as tf\n'), (468, 'util.CustomLSTMCell', 'util.CustomLSTMCell', (["self.config['contextualization_size']", 'num_sentences', 'self.lstm_dropout'], {}), False, 'import util\n'), (469, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""bw_cell"""'], {}), True, 'import tensorflow as tf\n'), (470, 'util.CustomLSTMCell', 'util.CustomLSTMCell', (["self.config['contextualization_size']", 'num_sentences', 'self.lstm_dropout'], {}), False, 'import util\n'), (471, 'tensorflow.tile', 'tf.tile', (['cell_fw.initial_state.c', '[num_sentences, 1]'], {}), True, 'import tensorflow as tf\n'), (471, 'tensorflow.tile', 'tf.tile', (['cell_fw.initial_state.h', '[num_sentences, 1]'], {}), True, 'import tensorflow as tf\n'), (472, 'tensorflow.tile', 'tf.tile', (['cell_bw.initial_state.c', '[num_sentences, 1]'], {}), True, 'import tensorflow as tf\n'), (472, 'tensorflow.tile', 'tf.tile', (['cell_bw.initial_state.h', '[num_sentences, 1]'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (334, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_span_emb', '(1)'], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.expand_dims', 'tf.expand_dims', (['top_antecedent_weights', '(2)'], {}), True, 'import tensorflow as tf\n'), (402, 'math.log', 'math.log', (['(2)'], {}), False, 'import math\n'), (455, 'util.shape', 'util.shape', (['emb', '(2)'], {}), False, 'import util\n'), (303, 'tensorflow.shape', 'tf.shape', (['context_outputs'], {}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.concat', 'tf.concat', (['[top_span_emb, attended_span_emb]', '(1)'], {}), True, 'import tensorflow as tf\n'), (337, 'util.shape', 'util.shape', (['top_span_emb', '(-1)'], {}), False, 'import util\n'), (402, 'tensorflow.to_float', 'tf.to_float', (['distances'], {}), True, 'import tensorflow as tf\n'), (485, 'util.shape', 'util.shape', (['text_outputs', '(2)'], {}), False, 'import util\n')]
sakibguy/models
662f392677be0e6822eb9852a57f06b3fd1513bf
# Copyright 2022 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. """Learning rate schedule.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from official.modeling.hyperparams import params_dict class StepLearningRateWithLinearWarmup( tf.keras.optimizers.schedules.LearningRateSchedule): """Class to generate learning rate tensor.""" def __init__(self, total_steps, params): """Creates the step learning rate tensor with linear warmup.""" super(StepLearningRateWithLinearWarmup, self).__init__() self._total_steps = total_steps assert isinstance(params, (dict, params_dict.ParamsDict)) if isinstance(params, dict): params = params_dict.ParamsDict(params) self._params = params def __call__(self, global_step): warmup_lr = self._params.warmup_learning_rate warmup_steps = self._params.warmup_steps init_lr = self._params.init_learning_rate lr_levels = self._params.learning_rate_levels lr_steps = self._params.learning_rate_steps linear_warmup = ( warmup_lr + tf.cast(global_step, dtype=tf.float32) / warmup_steps * (init_lr - warmup_lr)) learning_rate = tf.where(global_step < warmup_steps, linear_warmup, init_lr) for next_learning_rate, start_step in zip(lr_levels, lr_steps): learning_rate = tf.where(global_step >= start_step, next_learning_rate, learning_rate) return learning_rate def get_config(self): return {'_params': self._params.as_dict()} class CosineLearningRateWithLinearWarmup( tf.keras.optimizers.schedules.LearningRateSchedule): """Class to generate learning rate tensor.""" def __init__(self, total_steps, params): """Creates the consine learning rate tensor with linear warmup.""" super(CosineLearningRateWithLinearWarmup, self).__init__() self._total_steps = total_steps assert isinstance(params, (dict, params_dict.ParamsDict)) if isinstance(params, dict): params = params_dict.ParamsDict(params) self._params = params def __call__(self, global_step): global_step = tf.cast(global_step, dtype=tf.float32) warmup_lr = self._params.warmup_learning_rate warmup_steps = self._params.warmup_steps init_lr = self._params.init_learning_rate total_steps = self._total_steps linear_warmup = ( warmup_lr + global_step / warmup_steps * (init_lr - warmup_lr)) cosine_learning_rate = ( init_lr * (tf.cos(np.pi * (global_step - warmup_steps) / (total_steps - warmup_steps)) + 1.0) / 2.0) learning_rate = tf.where(global_step < warmup_steps, linear_warmup, cosine_learning_rate) return learning_rate def get_config(self): return {'_params': self._params.as_dict()} def learning_rate_generator(total_steps, params): """The learning rate function generator.""" if params.type == 'step': return StepLearningRateWithLinearWarmup(total_steps, params) elif params.type == 'cosine': return CosineLearningRateWithLinearWarmup(total_steps, params) else: raise ValueError('Unsupported learning rate type: {}.'.format(params.type))
[ "tensorflow.cast", "tensorflow.cos", "tensorflow.where" ]
official/legacy/detection/modeling/learning_rates.py
[(48, 'tensorflow.where', 'tf.where', (['(global_step < warmup_steps)', 'linear_warmup', 'init_lr'], {}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.cast', 'tf.cast', (['global_step'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.where', 'tf.where', (['(global_step < warmup_steps)', 'linear_warmup', 'cosine_learning_rate'], {}), True, 'import tensorflow as tf\n'), (36, 'official.modeling.hyperparams.params_dict.ParamsDict', 'params_dict.ParamsDict', (['params'], {}), False, 'from official.modeling.hyperparams import params_dict\n'), (51, 'tensorflow.where', 'tf.where', (['(global_step >= start_step)', 'next_learning_rate', 'learning_rate'], {}), True, 'import tensorflow as tf\n'), (69, 'official.modeling.hyperparams.params_dict.ParamsDict', 'params_dict.ParamsDict', (['params'], {}), False, 'from official.modeling.hyperparams import params_dict\n'), (46, 'tensorflow.cast', 'tf.cast', (['global_step'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (81, 'tensorflow.cos', 'tf.cos', (['(np.pi * (global_step - warmup_steps) / (total_steps - warmup_steps))'], {}), True, 'import tensorflow as tf\n')]
ShuoZ9379/Integration_SIL_and_MBL
d7df6501a665d65eb791f7fd9b8e85fd660e6320
import scipy.optimize # import numpy as np import autograd.numpy as np # Thinly-wrapped numpy from autograd import grad import tensorflow as tf from baselines import logger import baselines.common.tf_util as U class EtaOmegaOptimizer(object): """ Finds eta and omega Lagrange multipliers. """ def __init__(self, beta, epsilon, init_eta, init_omega): self.init_eta_omega(beta, epsilon, init_eta, init_omega) def optimize(self, w_theta, Waa, Wsa, wa, varphis, Kt, prec, is_valid_eta_omega, old_entropy, eta=None): # wa = w_beta * \grad_beta \varphi_beta(s) * K^T * Prec if False: f_dual = self.opt_info['f_dual'] f_dual_grad = self.opt_info['f_dual_grad'] # Set BFGS eval function def eval_dual(input): param_eta = input[0] param_omega = input[1] val = f_dual(*([varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy])) return val.astype(np.float64) # Set BFGS gradient eval function def eval_dual_grad(input): param_eta = input[0] param_omega = input[1] grad = f_dual_grad(*([varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy])) return np.asarray(grad) if eta is not None: param_eta = eta else: param_eta = self.param_eta if self.beta == 0: beta = 0 else: beta = old_entropy - self.beta # eta_before = param_eta # omega_before = self.param_omega # dual_before = eval_dual([eta_before, omega_before]) # dual_grad_before = eval_dual_grad([eta_before, omega_before]) x0 = [param_eta, self.param_omega] # TEST # small = 0.000000001 # f1 = [self.param_eta - small, self.param_omega] # f2 = [self.param_eta + small, self.param_omega] # fd = (eval_dual(f1) - eval_dual(f2)) / (2 * small) # # duals = self.opt_info["f_duals"](*([varphis, Kt, prec, Waa, Wsa, wa] + [eta_before, omega_before, old_entropy])) # logger.log("Theano eta/omega: " + str(eta_before) + "/" + str(omega_before) + ": " + str(dual_before) + # ", " + str(duals) + ", grad: " + str(eval_dual_grad(x0)) + ", fd: " + str(fd)) # # END TEST # Create dual function def eval_dual(input): param_eta = input[0] param_omega = input[1] # ha(s): eta * (\varphi(s)^T * K^T * \Sigma^{-1} + W_{sa}) + wa(s)) ha = np.dot(varphis, param_eta * np.dot(Kt, prec) + Wsa) + wa # hss(s): eta * (\varphi(s)^T * K^T * \Sigma^{-1} * K * \varphi(s)) varphisKt = np.dot(varphis, Kt) hss = param_eta * np.sum(np.dot(varphisKt, prec) * varphisKt, axis=1) Haa = param_eta * prec + Waa # Haa = 0.5 * (Haa + np.transpose(Haa)) HaaInv = np.linalg.inv(Haa) # The two terms 'term1' and 'term2' which come from normalizers of the # 1. Original policy distribution # 2. The distribution after completing the square sigma = np.linalg.inv(prec) term1 = -0.5 * param_eta * np.linalg.slogdet(2 * np.pi * sigma)[1] if self.beta == 0: term2 = 0.5 * param_eta * np.linalg.slogdet(2 * np.pi * param_eta * HaaInv)[1] else: term2 = 0.5 * (param_eta + param_omega) * np.linalg.slogdet( 2 * np.pi * (param_eta + param_omega) * HaaInv)[1] dual = param_eta * self.epsilon - param_omega * beta + \ term1 + term2 + np.mean( 0.5 * (np.sum(np.dot(ha, HaaInv) * ha, axis=1) - hss)) return dual # Automatic gradient of the dual eval_dual_grad = grad(eval_dual) if True: def fx(x): eta, omega = x # eta: Lagrange variable of KL constraint, omega: of the entropy constraint error_return_val = 1e6, np.array([0., 0.]) if eta + omega < 0: return error_return_val if not is_valid_eta_omega(eta, omega, w_theta): return error_return_val return eval_dual(x), eval_dual_grad(x) else: def fx(x): eta, omega = x # eta: Lagrange variable of KL constraint, omega: of the entropy constraint error_return_val = 1e6, np.array([0., 0.]) if eta + omega < 0: return error_return_val if not is_valid_eta_omega(eta, omega, w_theta): return error_return_val return eval_dual(x), eval_dual_grad(x) # L-BFGS-B expects double floats # return np.float64(eval_dual(x)), np.float64(eval_dual_grad(x)) # L-BFGS-B expects double floats logger.log('optimizing dual') # Make sure valid initial covariance matrices while (not is_valid_eta_omega(x0[0], x0[1], w_theta)): x0[0] *= 2 logger.log("Eta increased: " + str(x0[0])) if eta is None: omega_lower = -100 if False: res = scipy.optimize.minimize(fx, x0, method='L-BFGS-B', jac=True, bounds=((1e-12, None), (omega_lower, None)), options={'ftol': 1e-12}) else: res = scipy.optimize.minimize(fx, x0, method='SLSQP', jac=True, bounds=((1e-12, None), (omega_lower, None)), options={'ftol': 1e-12}) # Make sure that eta > omega if res.x[1] < 0 and -res.x[1] > res.x[0]: res.x[1] = -res.x[0] + 1e-6 else: # Fixed eta: make sure that eta > omega omega_lower = np.max([-(eta - 1e-3) + 1e-6, -100]) if False: res = scipy.optimize.minimize(fx, x0, method='L-BFGS-B', jac=True, bounds=((eta - 1e-3, eta + 1e-3), (omega_lower, None)), options={'ftol': 1e-16}) else: res = scipy.optimize.minimize(fx, x0, method='SLSQP', jac=True, bounds=((eta - 1e-3, eta + 1e-3), (omega_lower, None)), options={'ftol': 1e-16}) if self.beta == 0: res.x[1] = 0 logger.log("dual optimized, eta: " + str(res.x[0]) + ", omega: " + str(res.x[1])) return res.x[0], res.x[1] # def f(x, grad): # if grad.size > 0: # grad[:] = eval_dual_grad(x) # # return np.float64(eval_dual(x)) # self.nlopt_opt.set_min_objective(f) # # Set parameter boundaries: eta, omega > 0 # self.nlopt_opt.set_lower_bounds([1e-12, 1e-12]) # # self.nlopt_opt.set_ftol_rel(1e-12) # self.nlopt_opt.set_xtol_rel(1e-12) # self.nlopt_opt.set_vector_storage(100) # try: # x = self.nlopt_opt.optimize([self.param_eta, self.param_omega]) # except RuntimeError: # entropy = np.mean(self.policy.distribution.entropy_log_probs(samples_data["agent_infos"])) # if entropy < 1e-9: # # ignore error since we already converged and are at the optimal policy # x = [eta_before, omega_before] # else: # print("Error during optimization of the dual...") # raise # logger.log('dual optimized') # # # get optimal values # return x[0], x[1] def init_eta_omega(self, beta, epsilon, init_eta, init_omega): # Here we define the symbolic function for the dual and the gradient self.beta = beta self.epsilon = epsilon # Init dual param values self.param_eta = init_eta self.param_omega = init_omega self.param_eta_non_lin = init_eta self.param_omega_non_lin = init_omega param_eta = tf.placeholder(dtype=tf.float32, shape=[], name="param_eta") param_omega = tf.placeholder(dtype=tf.float32, shape=[], name="param_omega") old_entropy = tf.placeholder(dtype=tf.float32, shape=[], name="old_entropy") varphis = tf.placeholder(dtype=tf.float32, shape=[None, None], name="varphis") Kt = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Kt") prec = tf.placeholder(dtype=tf.float32, shape=[None, None], name="prec") Waa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Waa") Wsa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Wsa") wa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="wa") # varphis = ext.new_tensor( # 'varphis', # ndim=2, # dtype=theano.config.floatX # ) # Kt = ext.new_tensor( # 'Kt', # ndim=2, # dtype=theano.config.floatX # ) # prec = ext.new_tensor( # 'prec', # ndim=2, # dtype=theano.config.floatX # ) # Waa = ext.new_tensor( # 'Waa', # ndim=2, # dtype=theano.config.floatX # ) # Wsa = ext.new_tensor( # 'Wsa', # ndim=2, # dtype=theano.config.floatX # ) # wa = ext.new_tensor( # 'wa', # ndim=2, # dtype=theano.config.floatX # ) if self.beta == 0: beta = 0 else: beta = old_entropy - self.beta # beta = self.printt('beta shape: ', beta) # log_action_prob = self.printn('log_action_prob shape: ', log_action_prob) # action_prob = self.printn('action_prob shape: ', action_prob) # q_values = self.printn('q_values shape: ', q_values) # beta = self.printn('beta shape: ', beta) # ha(s): eta * (\varphi(s)^T * K^T * \Sigma^{-1} + W_{sa}) + wa(s)) ha = tf.matmul(varphis, param_eta * tf.matmul(Kt, prec) + Wsa) + wa # hss(s): eta * (\varphi(s)^T * K^T * \Sigma^{-1} * K * \varphi(s)) varphisKt = tf.matmul(varphis, Kt) hss = param_eta * tf.reduce_sum(tf.matmul(varphisKt, prec) * varphisKt, axis=1) Haa = param_eta * prec + Waa # Haa = 0.5 * (Haa + TT.transpose(Haa)) HaaInv = tf.matrix_inverse(Haa) # The two terms 'term1' and 'term2' which come from normalizers of the # 1. Original policy distribution # 2. The distribution after completing the square sigma = tf.matrix_inverse(prec) term1 = -0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * sigma)) if self.beta == 0: term2 = 0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * param_eta * HaaInv)) else: term2 = 0.5 * (param_eta + param_omega) * tf.log(tf.matrix_determinant(2 * np.pi * (param_eta + param_omega) * HaaInv)) dual = param_eta * self.epsilon - param_omega * beta + \ term1 + term2 + tf.reduce_mean( 0.5 * (tf.reduce_sum(tf.matmul(ha, HaaInv) * ha, axis=1) - hss)) # Symbolic dual gradient dual_grad = tf.gradients(xs=[param_eta, param_omega], ys=dual) # Eval functions. f_dual = U.function( inputs=[varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy], outputs=dual, # mode='DebugMode' # TEST ) f_dual_grad = U.function( inputs=[varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy], outputs=dual_grad, # mode='DebugMode' # TEST ) # # # TEST # d0 = param_eta * self.epsilon - param_omega * beta # d1 = term1 # d2 = term2 # d3 = TT.mean(0.5 * (TT.sum(TT.dot(ha, HaaInv) * ha, axis=1))) # d4 = TT.mean(hss) # f_duals = ext.compile_function( # inputs=[varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy], # outputs=[d0, d1, d2, d3, d4] # ) # # END TEST self.opt_info = dict( f_dual=f_dual, f_dual_grad=f_dual_grad, # f_duals=f_duals, # TEST )
[ "tensorflow.matmul", "tensorflow.matrix_inverse", "tensorflow.gradients", "tensorflow.matrix_determinant", "tensorflow.placeholder" ]
baselines/n_copos/eta_omega_dual.py
[(125, 'baselines.logger.log', 'logger.log', (['"""optimizing dual"""'], {}), False, 'from baselines import logger\n'), (204, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[]', 'name': '"""param_eta"""'}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[]', 'name': '"""param_omega"""'}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[]', 'name': '"""old_entropy"""'}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""varphis"""'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""Kt"""'}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""prec"""'}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""Waa"""'}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""Wsa"""'}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[None, None]', 'name': '"""wa"""'}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.matmul', 'tf.matmul', (['varphis', 'Kt'], {}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.matrix_inverse', 'tf.matrix_inverse', (['Haa'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.matrix_inverse', 'tf.matrix_inverse', (['prec'], {}), True, 'import tensorflow as tf\n'), (283, 'tensorflow.gradients', 'tf.gradients', ([], {'xs': '[param_eta, param_omega]', 'ys': 'dual'}), True, 'import tensorflow as tf\n'), (286, 'baselines.common.tf_util.function', 'U.function', ([], {'inputs': '([varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy])', 'outputs': 'dual'}), True, 'import baselines.common.tf_util as U\n'), (292, 'baselines.common.tf_util.function', 'U.function', ([], {'inputs': '([varphis, Kt, prec, Waa, Wsa, wa] + [param_eta, param_omega, old_entropy])', 'outputs': 'dual_grad'}), True, 'import baselines.common.tf_util as U\n'), (78, 'autograd.numpy.dot', 'np.dot', (['varphis', 'Kt'], {}), True, 'import autograd.numpy as np\n'), (83, 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['Haa'], {}), True, 'import autograd.numpy as np\n'), (88, 'autograd.numpy.linalg.inv', 'np.linalg.inv', (['prec'], {}), True, 'import autograd.numpy as np\n'), (146, 'autograd.numpy.max', 'np.max', (['[-(eta - 0.001) + 1e-06, -100]'], {}), True, 'import autograd.numpy as np\n'), (39, 'autograd.numpy.asarray', 'np.asarray', (['grad'], {}), True, 'import autograd.numpy as np\n'), (272, 'tensorflow.matrix_determinant', 'tf.matrix_determinant', (['(2 * np.pi * sigma)'], {}), True, 'import tensorflow as tf\n'), (89, 'autograd.numpy.linalg.slogdet', 'np.linalg.slogdet', (['(2 * np.pi * sigma)'], {}), True, 'import autograd.numpy as np\n'), (108, 'autograd.numpy.array', 'np.array', (['[0.0, 0.0]'], {}), True, 'import autograd.numpy as np\n'), (117, 'autograd.numpy.array', 'np.array', (['[0.0, 0.0]'], {}), True, 'import autograd.numpy as np\n'), (262, 'tensorflow.matmul', 'tf.matmul', (['varphisKt', 'prec'], {}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.matrix_determinant', 'tf.matrix_determinant', (['(2 * np.pi * param_eta * HaaInv)'], {}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.matrix_determinant', 'tf.matrix_determinant', (['(2 * np.pi * (param_eta + param_omega) * HaaInv)'], {}), True, 'import tensorflow as tf\n'), (79, 'autograd.numpy.dot', 'np.dot', (['varphisKt', 'prec'], {}), True, 'import autograd.numpy as np\n'), (91, 'autograd.numpy.linalg.slogdet', 'np.linalg.slogdet', (['(2 * np.pi * param_eta * HaaInv)'], {}), True, 'import autograd.numpy as np\n'), (93, 'autograd.numpy.linalg.slogdet', 'np.linalg.slogdet', (['(2 * np.pi * (param_eta + param_omega) * HaaInv)'], {}), True, 'import autograd.numpy as np\n'), (258, 'tensorflow.matmul', 'tf.matmul', (['Kt', 'prec'], {}), True, 'import tensorflow as tf\n'), (75, 'autograd.numpy.dot', 'np.dot', (['Kt', 'prec'], {}), True, 'import autograd.numpy as np\n'), (280, 'tensorflow.matmul', 'tf.matmul', (['ha', 'HaaInv'], {}), True, 'import tensorflow as tf\n'), (98, 'autograd.numpy.dot', 'np.dot', (['ha', 'HaaInv'], {}), True, 'import autograd.numpy as np\n')]
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
""" Copyright (c) 2021, NVIDIA CORPORATION. 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 argparse import sys, os sys.path.append(os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)), "../../../"))) # os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import sparse_operation_kit as sok import tensorflow as tf import utils from sparse_models import SOKDemo, TFDemo from test_dense_emb_demo import check_saved_embedding_variables import strategy_wrapper import numpy as np def get_sok_results(args, init_tensors, *random_samples): if args.distributed_tool == "onedevice": strategy = strategy_wrapper.OneDeviceStrategy() elif args.distributed_tool == "horovod": import horovod.tensorflow as hvd hvd.init() strategy = strategy_wrapper.HorovodStrategy() else: raise ValueError(f"{args.distributed_tool} is not supported.") with strategy.scope(): sok_init_op = sok.Init(global_batch_size=args.global_batch_size) sok_sparse_demo = SOKDemo(max_vocabulary_size_per_gpu=args.max_vocabulary_size_per_gpu, embedding_vec_size=args.embedding_vec_size, combiner=args.combiner, slot_num=args.slot_num, max_nnz=args.max_nnz, use_hashtable=args.use_hashtable, num_of_dense_layers=0) emb_opt = utils.get_embedding_optimizer(args.optimizer)(learning_rate=0.1) dense_opt = utils.get_dense_optimizer(args.optimizer)(learning_rate=0.1) sok_saver = sok.Saver() restore_op = list() for i, embedding_layer in enumerate(sok_sparse_demo.embedding_layers): control_inputs = [restore_op[-1]] if restore_op else None with tf.control_dependencies(control_inputs): if args.restore_params: filepath = r"./embedding_variables" op = sok_saver.restore_from_file(embedding_layer.embedding_variable, filepath) else: op = sok_saver.load_embedding_values(embedding_layer.embedding_variable, init_tensors[i]) restore_op.append(op) loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction="none") def _replica_loss(labels, logits): loss = loss_fn(labels, logits) return tf.nn.compute_average_loss(loss, global_batch_size=args.global_batch_size) def _train_step(inputs, labels, training): def _step_fn(inputs, labels): logit, embedding_vector = sok_sparse_demo(inputs, training=training) loss = _replica_loss(labels, logit) emb_var, other_var = sok.split_embedding_variable_from_others(sok_sparse_demo.trainable_variables) grads = tf.gradients(loss, emb_var + other_var, colocate_gradients_with_ops=True, unconnected_gradients=tf.UnconnectedGradients.NONE) emb_grads, other_grads = grads[:len(emb_var)], grads[len(emb_var):] if "plugin" in args.optimizer: emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var)) else: with sok.OptimizerScope(emb_var): emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var)) with tf.control_dependencies([*emb_grads]): # in case NCCL runs concurrently via SOK and horovod other_grads = strategy.reduce("sum", other_grads) other_train_op = dense_opt.apply_gradients(zip(other_grads, other_var)) with tf.control_dependencies([emb_train_op, other_train_op]): total_loss = strategy.reduce("sum", loss) total_loss = tf.identity(total_loss) return total_loss, embedding_vector return strategy.run(_step_fn, inputs, labels) replica_batch_size = args.global_batch_size // args.gpu_num dataset = utils.tf_dataset(*random_samples, batchsize=replica_batch_size, to_sparse_tensor=True, repeat=1) train_iterator = dataset.make_initializable_iterator() iterator_init = train_iterator.initializer inputs, labels = train_iterator.get_next() graph_results = _train_step(inputs, labels, training=True) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) if "plugin" in args.optimizer: init_op = tf.group(init_op, emb_opt.initializer) save_op = list() for i, embedding_layer in enumerate(sok_sparse_demo.embedding_layers): control_inputs = [save_op[-1]] if save_op else None with tf.control_dependencies(control_inputs): if args.save_params: filepath = r"./embedding_variables/" utils.try_make_dirs(filepath) op = sok_saver.dump_to_file(embedding_layer.embedding_variable, filepath) else: op = tf.constant(1.0) save_op.append(op) sok_results = list() with tf.Session() as sess: sess.run(sok_init_op) sess.run([init_op, iterator_init]) sess.run(restore_op) sess.graph.finalize() for step in range(args.iter_num): loss_v, emb_vector_v = sess.run([*graph_results]) print("*" * 80) print(f"Step: {step}, loss: {loss_v}, embedding_vector:\n{emb_vector_v}") sok_results.append(emb_vector_v) sess.run(save_op) name = list() for embedding_layer in sok_sparse_demo.embedding_layers: name.append(embedding_layer.embedding_variable.m_var_name) return sok_results, name def get_tf_results(args, init_tensors, *random_samples): graph = tf.Graph() with graph.as_default(): tf_sparse_demo = TFDemo(vocabulary_size=args.max_vocabulary_size_per_gpu * args.gpu_num, embedding_vec_size=args.embedding_vec_size, combiner=args.combiner, slot_num=args.slot_num, max_nnz=args.max_nnz, use_hashtable=args.use_hashtable, num_of_dense_layers=0) optimizer = utils.get_dense_optimizer(args.optimizer)(learning_rate=0.1) loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True) def _train_step(inputs, labels, training): logit, embedding_vector = tf_sparse_demo(inputs, training=training) loss = loss_fn(labels, logit) grads = tf.gradients(loss, tf_sparse_demo.trainable_variables, colocate_gradients_with_ops=True, unconnected_gradients=tf.UnconnectedGradients.NONE) train_op = optimizer.apply_gradients(zip(grads, tf_sparse_demo.trainable_variables)) with tf.control_dependencies([train_op]): loss = tf.identity(loss) return loss, embedding_vector dataset = utils.tf_dataset(*random_samples, batchsize=args.global_batch_size, to_sparse_tensor=True, repeat=1) train_iterator = dataset.make_initializable_iterator() iterator_init = train_iterator.initializer inputs, labels = train_iterator.get_next() graph_results = _train_step(inputs, labels, training=True) init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) restore_op = list() for i, embedding_weight in enumerate(tf_sparse_demo.embedding_weights): restore_op.append(embedding_weight.assign(tf.concat(init_tensors[i], axis=0))) emb_values = list() for embedding_weight in tf_sparse_demo.embedding_weights: if args.save_params: filepath = r"./embedding_variables/" utils.try_make_dirs(filepath) emb_values.append(embedding_weight.read_value()) else: emb_values = tf.constant(1.0) tf_results = list() with tf.Session(graph=graph) as sess: sess.run([init_op, iterator_init]) sess.run(restore_op) sess.graph.finalize() for step in range(args.iter_num): loss_v, emb_vector_v = sess.run([*graph_results]) print("*" * 80) print(f"step: {step}, loss: {loss_v}, embedding_vector:\n{emb_vector_v}") tf_results.append(emb_vector_v) emb_values_v = sess.run(emb_values) if args.save_params: for i, value in enumerate(emb_values_v): utils.save_to_file(os.path.join(filepath, r"tf_variable_" + str(i) + r".file"), value) name = list() for embedding_weight in tf_sparse_demo.embedding_weights: name.append(embedding_weight.name) return tf_results, name def compare_sparse_emb_sok_with_tf(args): if args.global_batch_size % args.gpu_num != 0: raise ValueError(f"global_batch_size: {args.global_batch_size} is not divisible " f"by gpu_num: {args.gpu_num}") if args.use_hashtable: vocabulary_size = args.max_vocabulary_size_per_gpu * args.gpu_num else: vocabulary_size = args.max_vocabulary_size_per_gpu if args.generate_new_datas: replica_batch_size = args.global_batch_size // args.gpu_num random_samples = utils.generate_random_samples(num_of_samples=replica_batch_size * args.iter_num, vocabulary_size=vocabulary_size, slot_num=sum(args.slot_num), max_nnz=args.max_nnz, use_sparse_mask=True) utils.save_to_file(r"./random_samples_" + str(args.rank_idx) + r".file", *random_samples) else: random_samples = utils.restore_from_file(r"./random_samples_" + str(args.rank_idx) + r".file") if args.restore_params: filepath = r"./embedding_variables" # because we already checked the variable consistency when saving # so that we can directly use TF Variable file to initialize # TF's Variable and SOK's Variable init_tensors = list() for i in range(len(args.slot_num)): tf_values_filename = os.path.join(filepath, r"tf_variable_" + str(i) + r".file") init_tensors.append(utils.restore_from_file(tf_values_filename)) else: init_tensors = list() for i in range(len(args.slot_num)): init_tensors.append(utils.get_ones_tensor(max_vocab_size_per_gpu=args.max_vocabulary_size_per_gpu, embedding_vec_size=args.embedding_vec_size[i], num=args.gpu_num)) sok_results, variable_names = get_sok_results(args, init_tensors, *random_samples) utils.save_to_file(r"./sok_embedding_vectors_" + str(args.rank_idx) + r".file", *sok_results) if args.rank_idx != 0: return # aggregate dataset from different worker dataset_filenames = [r"./random_samples_" + str(rank_idx) + r".file" for rank_idx in range(args.rank_size)] random_samples_total = [list() for _ in range(args.iter_num)] random_labels_total = [list() for _ in range(args.iter_num)] local_batch_size = args.global_batch_size // args.gpu_num for rank_idx in range(args.rank_size): samples, labels = utils.restore_from_file(dataset_filenames[rank_idx]) for i in range(args.iter_num): random_samples_total[i].extend(samples[i * local_batch_size : (i + 1) * local_batch_size]) random_labels_total[i].extend(labels[i * local_batch_size : (i + 1) * local_batch_size]) random_samples_total = np.concatenate(random_samples_total, axis=0) random_labels_total = np.concatenate(random_labels_total, axis=0) tf_results, _ = get_tf_results(args, init_tensors, random_samples_total, random_labels_total) # aggregate sok forward results from different worker sok_results_filenames = [r"./sok_embedding_vectors_" + str(rank_idx) + r".file" for rank_idx in range(args.rank_size)] sok_results_total = list() for filename in sok_results_filenames: sok_results = utils.restore_from_file(filename) sok_results_total.append(sok_results) if len(sok_results_total[0]) != len(tf_results): raise ValueError("The length of sok results is not equal to that of tensorflow.") if len(sok_results) != args.iter_num: raise ValueError("The length of embedding vectors: %d is not equal to iteration number: %d." %(len(sok_results), args.iter_num)) rtol, atol = 1e-3, 1e-3 if args.restore_params: rtol, atol = rtol * 10, atol * 10 if args.distributed_tool == "horovod": rtol, atol = rtol * 10, atol * 10 for i in range(args.iter_num): sok_vector = np.concatenate([sok_results_total[rank_idx][i] for rank_idx in range(args.rank_size)], axis=0) allclose = np.allclose(sok_vector, tf_results[i], rtol=rtol, atol=atol) if not allclose: raise ValueError(f"\n{sok_vector} \nis not near to \n{tf_results[i]} \nat rtol={rtol}, atol={atol}") print(f"\n[INFO]: For {len(args.slot_num)} Sparse Embedding layer, using {args.gpu_num} GPUs + {args.optimizer} optimizer, " f"using hashtable? {args.use_hashtable}, combiner = {args.combiner}, the embedding vectors" f" obtained from sok and tf are consistent for {args.iter_num} iterations.") if args.save_params: check_saved_embedding_variables(args, variable_names, use_hashtable=args.use_hashtable, gpu_num=args.gpu_num) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--gpu_num", type=int, required=False, default=1) parser.add_argument("--distributed_tool", type=str, required=False, choices=["horovod", "onedevice"], default="onedevice") parser.add_argument("--iter_num", type=int, required=False, default=50) parser.add_argument("--max_vocabulary_size_per_gpu", type=int, required=False, default=1024) parser.add_argument("--combiner", type=str, required=False, default="sum", choices=["sum", "mean"]) parser.add_argument("--slot_num", type=int, nargs="+", help="the number of feature fileds", required=False, default=1) parser.add_argument("--max_nnz", type=int, help="the maximum of valid inputs", required=False, default=1) parser.add_argument("--embedding_vec_size", type=int, nargs="+", required=False, default=1) parser.add_argument("--global_batch_size", type=int, required=False, default=16) parser.add_argument("--optimizer", type=str, required=False, default="adam", choices=["plugin_adam", "adam", "sgd", "compat_adam"]) parser.add_argument("--generate_new_datas", type=int, choices=[0, 1], required=False, default=1) parser.add_argument("--save_params", type=int, choices=[0, 1], required=False, default=1) parser.add_argument("--restore_params", type=int, choices=[0, 1], required=False, default=0) parser.add_argument("--use_hashtable", type=int, choices=[0, 1], required=False, default=1) args = parser.parse_args() args.generate_new_datas = True if args.generate_new_datas == 1 else False args.save_params = True if args.save_params == 1 else False args.restore_params = True if args.restore_params == 1 else False args.use_hashtable = True if args.use_hashtable == 1 else False if (args.distributed_tool == "onedevice" and args.gpu_num != 1): raise ValueError(f"When 'onedevice' is used as the distributed_tool, " f"gpu_num must be 1, which is {args.gpu_num}") if args.distributed_tool == "onedevice": available_gpus = ",".join(map(str, range(args.gpu_num))) rank_size = args.gpu_num rank_idx = 0 else: # gpu_num will be ignored. rank_size = os.getenv("OMPI_COMM_WORLD_SIZE") if rank_size is None: raise ValueError(f"When distributed_tool is set to {args.distributed_tool}, " "mpiexec / mpirun must be used to launch this program.") rank_size = int(rank_size) rank_idx = int(os.getenv("OMPI_COMM_WORLD_RANK")) available_gpus = str(rank_idx) os.environ["CUDA_VISIBLE_DEVICES"] = available_gpus args.rank_size = rank_size args.rank_idx = rank_idx args.gpu_num = rank_size compare_sparse_emb_sok_with_tf(args)
[ "tensorflow.nn.compute_average_loss", "tensorflow.Graph", "tensorflow.local_variables_initializer", "numpy.allclose", "tensorflow.control_dependencies", "tensorflow.constant", "tensorflow.concat", "tensorflow.gradients", "tensorflow.keras.losses.BinaryCrossentropy", "tensorflow.identity", "numpy.concatenate", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.group" ]
sparse_operation_kit/unit_test/test_scripts/tf1/test_sparse_emb_demo.py
[(55, 'sparse_operation_kit.Saver', 'sok.Saver', ([], {}), True, 'import sparse_operation_kit as sok\n'), (67, 'tensorflow.keras.losses.BinaryCrossentropy', 'tf.keras.losses.BinaryCrossentropy', ([], {'from_logits': '(True)', 'reduction': '"""none"""'}), True, 'import tensorflow as tf\n'), (97, 'utils.tf_dataset', 'utils.tf_dataset', (['*random_samples'], {'batchsize': 'replica_batch_size', 'to_sparse_tensor': '(True)', 'repeat': '(1)'}), False, 'import utils\n'), (144, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (269, 'numpy.concatenate', 'np.concatenate', (['random_samples_total'], {'axis': '(0)'}), True, 'import numpy as np\n'), (270, 'numpy.concatenate', 'np.concatenate', (['random_labels_total'], {'axis': '(0)'}), True, 'import numpy as np\n'), (309, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (33, 'strategy_wrapper.OneDeviceStrategy', 'strategy_wrapper.OneDeviceStrategy', ([], {}), False, 'import strategy_wrapper\n'), (42, 'sparse_operation_kit.Init', 'sok.Init', ([], {'global_batch_size': 'args.global_batch_size'}), True, 'import sparse_operation_kit as sok\n'), (44, 'sparse_models.SOKDemo', 'SOKDemo', ([], {'max_vocabulary_size_per_gpu': 'args.max_vocabulary_size_per_gpu', 'embedding_vec_size': 'args.embedding_vec_size', 'combiner': 'args.combiner', 'slot_num': 'args.slot_num', 'max_nnz': 'args.max_nnz', 'use_hashtable': 'args.use_hashtable', 'num_of_dense_layers': '(0)'}), False, 'from sparse_models import SOKDemo, TFDemo\n'), (70, 'tensorflow.nn.compute_average_loss', 'tf.nn.compute_average_loss', (['loss'], {'global_batch_size': 'args.global_batch_size'}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.group', 'tf.group', (['init_op', 'emb_opt.initializer'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (146, 'sparse_models.TFDemo', 'TFDemo', ([], {'vocabulary_size': '(args.max_vocabulary_size_per_gpu * args.gpu_num)', 'embedding_vec_size': 'args.embedding_vec_size', 'combiner': 'args.combiner', 'slot_num': 'args.slot_num', 'max_nnz': 'args.max_nnz', 'use_hashtable': 'args.use_hashtable', 'num_of_dense_layers': '(0)'}), False, 'from sparse_models import SOKDemo, TFDemo\n'), (156, 'tensorflow.keras.losses.BinaryCrossentropy', 'tf.keras.losses.BinaryCrossentropy', ([], {'from_logits': '(True)'}), True, 'import tensorflow as tf\n'), (169, 'utils.tf_dataset', 'utils.tf_dataset', (['*random_samples'], {'batchsize': 'args.global_batch_size', 'to_sparse_tensor': '(True)', 'repeat': '(1)'}), False, 'import utils\n'), (193, 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), True, 'import tensorflow as tf\n'), (265, 'utils.restore_from_file', 'utils.restore_from_file', (['dataset_filenames[rank_idx]'], {}), False, 'import utils\n'), (279, 'utils.restore_from_file', 'utils.restore_from_file', (['filename'], {}), False, 'import utils\n'), (296, 'numpy.allclose', 'np.allclose', (['sok_vector', 'tf_results[i]'], {'rtol': 'rtol', 'atol': 'atol'}), True, 'import numpy as np\n'), (305, 'test_dense_emb_demo.check_saved_embedding_variables', 'check_saved_embedding_variables', (['args', 'variable_names'], {'use_hashtable': 'args.use_hashtable', 'gpu_num': 'args.gpu_num'}), False, 'from test_dense_emb_demo import check_saved_embedding_variables\n'), (357, 'os.getenv', 'os.getenv', (['"""OMPI_COMM_WORLD_SIZE"""'], {}), False, 'import sys, os\n'), (36, 'horovod.tensorflow.init', 'hvd.init', ([], {}), True, 'import horovod.tensorflow as hvd\n'), (37, 'strategy_wrapper.HorovodStrategy', 'strategy_wrapper.HorovodStrategy', ([], {}), False, 'import strategy_wrapper\n'), (52, 'utils.get_embedding_optimizer', 'utils.get_embedding_optimizer', (['args.optimizer'], {}), False, 'import utils\n'), (53, 'utils.get_dense_optimizer', 'utils.get_dense_optimizer', (['args.optimizer'], {}), False, 'import utils\n'), (59, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['control_inputs'], {}), True, 'import tensorflow as tf\n'), (76, 'sparse_operation_kit.split_embedding_variable_from_others', 'sok.split_embedding_variable_from_others', (['sok_sparse_demo.trainable_variables'], {}), True, 'import sparse_operation_kit as sok\n'), (77, 'tensorflow.gradients', 'tf.gradients', (['loss', '(emb_var + other_var)'], {'colocate_gradients_with_ops': '(True)', 'unconnected_gradients': 'tf.UnconnectedGradients.NONE'}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['control_inputs'], {}), True, 'import tensorflow as tf\n'), (154, 'utils.get_dense_optimizer', 'utils.get_dense_optimizer', (['args.optimizer'], {}), False, 'import utils\n'), (160, 'tensorflow.gradients', 'tf.gradients', (['loss', 'tf_sparse_demo.trainable_variables'], {'colocate_gradients_with_ops': '(True)', 'unconnected_gradients': 'tf.UnconnectedGradients.NONE'}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (362, 'os.getenv', 'os.getenv', (['"""OMPI_COMM_WORLD_RANK"""'], {}), False, 'import sys, os\n'), (20, 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), False, 'import sys, os\n'), (85, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[*emb_grads]'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[emb_train_op, other_train_op]'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.identity', 'tf.identity', (['total_loss'], {}), True, 'import tensorflow as tf\n'), (115, 'utils.try_make_dirs', 'utils.try_make_dirs', (['filepath'], {}), False, 'import utils\n'), (118, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[train_op]'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.identity', 'tf.identity', (['loss'], {}), True, 'import tensorflow as tf\n'), (187, 'utils.try_make_dirs', 'utils.try_make_dirs', (['filepath'], {}), False, 'import utils\n'), (190, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (245, 'utils.restore_from_file', 'utils.restore_from_file', (['tf_values_filename'], {}), False, 'import utils\n'), (249, 'utils.get_ones_tensor', 'utils.get_ones_tensor', ([], {'max_vocab_size_per_gpu': 'args.max_vocabulary_size_per_gpu', 'embedding_vec_size': 'args.embedding_vec_size[i]', 'num': 'args.gpu_num'}), False, 'import utils\n'), (83, 'sparse_operation_kit.OptimizerScope', 'sok.OptimizerScope', (['emb_var'], {}), True, 'import sparse_operation_kit as sok\n'), (181, 'tensorflow.concat', 'tf.concat', (['init_tensors[i]'], {'axis': '(0)'}), True, 'import tensorflow as tf\n')]
huangwenwenlili/imgclsmob
1505fd61acbed429773f5c7ce286c858fc2278b8
import numpy as np import tensorflow as tf from .tensorflowcv.model_provider import get_model def save_model_params(sess, file_path): # assert file_path.endswith('.npz') param_dict = {v.name: v.eval(sess) for v in tf.global_variables()} np.savez_compressed(file_path, **param_dict) def load_model_params(net, param_dict, sess, ignore_missing=False): for param_name, param_data in param_dict: with tf.variable_scope(param_name, reuse=True): try: var = tf.get_variable(param_name) sess.run(var.assign(param_data)) except ValueError: if not ignore_missing: raise def prepare_model(model_name, use_pretrained, pretrained_model_file_path): kwargs = {'pretrained': use_pretrained} net = get_model(model_name, **kwargs) input_image_size = net.in_size[0] if hasattr(net, 'in_size') else 224 x = tf.placeholder( dtype=tf.float32, shape=(None, 3, input_image_size, input_image_size), name='xx') y_net = net(x) if use_pretrained or pretrained_model_file_path: from .tensorflowcv.model_provider import init_variables_from_state_dict with tf.Session() as sess: from .tensorflowcv.model_provider import load_state_dict if pretrained_model_file_path: init_variables_from_state_dict( sess=sess, state_dict=load_state_dict(file_path=pretrained_model_file_path)) else: init_variables_from_state_dict(sess=sess, state_dict=net.state_dict) return y_net
[ "tensorflow.get_variable", "tensorflow.global_variables", "tensorflow.placeholder", "numpy.savez_compressed", "tensorflow.Session", "tensorflow.variable_scope" ]
tensorflow_/utils.py
[(11, 'numpy.savez_compressed', 'np.savez_compressed', (['file_path'], {}), True, 'import numpy as np\n'), (36, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, 3, input_image_size, input_image_size)', 'name': '"""xx"""'}), True, 'import tensorflow as tf\n'), (10, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.variable_scope', 'tf.variable_scope', (['param_name'], {'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (21, 'tensorflow.get_variable', 'tf.get_variable', (['param_name'], {}), True, 'import tensorflow as tf\n')]
MoonBlvd/TFSegmentation
baa874237289227c99163fe119448579904a231f
import tensorflow as tf import numpy as np from layers.utils import variable_summaries, variable_with_weight_decay from utils.misc import timeit from utils.misc import _debug # import torchfile import pickle import pdb class RESNET18: """ RESNET 18 Encoder class """ def __init__(self, x_input, num_classes, pretrained_path, train_flag, bias=-1, weight_decay=5e-4, test_classification=False): """ :param x_input: Input Images to the RESNET Encoder :param num_classes: :param pretrained_path: :param train_flag: :param weight_decay: """ # Load pretrained path if pretrained_path.split('.')[-1]=='npy': self.pretrained_weights = np.load(pretrained_path) elif pretrained_path.split('.')[-1]=='pkl': with open(pretrained_path, 'rb') as ff: self.pretrained_weights = pickle.load(ff, encoding='latin1') print('pretrained weights dictionary loaded from disk') # init parameters and input self.x_input = x_input self.num_classes = num_classes self.train_flag = train_flag self.wd = weight_decay self.bias = bias self.use_bias = True if self.bias == -1: self.use_bias = False self.test_classification = test_classification # All layers self.resnet_mean = None self.resnet_std = None self.x_preprocessed = None self.conv1 = None self.conv2 = None self.conv3 = None self.conv4 = None self.conv5 = None self.score = None # These feed layers are for the decoder self.feed1 = None self.feed2 = None self.encoder_1 = None self.encoder_2 = None self.encoder_3 = None self.encoder_4 = None def build(self): """ Build the RESNET model using loaded weights """ print("Building the RESNET..") # Convert RGB to BGR with tf.name_scope('Pre_Processing'): self.x_preprocessed = self.x_input * (1.0 / 255.0) # self.x_preprocessed= self.x_input stat= torchfile.load('stat.t7') self.resnet_mean= stat.transpose(1,2,0) # self.resnet_mean = tf.constant([0.2869, 0.3251, 0.2839], dtype=tf.float32) self.x_preprocessed = (self.x_preprocessed - self.resnet_mean) #/ self.resnet_std # red, green, blue = tf.split(self.x_preprocessed, num_or_size_splits=3, axis=3) # self.x_preprocessed = tf.concat([blue,green,red], 3) # These variables to keep track of what i do # filters = [64, 64, 128, 256, 512] # kernels = [7, 3, 3, 3, 3] # strides = [2, 0, 2, 2, 2] tf.add_to_collection('debug_layers', self.x_preprocessed) with tf.variable_scope('conv1_x'): print('Building unit: conv1') self.conv1 = self._conv('conv1', self.x_preprocessed, padding= [[0,0],[3,3],[3,3],[0,0]], num_filters=64, kernel_size=(7, 7), stride=(2, 2), l2_strength=self.wd, bias=self.bias) self.conv1 = self._bn('bn1', self.conv1) self.conv1 = self._relu('relu1', self.conv1) _debug(self.conv1) self.conv1= tf.pad(self.conv1, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT") self.conv1 = tf.nn.max_pool(self.conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='max_pool1') _debug(self.conv1) print('conv1-shape: ' + str(self.conv1.shape.as_list())) with tf.variable_scope('conv2_x'): self.conv2 = self._residual_block('conv2_1', self.conv1, 64) _debug(self.conv2) self.conv2 = self._residual_block('conv2_2', self.conv2, 64) _debug(self.conv2) with tf.variable_scope('conv3_x'): self.conv3 = self._residual_block('conv3_1', self.conv2, 128, pool_first=True, strides=2) _debug(self.conv3) self.conv3 = self._residual_block('conv3_2', self.conv3, 128) _debug(self.conv3) with tf.variable_scope('conv4_x'): self.conv4 = self._residual_block('conv4_1', self.conv3, 256, pool_first=True, strides=2) _debug(self.conv4) self.conv4 = self._residual_block('conv4_2', self.conv4, 256) _debug(self.conv4) with tf.variable_scope('conv5_x'): self.conv5 = self._residual_block('conv5_1', self.conv4, 512, pool_first=True, strides=2) _debug(self.conv5) self.conv5 = self._residual_block('conv5_2', self.conv5, 512) _debug(self.conv5) if self.test_classification: with tf.variable_scope('logits'): print('Building unit: logits') self.score = tf.reduce_mean(self.conv5, axis=[1, 2]) self.score = self._fc('logits_dense', self.score, output_dim=self.num_classes, l2_strength=self.wd) print('logits-shape: ' + str(self.score.shape.as_list())) self.feed1 = self.conv4 self.feed2 = self.conv3 self.encoder_1 = self.conv2 self.encoder_2 = self.conv3 self.encoder_3 = self.conv4 self.encoder_4 = self.conv5 print("\nEncoder RESNET is built successfully\n\n") @timeit def load_pretrained_weights(self, sess): print("Loading pretrained weights of resnet18") all_vars = tf.trainable_variables() all_vars += tf.get_collection('mu_sigma_bn') for v in all_vars: if v.op.name in self.pretrained_weights.keys(): assign_op = v.assign(self.pretrained_weights[v.op.name]) sess.run(assign_op) print(v.op.name + " - loaded successfully") print("All pretrained weights of resnet18 is loaded") def _residual_block(self, name, x, filters, pool_first=False, strides=1, dilation=1): print('Building residual unit: %s' % name) with tf.variable_scope(name): # get input channels in_channel = x.shape.as_list()[-1] # Shortcut connection shortcut = tf.identity(x) if pool_first: if in_channel == filters: if strides == 1: shortcut = tf.identity(x) else: shortcut= tf.pad(x, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT") shortcut = tf.nn.max_pool(shortcut, [1, strides, strides, 1], [1, strides, strides, 1], 'VALID') else: shortcut = self._conv('shortcut_conv', x, padding='VALID', num_filters=filters, kernel_size=(1, 1), stride=(strides, strides), bias=self.bias) else: if dilation != 1: shortcut = self._conv('shortcut_conv', x, padding='VALID', num_filters=filters, kernel_size=(1, 1), dilation=dilation, bias=self.bias) # Residual x = self._conv('conv_1', x, padding=[[0,0],[1,1],[1,1],[0,0]], num_filters=filters, kernel_size=(3, 3), stride=(strides, strides), bias=self.bias) x = self._bn('bn_1', x) x = self._relu('relu_1', x) x = self._conv('conv_2', x, padding=[[0,0],[1,1],[1,1],[0,0]], num_filters=filters, kernel_size=(3, 3), bias=self.bias) x = self._bn('bn_2', x) # Merge x = x + shortcut x = self._relu('relu_2', x) print('residual-unit-%s-shape: ' % name + str(x.shape.as_list())) return x @staticmethod def _conv(name, x, num_filters=16, kernel_size=(3, 3), padding='SAME', stride=(1, 1), initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, dilation=1.0, bias=-1): with tf.variable_scope(name): stride = [1, stride[0], stride[1], 1] kernel_shape = [kernel_size[0], kernel_size[1], x.shape[-1], num_filters] w = variable_with_weight_decay(kernel_shape, initializer, l2_strength) variable_summaries(w) if dilation > 1: conv = tf.nn.atrous_conv2d(x, w, dilation, padding) else: if type(padding)==type(''): conv = tf.nn.conv2d(x, w, stride, padding) else: conv = tf.pad(x, padding, "CONSTANT") conv = tf.nn.conv2d(conv, w, stride, padding='VALID') if bias != -1: bias = tf.get_variable('biases', [num_filters], initializer=tf.constant_initializer(bias)) variable_summaries(bias) conv = tf.nn.bias_add(conv, bias) tf.add_to_collection('debug_layers', conv) return conv @staticmethod def _relu(name, x): with tf.variable_scope(name): return tf.nn.relu(x) @staticmethod def _fc(name, x, output_dim=128, initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0, bias=0.0): with tf.variable_scope(name): n_in = x.get_shape()[-1].value w = variable_with_weight_decay([n_in, output_dim], initializer, l2_strength) variable_summaries(w) if isinstance(bias, float): bias = tf.get_variable("biases", [output_dim], tf.float32, tf.constant_initializer(bias)) variable_summaries(bias) output = tf.nn.bias_add(tf.matmul(x, w), bias) return output def _bn(self, name, x): with tf.variable_scope(name): moving_average_decay = 0.9 decay = moving_average_decay batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2]) mu = tf.get_variable('mu', batch_mean.shape, dtype=tf.float32, initializer=tf.zeros_initializer(), trainable=False) tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, mu) tf.add_to_collection('mu_sigma_bn', mu) sigma = tf.get_variable('sigma', batch_var.shape, dtype=tf.float32, initializer=tf.ones_initializer(), trainable=False) tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, sigma) tf.add_to_collection('mu_sigma_bn', sigma) beta = tf.get_variable('beta', batch_mean.shape, dtype=tf.float32, initializer=tf.zeros_initializer()) gamma = tf.get_variable('gamma', batch_var.shape, dtype=tf.float32, initializer=tf.ones_initializer()) # BN when training update = 1.0 - decay update_mu = mu.assign_sub(update * (mu - batch_mean)) update_sigma = sigma.assign_sub(update * (sigma - batch_var)) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mu) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_sigma) mean, var = tf.cond(self.train_flag, lambda: (batch_mean, batch_var), lambda: (mu, sigma)) bn = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5) tf.add_to_collection('debug_layers', bn) return bn
[ "tensorflow.cond", "tensorflow.nn.max_pool", "tensorflow.pad", "tensorflow.nn.atrous_conv2d", "tensorflow.nn.conv2d", "tensorflow.get_collection", "tensorflow.nn.moments", "tensorflow.ones_initializer", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.name_scope", "tensorflow.trainable_variables", "numpy.load", "tensorflow.matmul", "tensorflow.nn.batch_normalization", "tensorflow.zeros_initializer", "tensorflow.identity", "tensorflow.add_to_collection", "tensorflow.nn.bias_add", "tensorflow.nn.relu", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.constant_initializer", "tensorflow.variable_scope" ]
models/encoders/resnet_18.py
[(94, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""debug_layers"""', 'self.x_preprocessed'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.get_collection', 'tf.get_collection', (['"""mu_sigma_bn"""'], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), True, 'import tensorflow as tf\n'), (34, 'numpy.load', 'np.load', (['pretrained_path'], {}), True, 'import numpy as np\n'), (80, 'tensorflow.name_scope', 'tf.name_scope', (['"""Pre_Processing"""'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv1_x"""'], {}), True, 'import tensorflow as tf\n'), (105, 'utils.misc._debug', '_debug', (['self.conv1'], {}), False, 'from utils.misc import _debug\n'), (107, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['self.conv1'], {'ksize': '[1, 3, 3, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""VALID"""', 'name': '"""max_pool1"""'}), True, 'import tensorflow as tf\n'), (109, 'utils.misc._debug', '_debug', (['self.conv1'], {}), False, 'from utils.misc import _debug\n'), (112, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv2_x"""'], {}), True, 'import tensorflow as tf\n'), (114, 'utils.misc._debug', '_debug', (['self.conv2'], {}), False, 'from utils.misc import _debug\n'), (116, 'utils.misc._debug', '_debug', (['self.conv2'], {}), False, 'from utils.misc import _debug\n'), (118, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv3_x"""'], {}), True, 'import tensorflow as tf\n'), (120, 'utils.misc._debug', '_debug', (['self.conv3'], {}), False, 'from utils.misc import _debug\n'), (122, 'utils.misc._debug', '_debug', (['self.conv3'], {}), False, 'from utils.misc import _debug\n'), (124, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv4_x"""'], {}), True, 'import tensorflow as tf\n'), (126, 'utils.misc._debug', '_debug', (['self.conv4'], {}), False, 'from utils.misc import _debug\n'), (128, 'utils.misc._debug', '_debug', (['self.conv4'], {}), False, 'from utils.misc import _debug\n'), (130, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv5_x"""'], {}), True, 'import tensorflow as tf\n'), (132, 'utils.misc._debug', '_debug', (['self.conv5'], {}), False, 'from utils.misc import _debug\n'), (134, 'utils.misc._debug', '_debug', (['self.conv5'], {}), False, 'from utils.misc import _debug\n'), (166, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.identity', 'tf.identity', (['x'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (214, 'layers.utils.variable_with_weight_decay', 'variable_with_weight_decay', (['kernel_shape', 'initializer', 'l2_strength'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (216, 'layers.utils.variable_summaries', 'variable_summaries', (['w'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (232, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""debug_layers"""', 'conv'], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.nn.relu', 'tf.nn.relu', (['x'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (248, 'layers.utils.variable_with_weight_decay', 'variable_with_weight_decay', (['[n_in, output_dim]', 'initializer', 'l2_strength'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (250, 'layers.utils.variable_summaries', 'variable_summaries', (['w'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (255, 'layers.utils.variable_summaries', 'variable_summaries', (['bias'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (262, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[0, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.GLOBAL_VARIABLES', 'mu'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""mu_sigma_bn"""', 'mu'], {}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.GLOBAL_VARIABLES', 'sigma'], {}), True, 'import tensorflow as tf\n'), (275, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""mu_sigma_bn"""', 'sigma'], {}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_mu'], {}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_sigma'], {}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.cond', 'tf.cond', (['self.train_flag', '(lambda : (batch_mean, batch_var))', '(lambda : (mu, sigma))'], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.nn.batch_normalization', 'tf.nn.batch_normalization', (['x', 'mean', 'var', 'beta', 'gamma', '(1e-05)'], {}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""debug_layers"""', 'bn'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.constant', 'tf.constant', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (137, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""logits"""'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['self.conv5'], {'axis': '[1, 2]'}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.nn.atrous_conv2d', 'tf.nn.atrous_conv2d', (['x', 'w', 'dilation', 'padding'], {}), True, 'import tensorflow as tf\n'), (229, 'layers.utils.variable_summaries', 'variable_summaries', (['bias'], {}), False, 'from layers.utils import variable_summaries, variable_with_weight_decay\n'), (230, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['conv', 'bias'], {}), True, 'import tensorflow as tf\n'), (257, 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), True, 'import tensorflow as tf\n'), (37, 'pickle.load', 'pickle.load', (['ff'], {'encoding': '"""latin1"""'}), False, 'import pickle\n'), (221, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'w', 'stride', 'padding'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.pad', 'tf.pad', (['x', 'padding', '"""CONSTANT"""'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['conv', 'w', 'stride'], {'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['bias'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (279, 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.identity', 'tf.identity', (['x'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['shortcut', '[1, strides, strides, 1]', '[1, strides, strides, 1]', '"""VALID"""'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['bias'], {}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.constant', 'tf.constant', (['[[0, 0], [1, 1], [1, 1], [0, 0]]'], {}), True, 'import tensorflow as tf\n')]
Mofokeng-C/rgz_rcnn_py3
00bb9a9179b74db5e3fe469f4249dc00c5c0edfc
# Modified by Chen Wu ([email protected]) from fast_rcnn.config import cfg, get_output_dir import argparse from utils.timer import Timer import numpy as np import cv2 from utils.cython_nms import nms, nms_new from utils.boxes_grid import get_boxes_grid from utils.project_bbox import project_bbox_inv import pickle import heapq from utils.blob import im_list_to_blob import os import math from rpn_msr.generate import imdb_proposals_det import tensorflow as tf from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv, bbox_contains try: import matplotlib.pyplot as plt except: print('Cannot run vis during test due to the unavailability of matplotlib') from tensorflow.python.client import timeline import time from collections import defaultdict def _get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image in BGR order Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ im_orig = im.astype(np.float32, copy=True) im_orig -= cfg.PIXEL_MEANS im_shape = im_orig.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) processed_ims = [] im_scale_factors = [] for target_size in cfg.TEST.SCALES: im_scale = float(target_size) / float(im_size_min) # Prevent the biggest axis from being more than MAX_SIZE if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE: im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max) im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR) im_scale_factors.append(im_scale) processed_ims.append(im) # Create a blob to hold the input images blob = im_list_to_blob(processed_ims) return blob, np.array(im_scale_factors) def _get_rois_blob(im_rois, im_scale_factors): """Converts RoIs into network inputs. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates im_scale_factors (list): scale factors as returned by _get_image_blob Returns: blob (ndarray): R x 5 matrix of RoIs in the image pyramid """ rois, levels = _project_im_rois(im_rois, im_scale_factors) rois_blob = np.hstack((levels, rois)) return rois_blob.astype(np.float32, copy=False) def _project_im_rois(im_rois, scales): """Project image RoIs into the image pyramid built by _get_image_blob. Arguments: im_rois (ndarray): R x 4 matrix of RoIs in original image coordinates scales (list): scale factors as returned by _get_image_blob Returns: rois (ndarray): R x 4 matrix of projected RoI coordinates levels (list): image pyramid levels used by each projected RoI """ im_rois = im_rois.astype(np.float, copy=False) scales = np.array(scales) if len(scales) > 1: widths = im_rois[:, 2] - im_rois[:, 0] + 1 heights = im_rois[:, 3] - im_rois[:, 1] + 1 areas = widths * heights scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1)[:, np.newaxis] else: levels = np.zeros((im_rois.shape[0], 1), dtype=np.int) rois = im_rois * scales[levels] return rois, levels def _get_blobs(im, rois): """Convert an image and RoIs within that image into network inputs.""" if cfg.TEST.HAS_RPN: blobs = {'data' : None, 'rois' : None} blobs['data'], im_scale_factors = _get_image_blob(im) else: blobs = {'data' : None, 'rois' : None} blobs['data'], im_scale_factors = _get_image_blob(im) if cfg.IS_MULTISCALE: if cfg.IS_EXTRAPOLATING: blobs['rois'] = _get_rois_blob(rois, cfg.TEST.SCALES) else: blobs['rois'] = _get_rois_blob(rois, cfg.TEST.SCALES_BASE) else: blobs['rois'] = _get_rois_blob(rois, cfg.TEST.SCALES_BASE) return blobs, im_scale_factors def _clip_boxes(boxes, im_shape): """Clip boxes to image boundaries.""" # x1 >= 0 boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0) # x2 < im_shape[1] boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1) # y2 < im_shape[0] boxes[:, 3::4] = np.minimum(boxes[:, 3::4], im_shape[0] - 1) return boxes def _rescale_boxes(boxes, inds, scales): """Rescale boxes according to image rescaling.""" for i in range(boxes.shape[0]): boxes[i,:] = boxes[i,:] / scales[int(inds[i])] return boxes def im_detect(sess, net, im, boxes=None, save_vis_dir=None, img_name='', include_rpn_score=False): """Detect object classes in an image given object proposals. Arguments: net (caffe.Net): Fast R-CNN network to use im (ndarray): color image to test (in BGR order) boxes (ndarray): R x 4 array of object proposals Returns: scores (ndarray): R x K array of object class scores (K includes background as object category 0) boxes (ndarray): R x (4*K) array of predicted bounding boxes """ blobs, im_scales = _get_blobs(im, boxes) # When mapping from image ROIs to feature map ROIs, there's some aliasing # (some distinct image ROIs get mapped to the same feature ROI). # Here, we identify duplicate feature ROIs, so we only compute features # on the unique subset. if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN: v = np.array([1, 1e3, 1e6, 1e9, 1e12]) hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v) _, index, inv_index = np.unique(hashes, return_index=True, return_inverse=True) blobs['rois'] = blobs['rois'][index, :] boxes = boxes[index, :] if cfg.TEST.HAS_RPN: im_blob = blobs['data'] blobs['im_info'] = np.array( [[im_blob.shape[1], im_blob.shape[2], im_scales[0]]], dtype=np.float32) # forward pass if cfg.TEST.HAS_RPN: feed_dict={net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0} else: feed_dict={net.data: blobs['data'], net.rois: blobs['rois'], net.keep_prob: 1.0} run_options = None run_metadata = None if cfg.TEST.DEBUG_TIMELINE: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() #theta_tensor = tf.get_default_graph().get_tensor_by_name('spt_trans_theta') cls_score, cls_prob, bbox_pred, rois = sess.run([net.get_output('cls_score'), net.get_output('cls_prob'), net.get_output('bbox_pred'), net.get_output('rois')], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) if (save_vis_dir is not None and os.path.exists(save_vis_dir)): # first get the weights out with tf.variable_scope('conv5_3', reuse=True) as scope: conv5_3_weights = tf.get_variable("weights") conv5_3_weights_np, conv5_3_features, st_pool_features =\ sess.run([conv5_3_weights, net.get_output('conv5_3'), net.get_output('pool_5')], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata) np.save(os.path.join(save_vis_dir, '%s_conv5_3_w.npy' % img_name), conv5_3_weights_np) np.save(os.path.join(save_vis_dir, '%s_conv5_3_f.npy' % img_name), conv5_3_features) np.save(os.path.join(save_vis_dir, '%s_st_pool_f.npy' % img_name), st_pool_features) if cfg.TEST.HAS_RPN: assert len(im_scales) == 1, "Only single-image batch implemented" boxes = rois[:, 1:5] / im_scales[0] if cfg.TEST.SVM: # use the raw scores before softmax under the assumption they # were trained as linear SVMs scores = cls_score else: # use softmax estimated probabilities scores = cls_prob if cfg.TEST.BBOX_REG: # Apply bounding-box regression deltas box_deltas = bbox_pred pred_boxes = bbox_transform_inv(boxes, box_deltas) #project_bbox_inv(pred_boxes, theta) # project spatially transformed box back pred_boxes = _clip_boxes(pred_boxes, im.shape) else: # Simply repeat the boxes, once for each class pred_boxes = np.tile(boxes, (1, scores.shape[1])) if cfg.DEDUP_BOXES > 0 and not cfg.TEST.HAS_RPN: # Map scores and predictions back to the original set of boxes scores = scores[inv_index, :] pred_boxes = pred_boxes[inv_index, :] if cfg.TEST.DEBUG_TIMELINE: trace = timeline.Timeline(step_stats=run_metadata.step_stats) trace_file = open(str(int(time.time() * 1000)) + '-test-timeline.ctf.json', 'w') trace_file.write(trace.generate_chrome_trace_format(show_memory=False)) trace_file.close() if (include_rpn_score): # score is a joint prob instead of conditional prob scores *= np.reshape(rois[:, 0], [-1, 1]) return scores, pred_boxes def vis_detections(im, class_name, dets, thresh=0.8): """Visual debugging of detections.""" import matplotlib.pyplot as plt #im = im[:, :, (2, 1, 0)] for i in range(np.minimum(10, dets.shape[0])): bbox = dets[i, :4] score = dets[i, -1] if score > thresh: #plt.cla() #plt.imshow(im) plt.gca().add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='g', linewidth=3) ) plt.gca().text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') plt.title('{} {:.3f}'.format(class_name, score)) #plt.show() def apply_nms(all_boxes, thresh): """Apply non-maximum suppression to all predicted boxes output by the test_net method. """ num_classes = len(all_boxes) num_images = len(all_boxes[0]) nms_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)] for cls_ind in range(num_classes): for im_ind in range(num_images): dets = all_boxes[cls_ind][im_ind] if dets == []: continue x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] inds = np.where((x2 > x1) & (y2 > y1) & (scores > cfg.TEST.DET_THRESHOLD))[0] dets = dets[inds,:] if dets == []: continue keep = nms(dets, thresh) if len(keep) == 0: continue nms_boxes[cls_ind][im_ind] = dets[keep, :].copy() return nms_boxes def remove_embedded(boxes, scores, remove_option=1): """ Return indices of those that should be KEPT """ removed_indices = set() num_props = boxes.shape[0] for i in range(num_props): if (i in removed_indices): continue bxA = boxes[i, :] for j in range(num_props): if ((j == i) or (j in removed_indices)): continue bxB = boxes[j, :] if (bbox_contains(bxA, bxB, delta=0)): if ((1 == remove_option) and (scores[i] != scores[j])): if (scores[i] > scores[j]): removed_indices.add(j) else: removed_indices.add(i) else: # remove_option == 2 or scores[i] == scores[j] removed_indices.add(j) return sorted(set(range(num_props)) - removed_indices) # nr = len(removed_indices) # if (nr > 0): # new_boxes = sorted(set(range(num_props)) - removed_indices) # boxes = boxes[new_boxes, :] # scores = scores[new_boxes] # # return boxes, scores def test_net(sess, net, imdb, weights_filename , max_per_image=300, thresh=0.05, vis=False, force=False): """Test a Fast R-CNN network on an image database.""" num_images = len(imdb.image_index) # all detections are collected into: # all_boxes[cls][image] = N x 5 array of detections in # (x1, y1, x2, y2, score) all_boxes = [[[] for _ in range(num_images)] for _ in range(imdb.num_classes)] output_dir = get_output_dir(imdb, weights_filename) det_file = os.path.join(output_dir, 'detections.pkl') if (force and os.path.exists(det_file)): os.remove(det_file) if (not os.path.exists(det_file)): # timers _t = {'im_detect' : Timer(), 'misc' : Timer()} if not cfg.TEST.HAS_RPN: roidb = imdb.roidb for i in range(num_images): # filter out any ground truth boxes if cfg.TEST.HAS_RPN: box_proposals = None else: # The roidb may contain ground-truth rois (for example, if the roidb # comes from the training or val split). We only want to evaluate # detection on the *non*-ground-truth rois. We select those the rois # that have the gt_classes field set to 0, which means there's no # ground truth. box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0] im = cv2.imread(imdb.image_path_at(i)) _t['im_detect'].tic() scores, boxes = im_detect(sess, net, im, box_proposals) _t['im_detect'].toc() _t['misc'].tic() if vis: image = im[:, :, (2, 1, 0)] plt.cla() plt.imshow(image) # skip j = 0, because it's the background class ttt = 0 bbox_img = [] bscore_img = [] bbc = 0 #bbox count index_map = dict() for j in range(1, imdb.num_classes): inds = np.where(scores[:, j] > thresh)[0] ttt += len(inds) cls_scores = scores[inds, j] cls_boxes = boxes[inds, j*4:(j+1)*4] cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \ .astype(np.float32, copy=False) keep = nms(cls_dets, cfg.TEST.NMS) cls_dets = cls_dets[keep, :] if vis: vis_detections(image, imdb.classes[j], cls_dets) all_boxes[j][i] = cls_dets #cls_dets.shape == [nb_detections_for_cls_j, 5] # we need to get all bboxes in a image regardless of classes # if (cls_dets.shape[0] > 0): # bbox_img.append(cls_dets[:, 0:-1]) # bscore_img.append(np.reshape(cls_dets[:, -1], [-1, 1])) # # remember the mapping # for bc in range(cls_dets.shape[0]): # index_map[bbc] = (j, bc) # bbc += 1 removed = 0 # if (len(bbox_img) > 0): # boxes = np.vstack(bbox_img) # scores = np.vstack(bscore_img) # keep_indices = remove_embedded(boxes, scores, remove_option=1) # removed = bbc - len(keep_indices) # # need to find out which j, and which k correspond to which index # cls_keep = defaultdict(list) # for ki in keep_indices: # j, bc = index_map[ki] # cls_keep[j].append(bc) # # for j in xrange(1, imdb.num_classes): # if (j in cls_keep): # all_boxes[j][i] = all_boxes[j][i][cls_keep[j], :] if vis: plt.show() # Limit to max_per_image detections *over all classes* if max_per_image > 0: image_scores = np.hstack([all_boxes[j][i][:, -1] for j in range(1, imdb.num_classes)]) if len(image_scores) > max_per_image: image_thresh = np.sort(image_scores)[-max_per_image] for j in range(1, imdb.num_classes): keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0] all_boxes[j][i] = all_boxes[j][i][keep, :] _t['misc'].toc() print('im_detect: {:d}/{:d} {:d} detection {:d} removed {:.3f}s' \ .format(i + 1, num_images, ttt, removed, _t['im_detect'].average_time)) with open(det_file, 'wb') as f: pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL) else: with open(det_file, 'r') as fin: all_boxes = pickle.load(fin) print('Evaluating detections') imdb.evaluate_detections(all_boxes, output_dir)
[ "tensorflow.get_variable", "matplotlib.pyplot.imshow", "numpy.minimum", "tensorflow.RunMetadata", "numpy.round", "numpy.max", "numpy.where", "tensorflow.python.client.timeline.Timeline", "numpy.hstack", "matplotlib.pyplot.gca", "numpy.unique", "numpy.reshape", "numpy.zeros", "numpy.min", "tensorflow.RunOptions", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.Rectangle", "numpy.maximum", "numpy.abs", "matplotlib.pyplot.cla", "numpy.tile", "numpy.sort", "tensorflow.variable_scope" ]
lib/fast_rcnn/test.py
[(40, 'numpy.min', 'np.min', (['im_shape[0:2]'], {}), True, 'import numpy as np\n'), (41, 'numpy.max', 'np.max', (['im_shape[0:2]'], {}), True, 'import numpy as np\n'), (57, 'utils.blob.im_list_to_blob', 'im_list_to_blob', (['processed_ims'], {}), False, 'from utils.blob import im_list_to_blob\n'), (70, 'numpy.hstack', 'np.hstack', (['(levels, rois)'], {}), True, 'import numpy as np\n'), (83, 'numpy.array', 'np.array', (['scales'], {}), True, 'import numpy as np\n'), (121, 'numpy.maximum', 'np.maximum', (['boxes[:, 0::4]', '(0)'], {}), True, 'import numpy as np\n'), (123, 'numpy.maximum', 'np.maximum', (['boxes[:, 1::4]', '(0)'], {}), True, 'import numpy as np\n'), (125, 'numpy.minimum', 'np.minimum', (['boxes[:, 2::4]', '(im_shape[1] - 1)'], {}), True, 'import numpy as np\n'), (127, 'numpy.minimum', 'np.minimum', (['boxes[:, 3::4]', '(im_shape[0] - 1)'], {}), True, 'import numpy as np\n'), (341, 'fast_rcnn.config.get_output_dir', 'get_output_dir', (['imdb', 'weights_filename'], {}), False, 'from fast_rcnn.config import cfg, get_output_dir\n'), (342, 'os.path.join', 'os.path.join', (['output_dir', '"""detections.pkl"""'], {}), False, 'import os\n'), (51, 'cv2.resize', 'cv2.resize', (['im_orig', 'None', 'None'], {'fx': 'im_scale', 'fy': 'im_scale', 'interpolation': 'cv2.INTER_LINEAR'}), False, 'import cv2\n'), (59, 'numpy.array', 'np.array', (['im_scale_factors'], {}), True, 'import numpy as np\n'), (91, 'numpy.abs', 'np.abs', (['(scaled_areas - 224 * 224)'], {}), True, 'import numpy as np\n'), (94, 'numpy.zeros', 'np.zeros', (['(im_rois.shape[0], 1)'], {'dtype': 'np.int'}), True, 'import numpy as np\n'), (160, 'numpy.array', 'np.array', (['[1, 1000.0, 1000000.0, 1000000000.0, 1000000000000.0]'], {}), True, 'import numpy as np\n'), (162, 'numpy.unique', 'np.unique', (['hashes'], {'return_index': '(True)', 'return_inverse': '(True)'}), True, 'import numpy as np\n'), (169, 'numpy.array', 'np.array', (['[[im_blob.shape[1], im_blob.shape[2], im_scales[0]]]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (181, 'tensorflow.RunOptions', 'tf.RunOptions', ([], {'trace_level': 'tf.RunOptions.FULL_TRACE'}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.RunMetadata', 'tf.RunMetadata', ([], {}), True, 'import tensorflow as tf\n'), (191, 'os.path.exists', 'os.path.exists', (['save_vis_dir'], {}), False, 'import os\n'), (222, 'fast_rcnn.bbox_transform.bbox_transform_inv', 'bbox_transform_inv', (['boxes', 'box_deltas'], {}), False, 'from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv, bbox_contains\n'), (227, 'numpy.tile', 'np.tile', (['boxes', '(1, scores.shape[1])'], {}), True, 'import numpy as np\n'), (235, 'tensorflow.python.client.timeline.Timeline', 'timeline.Timeline', ([], {'step_stats': 'run_metadata.step_stats'}), False, 'from tensorflow.python.client import timeline\n'), (242, 'numpy.reshape', 'np.reshape', (['rois[:, (0)]', '[-1, 1]'], {}), True, 'import numpy as np\n'), (250, 'numpy.minimum', 'np.minimum', (['(10)', 'dets.shape[0]'], {}), True, 'import numpy as np\n'), (343, 'os.path.exists', 'os.path.exists', (['det_file'], {}), False, 'import os\n'), (344, 'os.remove', 'os.remove', (['det_file'], {}), False, 'import os\n'), (345, 'os.path.exists', 'os.path.exists', (['det_file'], {}), False, 'import os\n'), (49, 'numpy.round', 'np.round', (['(im_scale * im_size_max)'], {}), True, 'import numpy as np\n'), (193, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv5_3"""'], {'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.get_variable', 'tf.get_variable', (['"""weights"""'], {}), True, 'import tensorflow as tf\n'), (201, 'os.path.join', 'os.path.join', (['save_vis_dir', "('%s_conv5_3_w.npy' % img_name)"], {}), False, 'import os\n'), (202, 'os.path.join', 'os.path.join', (['save_vis_dir', "('%s_conv5_3_f.npy' % img_name)"], {}), False, 'import os\n'), (203, 'os.path.join', 'os.path.join', (['save_vis_dir', "('%s_st_pool_f.npy' % img_name)"], {}), False, 'import os\n'), (294, 'utils.cython_nms.nms', 'nms', (['dets', 'thresh'], {}), False, 'from utils.cython_nms import nms, nms_new\n'), (314, 'fast_rcnn.bbox_transform.bbox_contains', 'bbox_contains', (['bxA', 'bxB'], {'delta': '(0)'}), False, 'from fast_rcnn.bbox_transform import clip_boxes, bbox_transform_inv, bbox_contains\n'), (347, 'utils.timer.Timer', 'Timer', ([], {}), False, 'from utils.timer import Timer\n'), (347, 'utils.timer.Timer', 'Timer', ([], {}), False, 'from utils.timer import Timer\n'), (435, 'pickle.dump', 'pickle.dump', (['all_boxes', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), False, 'import pickle\n'), (438, 'pickle.load', 'pickle.load', (['fin'], {}), False, 'import pickle\n'), (161, 'numpy.round', 'np.round', (["(blobs['rois'] * cfg.DEDUP_BOXES)"], {}), True, 'import numpy as np\n'), (257, 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['(bbox[0], bbox[1])', '(bbox[2] - bbox[0])', '(bbox[3] - bbox[1])'], {'fill': '(False)', 'edgecolor': '"""g"""', 'linewidth': '(3)'}), True, 'import matplotlib.pyplot as plt\n'), (289, 'numpy.where', 'np.where', (['((x2 > x1) & (y2 > y1) & (scores > cfg.TEST.DET_THRESHOLD))'], {}), True, 'import numpy as np\n'), (372, 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (373, 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), True, 'import matplotlib.pyplot as plt\n'), (388, 'utils.cython_nms.nms', 'nms', (['cls_dets', 'cfg.TEST.NMS'], {}), False, 'from utils.cython_nms import nms, nms_new\n'), (419, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (256, 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (262, 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (382, 'numpy.where', 'np.where', (['(scores[:, (j)] > thresh)'], {}), True, 'import numpy as np\n'), (386, 'numpy.hstack', 'np.hstack', (['(cls_boxes, cls_scores[:, (np.newaxis)])'], {}), True, 'import numpy as np\n'), (425, 'numpy.sort', 'np.sort', (['image_scores'], {}), True, 'import numpy as np\n'), (236, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (427, 'numpy.where', 'np.where', (['(all_boxes[j][i][:, (-1)] >= image_thresh)'], {}), True, 'import numpy as np\n')]
WenjayDu/PocketFlow
19ed4858b2fc914541032f74239ca08c0074c237
# Tencent is pleased to support the open source community by making PocketFlow available. # # Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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. # ============================================================================== """Weight sparsification learner.""" import os from timeit import default_timer as timer import numpy as np import tensorflow as tf from learners.abstract_learner import AbstractLearner from learners.distillation_helper import DistillationHelper from learners.weight_sparsification.pr_optimizer import PROptimizer from learners.weight_sparsification.utils import get_maskable_vars from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('ws_save_path', './models_ws/model.ckpt', 'WS: model\'s save path') tf.app.flags.DEFINE_float('ws_prune_ratio', 0.75, 'WS: target pruning ratio') tf.app.flags.DEFINE_string('ws_prune_ratio_prtl', 'optimal', 'WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')') tf.app.flags.DEFINE_integer('ws_nb_rlouts', 200, 'WS: # of roll-outs for the RL agent') tf.app.flags.DEFINE_integer('ws_nb_rlouts_min', 50, 'WS: minimal # of roll-outs for the RL agent to start training') tf.app.flags.DEFINE_string('ws_reward_type', 'single-obj', 'WS: reward type (\'single-obj\' OR \'multi-obj\')') tf.app.flags.DEFINE_float('ws_lrn_rate_rg', 3e-2, 'WS: learning rate for layerwise regression') tf.app.flags.DEFINE_integer('ws_nb_iters_rg', 20, 'WS: # of iterations for layerwise regression') tf.app.flags.DEFINE_float('ws_lrn_rate_ft', 3e-4, 'WS: learning rate for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_ft', 400, 'WS: # of iterations for global fine-tuning') tf.app.flags.DEFINE_integer('ws_nb_iters_feval', 25, 'WS: # of iterations for fast evaluation') tf.app.flags.DEFINE_float('ws_prune_ratio_exp', 3.0, 'WS: pruning ratio\'s exponent term') tf.app.flags.DEFINE_float('ws_iter_ratio_beg', 0.1, 'WS: iteration ratio (at starting time)') tf.app.flags.DEFINE_float('ws_iter_ratio_end', 0.5, 'WS: iteration ratio (at ending time)') tf.app.flags.DEFINE_float('ws_mask_update_step', 500, 'WS: step size for updating the pruning mask') def calc_prune_ratio(vars_list): """Calculate the overall pruning ratio for the given list of variables. Args: * vars_list: list of variables Returns: * prune_ratio: overall pruning ratio of the given list of variables """ nb_params_nnz = tf.add_n([tf.count_nonzero(var) for var in vars_list]) nb_params_all = tf.add_n([tf.size(var) for var in vars_list]) prune_ratio = 1.0 - tf.cast(nb_params_nnz, tf.float32) / tf.cast(nb_params_all, tf.float32) return prune_ratio class WeightSparseLearner(AbstractLearner): # pylint: disable=too-many-instance-attributes """Weight sparsification learner.""" def __init__(self, sm_writer, model_helper): """Constructor function. Args: * sm_writer: TensorFlow's summary writer * model_helper: model helper with definitions of model & dataset """ # class-independent initialization super(WeightSparseLearner, self).__init__(sm_writer, model_helper) # define the scope for masks self.mask_scope = 'mask' # compute the optimal pruning ratios (only when the execution mode is 'train') if FLAGS.exec_mode == 'train': pr_optimizer = PROptimizer(model_helper, self.mpi_comm) if FLAGS.ws_prune_ratio_prtl == 'optimal': if self.is_primary_worker('local'): self.download_model() # pre-trained model is required self.auto_barrier() tf.logging.info('model files: ' + ', '.join(os.listdir('./models'))) self.var_names_n_prune_ratios = pr_optimizer.run() # class-dependent initialization if FLAGS.enbl_dst: self.helper_dst = DistillationHelper(sm_writer, model_helper, self.mpi_comm) if FLAGS.exec_mode == 'train': self.__build_train() # only when the execution mode is 'train' self.__build_eval() # needed whatever the execution mode is def train(self): """Train a model and periodically produce checkpoint files.""" # initialization self.sess_train.run(self.init_op) if FLAGS.enbl_multi_gpu: self.sess_train.run(self.bcast_op) # train the model through iterations and periodically save & evaluate the model last_mask_applied = False time_prev = timer() for idx_iter in range(self.nb_iters_train): # train the model if (idx_iter + 1) % FLAGS.summ_step != 0: self.sess_train.run(self.train_op) else: __, summary, log_rslt = self.sess_train.run([self.train_op, self.summary_op, self.log_op]) if self.is_primary_worker('global'): time_step = timer() - time_prev self.__monitor_progress(summary, log_rslt, idx_iter, time_step) time_prev = timer() # apply pruning if (idx_iter + 1) % FLAGS.ws_mask_update_step == 0: iter_ratio = float(idx_iter + 1) / self.nb_iters_train if iter_ratio >= FLAGS.ws_iter_ratio_beg: if iter_ratio <= FLAGS.ws_iter_ratio_end: self.sess_train.run([self.prune_op, self.init_opt_op]) elif not last_mask_applied: last_mask_applied = True self.sess_train.run([self.prune_op, self.init_opt_op]) # save the model at certain steps if self.is_primary_worker('global') and (idx_iter + 1) % FLAGS.save_step == 0: self.__save_model() self.evaluate() # save the final model if self.is_primary_worker('global'): self.__save_model() self.evaluate() def evaluate(self): """Restore a model from the latest checkpoint files and then evaluate it.""" self.__restore_model(is_train=False) nb_iters = int(np.ceil(float(FLAGS.nb_smpls_eval) / FLAGS.batch_size_eval)) eval_rslts = np.zeros((nb_iters, len(self.eval_op))) for idx_iter in range(nb_iters): eval_rslts[idx_iter] = self.sess_eval.run(self.eval_op) for idx, name in enumerate(self.eval_op_names): tf.logging.info('%s = %.4e' % (name, np.mean(eval_rslts[:, idx]))) def __build_train(self): # pylint: disable=too-many-locals """Build the training graph.""" with tf.Graph().as_default(): # create a TF session for the current graph config = tf.ConfigProto() if FLAGS.enbl_multi_gpu: config.gpu_options.visible_device_list = str(mgw.local_rank()) # pylint: disable=no-member else: config.gpu_options.visible_device_list = '0' # pylint: disable=no-member sess = tf.Session(config=config) # data input pipeline with tf.variable_scope(self.data_scope): iterator = self.build_dataset_train() images, labels = iterator.get_next() # model definition - distilled model if FLAGS.enbl_dst: logits_dst = self.helper_dst.calc_logits(sess, images) # model definition - weight-sparsified model with tf.variable_scope(self.model_scope): # loss & extra evaluation metrics logits = self.forward_train(images) self.maskable_var_names = [var.name for var in self.maskable_vars] loss, metrics = self.calc_loss(labels, logits, self.trainable_vars) if FLAGS.enbl_dst: loss += self.helper_dst.calc_loss(logits, logits_dst) tf.summary.scalar('loss', loss) for key, value in metrics.items(): tf.summary.scalar(key, value) # learning rate schedule self.global_step = tf.train.get_or_create_global_step() lrn_rate, self.nb_iters_train = self.setup_lrn_rate(self.global_step) # overall pruning ratios of trainable & maskable variables pr_trainable = calc_prune_ratio(self.trainable_vars) pr_maskable = calc_prune_ratio(self.maskable_vars) tf.summary.scalar('pr_trainable', pr_trainable) tf.summary.scalar('pr_maskable', pr_maskable) # build masks and corresponding operations for weight sparsification self.masks, self.prune_op = self.__build_masks() # optimizer & gradients optimizer_base = tf.train.MomentumOptimizer(lrn_rate, FLAGS.momentum) if not FLAGS.enbl_multi_gpu: optimizer = optimizer_base else: optimizer = mgw.DistributedOptimizer(optimizer_base) grads_origin = optimizer.compute_gradients(loss, self.trainable_vars) grads_pruned = self.__calc_grads_pruned(grads_origin) # TF operations & model saver self.sess_train = sess with tf.control_dependencies(self.update_ops): self.train_op = optimizer.apply_gradients(grads_pruned, global_step=self.global_step) self.summary_op = tf.summary.merge_all() self.log_op = [lrn_rate, loss, pr_trainable, pr_maskable] + list(metrics.values()) self.log_op_names = ['lr', 'loss', 'pr_trn', 'pr_msk'] + list(metrics.keys()) self.init_op = tf.variables_initializer(self.vars) self.init_opt_op = tf.variables_initializer(optimizer_base.variables()) if FLAGS.enbl_multi_gpu: self.bcast_op = mgw.broadcast_global_variables(0) self.saver_train = tf.train.Saver(self.vars) def __build_eval(self): """Build the evaluation graph.""" with tf.Graph().as_default(): # create a TF session for the current graph config = tf.ConfigProto() if FLAGS.enbl_multi_gpu: config.gpu_options.visible_device_list = str(mgw.local_rank()) # pylint: disable=no-member else: config.gpu_options.visible_device_list = '0' # pylint: disable=no-member self.sess_eval = tf.Session(config=config) # data input pipeline with tf.variable_scope(self.data_scope): iterator = self.build_dataset_eval() images, labels = iterator.get_next() # model definition - distilled model if FLAGS.enbl_dst: logits_dst = self.helper_dst.calc_logits(self.sess_eval, images) # model definition - weight-sparsified model with tf.variable_scope(self.model_scope): # loss & extra evaluation metrics logits = self.forward_eval(images) loss, metrics = self.calc_loss(labels, logits, self.trainable_vars) if FLAGS.enbl_dst: loss += self.helper_dst.calc_loss(logits, logits_dst) # overall pruning ratios of trainable & maskable variables pr_trainable = calc_prune_ratio(self.trainable_vars) pr_maskable = calc_prune_ratio(self.maskable_vars) # TF operations for evaluation self.eval_op = [loss, pr_trainable, pr_maskable] + list(metrics.values()) self.eval_op_names = ['loss', 'pr_trn', 'pr_msk'] + list(metrics.keys()) self.saver_eval = tf.train.Saver(self.vars) def __build_masks(self): """build masks and corresponding operations for weight sparsification. Returns: * masks: list of masks for weight sparsification * prune_op: pruning operation """ masks, prune_ops = [], [] with tf.variable_scope(self.mask_scope): for var, var_name_n_prune_ratio in zip(self.maskable_vars, self.var_names_n_prune_ratios): # obtain the dynamic pruning ratio assert var.name == var_name_n_prune_ratio[0], \ 'unmatched variable names: %s vs. %s' % (var.name, var_name_n_prune_ratio[0]) prune_ratio = self.__calc_prune_ratio_dyn(var_name_n_prune_ratio[1]) # create a mask and non-masked backup for each variable name = var.name.replace(':0', '_mask') mask = tf.get_variable(name, initializer=tf.ones(var.shape), trainable=False) name = var.name.replace(':0', '_var_bkup') var_bkup = tf.get_variable(name, initializer=var.initialized_value(), trainable=False) # create update operations var_bkup_update_op = var_bkup.assign(tf.where(mask > 0.5, var, var_bkup)) with tf.control_dependencies([var_bkup_update_op]): mask_thres = tf.contrib.distributions.percentile(tf.abs(var_bkup), prune_ratio * 100) mask_update_op = mask.assign(tf.cast(tf.abs(var_bkup) > mask_thres, tf.float32)) with tf.control_dependencies([mask_update_op]): prune_op = var.assign(var_bkup * mask) # record pruning masks & operations masks += [mask] prune_ops += [prune_op] return masks, tf.group(prune_ops) def __calc_prune_ratio_dyn(self, prune_ratio_fnl): """Calculate the dynamic pruning ratio. Args: * prune_ratio_fnl: final pruning ratio Returns: * prune_ratio_dyn: dynamic pruning ratio """ idx_iter_beg = int(self.nb_iters_train * FLAGS.ws_iter_ratio_beg) idx_iter_end = int(self.nb_iters_train * FLAGS.ws_iter_ratio_end) base = tf.cast(self.global_step - idx_iter_beg, tf.float32) / (idx_iter_end - idx_iter_beg) base = tf.minimum(1.0, tf.maximum(0.0, base)) prune_ratio_dyn = prune_ratio_fnl * (1.0 - tf.pow(1.0 - base, FLAGS.ws_prune_ratio_exp)) return prune_ratio_dyn def __calc_grads_pruned(self, grads_origin): """Calculate the mask-pruned gradients. Args: * grads_origin: list of original gradients Returns: * grads_pruned: list of mask-pruned gradients """ grads_pruned = [] for grad in grads_origin: if grad[1].name not in self.maskable_var_names: grads_pruned += [grad] else: idx_mask = self.maskable_var_names.index(grad[1].name) grads_pruned += [(grad[0] * self.masks[idx_mask], grad[1])] return grads_pruned def __save_model(self): """Save the current model.""" save_path = self.saver_train.save(self.sess_train, FLAGS.ws_save_path, self.global_step) tf.logging.info('model saved to ' + save_path) def __restore_model(self, is_train): """Restore a model from the latest checkpoint files. Args: * is_train: whether to restore a model for training """ save_path = tf.train.latest_checkpoint(os.path.dirname(FLAGS.ws_save_path)) if is_train: self.saver_train.restore(self.sess_train, save_path) else: self.saver_eval.restore(self.sess_eval, save_path) tf.logging.info('model restored from ' + save_path) def __monitor_progress(self, summary, log_rslt, idx_iter, time_step): """Monitor the training progress. Args: * summary: summary protocol buffer * log_rslt: logging operations' results * idx_iter: index of the training iteration * time_step: time step between two summary operations """ # write summaries for TensorBoard visualization self.sm_writer.add_summary(summary, idx_iter) # compute the training speed speed = FLAGS.batch_size * FLAGS.summ_step / time_step if FLAGS.enbl_multi_gpu: speed *= mgw.size() # display monitored statistics log_str = ' | '.join(['%s = %.4e' % (name, value) for name, value in zip(self.log_op_names, log_rslt)]) tf.logging.info('iter #%d: %s | speed = %.2f pics / sec' % (idx_iter + 1, log_str, speed)) @property def maskable_vars(self): """List of all maskable variables.""" return get_maskable_vars(self.trainable_vars)
[ "tensorflow.count_nonzero", "tensorflow.control_dependencies", "tensorflow.cast", "tensorflow.variables_initializer", "tensorflow.app.flags.DEFINE_string", "numpy.mean", "tensorflow.where", "tensorflow.group", "tensorflow.summary.scalar", "tensorflow.Graph", "tensorflow.app.flags.DEFINE_integer", "tensorflow.train.get_or_create_global_step", "tensorflow.ConfigProto", "tensorflow.train.MomentumOptimizer", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.pow", "tensorflow.logging.info", "tensorflow.summary.merge_all", "tensorflow.size", "tensorflow.maximum", "tensorflow.ones", "tensorflow.app.flags.DEFINE_float", "tensorflow.variable_scope", "tensorflow.abs" ]
learners/weight_sparsification/learner.py
[(32, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""ws_save_path"""', '"""./models_ws/model.ckpt"""', '"""WS: model\'s save path"""'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_prune_ratio"""', '(0.75)', '"""WS: target pruning ratio"""'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""ws_prune_ratio_prtl"""', '"""optimal"""', '"""WS: pruning ratio protocol (\'uniform\' | \'heurist\' | \'optimal\')"""'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""ws_nb_rlouts"""', '(200)', '"""WS: # of roll-outs for the RL agent"""'], {}), True, 'import tensorflow as tf\n'), (37, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""ws_nb_rlouts_min"""', '(50)', '"""WS: minimal # of roll-outs for the RL agent to start training"""'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""ws_reward_type"""', '"""single-obj"""', '"""WS: reward type (\'single-obj\' OR \'multi-obj\')"""'], {}), True, 'import tensorflow as tf\n'), (41, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_lrn_rate_rg"""', '(0.03)', '"""WS: learning rate for layerwise regression"""'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""ws_nb_iters_rg"""', '(20)', '"""WS: # of iterations for layerwise regression"""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_lrn_rate_ft"""', '(0.0003)', '"""WS: learning rate for global fine-tuning"""'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""ws_nb_iters_ft"""', '(400)', '"""WS: # of iterations for global fine-tuning"""'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""ws_nb_iters_feval"""', '(25)', '"""WS: # of iterations for fast evaluation"""'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_prune_ratio_exp"""', '(3.0)', '"""WS: pruning ratio\'s exponent term"""'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_iter_ratio_beg"""', '(0.1)', '"""WS: iteration ratio (at starting time)"""'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_iter_ratio_end"""', '(0.5)', '"""WS: iteration ratio (at ending time)"""'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""ws_mask_update_step"""', '(500)', '"""WS: step size for updating the pruning mask"""'], {}), True, 'import tensorflow as tf\n'), (108, 'timeit.default_timer', 'timer', ([], {}), True, 'from timeit import default_timer as timer\n'), (330, 'tensorflow.logging.info', 'tf.logging.info', (["('model saved to ' + save_path)"], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.logging.info', 'tf.logging.info', (["('model restored from ' + save_path)"], {}), True, 'import tensorflow as tf\n'), (365, 'tensorflow.logging.info', 'tf.logging.info', (["('iter #%d: %s | speed = %.2f pics / sec' % (idx_iter + 1, log_str, speed))"], {}), True, 'import tensorflow as tf\n'), (371, 'learners.weight_sparsification.utils.get_maskable_vars', 'get_maskable_vars', (['self.trainable_vars'], {}), False, 'from learners.weight_sparsification.utils import get_maskable_vars\n'), (59, 'tensorflow.count_nonzero', 'tf.count_nonzero', (['var'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.size', 'tf.size', (['var'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.cast', 'tf.cast', (['nb_params_nnz', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.cast', 'tf.cast', (['nb_params_all', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (83, 'learners.weight_sparsification.pr_optimizer.PROptimizer', 'PROptimizer', (['model_helper', 'self.mpi_comm'], {}), False, 'from learners.weight_sparsification.pr_optimizer import PROptimizer\n'), (93, 'learners.distillation_helper.DistillationHelper', 'DistillationHelper', (['sm_writer', 'model_helper', 'self.mpi_comm'], {}), False, 'from learners.distillation_helper import DistillationHelper\n'), (156, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.variables_initializer', 'tf.variables_initializer', (['self.vars'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.train.Saver', 'tf.train.Saver', (['self.vars'], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.mask_scope'], {}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.group', 'tf.group', (['prune_ops'], {}), True, 'import tensorflow as tf\n'), (302, 'tensorflow.cast', 'tf.cast', (['(self.global_step - idx_iter_beg)', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (303, 'tensorflow.maximum', 'tf.maximum', (['(0.0)', 'base'], {}), True, 'import tensorflow as tf\n'), (338, 'os.path.dirname', 'os.path.dirname', (['FLAGS.ws_save_path'], {}), False, 'import os\n'), (360, 'utils.multi_gpu_wrapper.MultiGpuWrapper.size', 'mgw.size', ([], {}), True, 'from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw\n'), (164, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.data_scope'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.model_scope'], {}), True, 'import tensorflow as tf\n'), (180, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""loss"""', 'loss'], {}), True, 'import tensorflow as tf\n'), (185, 'tensorflow.train.get_or_create_global_step', 'tf.train.get_or_create_global_step', ([], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""pr_trainable"""', 'pr_trainable'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""pr_maskable"""', 'pr_maskable'], {}), True, 'import tensorflow as tf\n'), (198, 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['lrn_rate', 'FLAGS.momentum'], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['self.update_ops'], {}), True, 'import tensorflow as tf\n'), (216, 'utils.multi_gpu_wrapper.MultiGpuWrapper.broadcast_global_variables', 'mgw.broadcast_global_variables', (['(0)'], {}), True, 'from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw\n'), (232, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.data_scope'], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.model_scope'], {}), True, 'import tensorflow as tf\n'), (255, 'tensorflow.train.Saver', 'tf.train.Saver', (['self.vars'], {}), True, 'import tensorflow as tf\n'), (304, 'tensorflow.pow', 'tf.pow', (['(1.0 - base)', 'FLAGS.ws_prune_ratio_exp'], {}), True, 'import tensorflow as tf\n'), (118, 'timeit.default_timer', 'timer', ([], {}), True, 'from timeit import default_timer as timer\n'), (154, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (158, 'utils.multi_gpu_wrapper.MultiGpuWrapper.local_rank', 'mgw.local_rank', ([], {}), True, 'from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw\n'), (182, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['key', 'value'], {}), True, 'import tensorflow as tf\n'), (202, 'utils.multi_gpu_wrapper.MultiGpuWrapper.DistributedOptimizer', 'mgw.DistributedOptimizer', (['optimizer_base'], {}), True, 'from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw\n'), (222, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (226, 'utils.multi_gpu_wrapper.MultiGpuWrapper.local_rank', 'mgw.local_rank', ([], {}), True, 'from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw\n'), (279, 'tensorflow.where', 'tf.where', (['(mask > 0.5)', 'var', 'var_bkup'], {}), True, 'import tensorflow as tf\n'), (280, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[var_bkup_update_op]'], {}), True, 'import tensorflow as tf\n'), (283, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[mask_update_op]'], {}), True, 'import tensorflow as tf\n'), (116, 'timeit.default_timer', 'timer', ([], {}), True, 'from timeit import default_timer as timer\n'), (149, 'numpy.mean', 'np.mean', (['eval_rslts[:, (idx)]'], {}), True, 'import numpy as np\n'), (274, 'tensorflow.ones', 'tf.ones', (['var.shape'], {}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.abs', 'tf.abs', (['var_bkup'], {}), True, 'import tensorflow as tf\n'), (88, 'os.listdir', 'os.listdir', (['"""./models"""'], {}), False, 'import os\n'), (282, 'tensorflow.abs', 'tf.abs', (['var_bkup'], {}), True, 'import tensorflow as tf\n')]
ryanbrand/mil
6524047febe35fa59c356794f1649946332c4e7f
""" Utility functions for tensorflow. """ import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import array_ops import numpy as np def safe_get(name, *args, **kwargs): """ Same as tf.get_variable, except flips on reuse_variables automatically """ try: return tf.get_variable(name, *args, **kwargs) except ValueError: tf.get_variable_scope().reuse_variables() return tf.get_variable(name, *args, **kwargs) def init_weights(shape, name=None): shape = tuple(shape) weights = np.random.normal(scale=0.01, size=shape).astype('f') return safe_get(name, list(shape), initializer=tf.constant_initializer(weights), dtype=tf.float32) def init_bias(shape, name=None): return safe_get(name, initializer=tf.zeros(shape, dtype=tf.float32)) def init_fc_weights_xavier(shape, name=None): fc_initializer = tf.contrib.layers.xavier_initializer(dtype=tf.float32) return safe_get(name, list(shape), initializer=fc_initializer, dtype=tf.float32) def init_conv_weights_xavier(shape, name=None): conv_initializer = tf.contrib.layers.xavier_initializer_conv2d(dtype=tf.float32) return safe_get(name, list(shape), initializer=conv_initializer, dtype=tf.float32) def init_fc_weights_snn(shape, name=None): weights = np.random.normal(scale=np.sqrt(1.0/shape[0]), size=shape).astype('f') return safe_get(name, list(shape), initializer=tf.constant_initializer(weights), dtype=tf.float32) def init_conv_weights_snn(shape, name=None): weights = np.random.normal(scale=np.sqrt(1.0/(shape[0]*shape[1]*shape[2])), size=shape).astype('f') return safe_get(name, list(shape), initializer=tf.constant_initializer(weights), dtype=tf.float32) def batched_matrix_vector_multiply(vector, matrix): """ computes x^T A in mini-batches. """ vector_batch_as_matricies = tf.expand_dims(vector, [1]) mult_result = tf.matmul(vector_batch_as_matricies, matrix) squeezed_result = tf.squeeze(mult_result, [1]) return squeezed_result def euclidean_loss_layer(a, b, multiplier=100.0, use_l1=False, eps=0.01): """ Math: out = (action - mlp_out)'*precision*(action-mlp_out) = (u-uhat)'*A*(u-uhat)""" multiplier = tf.constant(multiplier, dtype='float') #for bc #10000 uP =a*multiplier-b*multiplier if use_l1: return tf.reduce_mean(eps*tf.square(uP) + tf.abs(uP)) return tf.reduce_mean(tf.square(uP)) def conv2d(img, w, b, strides=[1, 1, 1, 1], is_dilated=False): if is_dilated: layer = tf.nn.atrous_conv2d(img, w, rate=2, padding='SAME') + b else: layer = tf.nn.conv2d(img, w, strides=strides, padding='SAME') + b return layer def dropout(layer, keep_prob=0.9, is_training=True, name=None, selu=False): if selu: return dropout_selu(layer, 1.0 - keep_prob, name=name, training=is_training) if is_training: return tf.nn.dropout(layer, keep_prob=keep_prob, name=name) else: return tf.add(layer, 0, name=name) def norm(layer, norm_type='batch_norm', decay=0.9, id=0, is_training=True, activation_fn=tf.nn.relu, prefix='conv_'): if norm_type != 'batch_norm' and norm_type != 'layer_norm': return tf.nn.relu(layer) with tf.variable_scope('norm_layer_%s%d' % (prefix, id)) as vs: if norm_type == 'batch_norm': if is_training: try: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs) # updates_collections=None except ValueError: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None else: layer = tf.contrib.layers.batch_norm(layer, is_training=False, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None elif norm_type == 'layer_norm': # layer_norm # Take activation_fn out to apply lrelu try: layer = activation_fn(tf.contrib.layers.layer_norm(layer, center=True, scale=False, scope=vs)) # updates_collections=None except ValueError: layer = activation_fn(tf.contrib.layers.layer_norm(layer, center=True, scale=False, scope=vs, reuse=True)) elif norm_type == 'selu': layer = selu(layer) else: raise NotImplementedError('Other types of norm not implemented.') return layer class VBN(object): """ Virtual Batch Normalization """ def __init__(self, x, name, epsilon=1e-5): """ x is the reference batch """ assert isinstance(epsilon, float) shape = x.get_shape().as_list() with tf.variable_scope(name) as scope: self.epsilon = epsilon self.name = name self.mean = tf.reduce_mean(x, [0, 1, 2], keep_dims=True) self.mean_sq = tf.reduce_mean(tf.square(x), [0, 1, 2], keep_dims=True) self.batch_size = int(x.get_shape()[0]) assert x is not None assert self.mean is not None assert self.mean_sq is not None out = tf.nn.relu(self._normalize(x, self.mean, self.mean_sq, "reference")) self.reference_output = out def __call__(self, x, update=False): with tf.variable_scope(self.name) as scope: if not update: new_coeff = 1. / (self.batch_size + 1.) old_coeff = 1. - new_coeff new_mean = tf.reduce_mean(x, [1, 2], keep_dims=True) new_mean_sq = tf.reduce_mean(tf.square(x), [1, 2], keep_dims=True) mean = new_coeff * new_mean + old_coeff * self.mean mean_sq = new_coeff * new_mean_sq + old_coeff * self.mean_sq out = tf.nn.relu(self._normalize(x, mean, mean_sq, "live")) # Update the mean and mean_sq when passing the reference data else: self.mean = tf.reduce_mean(x, [0, 1, 2], keep_dims=True) self.mean_sq = tf.reduce_mean(tf.square(x), [0, 1, 2], keep_dims=True) out = tf.nn.relu(self._normalize(x, self.mean, self.mean_sq, "reference")) return out def _normalize(self, x, mean, mean_sq, message): # make sure this is called with a variable scope shape = x.get_shape().as_list() assert len(shape) == 4 self.gamma = safe_get("gamma", [shape[-1]], initializer=tf.random_normal_initializer(1., 0.02)) gamma = tf.reshape(self.gamma, [1, 1, 1, -1]) self.beta = safe_get("beta", [shape[-1]], initializer=tf.constant_initializer(0.)) beta = tf.reshape(self.beta, [1, 1, 1, -1]) assert self.epsilon is not None assert mean_sq is not None assert mean is not None std = tf.sqrt(self.epsilon + mean_sq - tf.square(mean)) out = x - mean out = out / std out = out * gamma out = out + beta return out def max_pool(img, k): return tf.nn.max_pool(img, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Consider stride size when using xavier for fp network def get_xavier_weights(filter_shape, poolsize=(2, 2), name=None): fan_in = np.prod(filter_shape[1:]) fan_out = (filter_shape[0] * np.prod(filter_shape[2:]) // np.prod(poolsize)) low = -4*np.sqrt(6.0/(fan_in + fan_out)) # use 4 for sigmoid, 1 for tanh activation high = 4*np.sqrt(6.0/(fan_in + fan_out)) weights = np.random.uniform(low=low, high=high, size=filter_shape) return safe_get(name, filter_shape, initializer=tf.constant_initializer(weights)) def get_he_weights(filter_shape, name=None): fan_in = np.prod(filter_shape[1:]) stddev = np.sqrt(2.6/fan_in) weights = stddev * np.random.randn(filter_shape[0], filter_shape[1], filter_shape[2], filter_shape[3]) return safe_get(name, filter_shape, initializer=tf.constant_initializer(weights))
[ "tensorflow.get_variable", "numpy.sqrt", "tensorflow.zeros", "tensorflow.nn.max_pool", "numpy.random.randn", "tensorflow.nn.atrous_conv2d", "tensorflow.nn.conv2d", "tensorflow.squeeze", "tensorflow.add", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.square", "tensorflow.random_normal_initializer", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.contrib.layers.batch_norm", "tensorflow.contrib.layers.xavier_initializer_conv2d", "tensorflow.nn.relu", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.contrib.layers.layer_norm", "numpy.random.normal", "numpy.prod", "tensorflow.variable_scope", "numpy.random.uniform", "tensorflow.get_variable_scope", "tensorflow.abs" ]
tf_utils.py
[(29, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.expand_dims', 'tf.expand_dims', (['vector', '[1]'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.matmul', 'tf.matmul', (['vector_batch_as_matricies', 'matrix'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.squeeze', 'tf.squeeze', (['mult_result', '[1]'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.constant', 'tf.constant', (['multiplier'], {'dtype': '"""float"""'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['img'], {'ksize': '[1, k, k, 1]', 'strides': '[1, k, k, 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (172, 'numpy.prod', 'np.prod', (['filter_shape[1:]'], {}), True, 'import numpy as np\n'), (178, 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'low', 'high': 'high', 'size': 'filter_shape'}), True, 'import numpy as np\n'), (182, 'numpy.prod', 'np.prod', (['filter_shape[1:]'], {}), True, 'import numpy as np\n'), (184, 'numpy.sqrt', 'np.sqrt', (['(2.6 / fan_in)'], {}), True, 'import numpy as np\n'), (15, 'tensorflow.get_variable', 'tf.get_variable', (['name', '*args'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.square', 'tf.square', (['uP'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['layer'], {'keep_prob': 'keep_prob', 'name': 'name'}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.add', 'tf.add', (['layer', '(0)'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.nn.relu', 'tf.nn.relu', (['layer'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.variable_scope', 'tf.variable_scope', (["('norm_layer_%s%d' % (prefix, id))"], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.reshape', 'tf.reshape', (['self.gamma', '[1, 1, 1, -1]'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.reshape', 'tf.reshape', (['self.beta', '[1, 1, 1, -1]'], {}), True, 'import tensorflow as tf\n'), (174, 'numpy.prod', 'np.prod', (['poolsize'], {}), True, 'import numpy as np\n'), (176, 'numpy.sqrt', 'np.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), True, 'import numpy as np\n'), (177, 'numpy.sqrt', 'np.sqrt', (['(6.0 / (fan_in + fan_out))'], {}), True, 'import numpy as np\n'), (185, 'numpy.random.randn', 'np.random.randn', (['filter_shape[0]', 'filter_shape[1]', 'filter_shape[2]', 'filter_shape[3]'], {}), True, 'import numpy as np\n'), (18, 'tensorflow.get_variable', 'tf.get_variable', (['name', '*args'], {}), True, 'import tensorflow as tf\n'), (22, 'numpy.random.normal', 'np.random.normal', ([], {'scale': '(0.01)', 'size': 'shape'}), True, 'import numpy as np\n'), (23, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['weights'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.zeros', 'tf.zeros', (['shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['weights'], {}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['weights'], {}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.nn.atrous_conv2d', 'tf.nn.atrous_conv2d', (['img', 'w'], {'rate': '(2)', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['img', 'w'], {'strides': 'strides', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x', '[0, 1, 2]'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.variable_scope', 'tf.variable_scope', (['self.name'], {}), True, 'import tensorflow as tf\n'), (173, 'numpy.prod', 'np.prod', (['filter_shape[2:]'], {}), True, 'import numpy as np\n'), (179, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['weights'], {}), True, 'import tensorflow as tf\n'), (186, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['weights'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.abs', 'tf.abs', (['uP'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['layer'], {'is_training': '(False)', 'center': '(True)', 'scale': '(False)', 'decay': 'decay', 'activation_fn': 'activation_fn', 'updates_collections': 'None', 'scope': 'vs', 'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.square', 'tf.square', (['x'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x', '[1, 2]'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['x', '[0, 1, 2]'], {'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(1.0)', '(0.02)'], {}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.square', 'tf.square', (['mean'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (37, 'numpy.sqrt', 'np.sqrt', (['(1.0 / shape[0])'], {}), True, 'import numpy as np\n'), (41, 'numpy.sqrt', 'np.sqrt', (['(1.0 / (shape[0] * shape[1] * shape[2]))'], {}), True, 'import numpy as np\n'), (57, 'tensorflow.square', 'tf.square', (['uP'], {}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['layer'], {'is_training': '(True)', 'center': '(True)', 'scale': '(False)', 'decay': 'decay', 'activation_fn': 'activation_fn', 'updates_collections': 'None', 'scope': 'vs'}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.square', 'tf.square', (['x'], {}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.square', 'tf.square', (['x'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['layer'], {'is_training': '(True)', 'center': '(True)', 'scale': '(False)', 'decay': 'decay', 'activation_fn': 'activation_fn', 'updates_collections': 'None', 'scope': 'vs', 'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.layers.layer_norm', 'tf.contrib.layers.layer_norm', (['layer'], {'center': '(True)', 'scale': '(False)', 'scope': 'vs'}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.contrib.layers.layer_norm', 'tf.contrib.layers.layer_norm', (['layer'], {'center': '(True)', 'scale': '(False)', 'scope': 'vs', 'reuse': '(True)'}), True, 'import tensorflow as tf\n')]
KarlKangYu/dcnn-pos-deps-head
2ac6c16ea217517e4af79a84a4b0e223b2f62cd0
import tensorflow as tf import numpy as np import math # weights initializers he_normal = tf.contrib.keras.initializers.he_normal() #he_normal = tf.contrib.layers.variance_scaling_initializer() regularizer = tf.contrib.layers.l2_regularizer(1e-4) def Convolutional_Block(inputs, shortcut, num_filters, name, is_training): print("-"*20) print("Convolutional Block", str(num_filters), name) print("-"*20) with tf.variable_scope("conv_block_" + str(num_filters) + "_" + name): for i in range(2): with tf.variable_scope("conv1d_%s" % str(i)): filter_shape = [3, inputs.get_shape()[2], num_filters] W = tf.get_variable(name='W', shape=filter_shape, initializer=he_normal, regularizer=regularizer) inputs = tf.nn.conv1d(inputs, W, stride=1, padding="SAME") inputs = tf.layers.batch_normalization(inputs=inputs, momentum=0.997, epsilon=1e-5, center=True, scale=True, training=is_training) inputs = tf.nn.relu(inputs) print("Conv1D:", inputs.get_shape()) print("-"*20) if shortcut is not None: print("-"*5) print("Optional Shortcut:", shortcut.get_shape()) print("-"*5) return inputs + shortcut return inputs # Three types of downsampling methods described by paper def downsampling(inputs, downsampling_type, name, optional_shortcut=False, shortcut=None): # k-maxpooling if downsampling_type=='k-maxpool': k = math.ceil(int(inputs.get_shape()[1]) / 2) pool = tf.nn.top_k(tf.transpose(inputs, [0,2,1]), k=k, name=name, sorted=False)[0] pool = tf.transpose(pool, [0,2,1]) # Linear elif downsampling_type=='linear': pool = tf.layers.conv1d(inputs=inputs, filters=inputs.get_shape()[2], kernel_size=3, strides=2, padding='same', use_bias=False) # Maxpooling else: pool = tf.layers.max_pooling1d(inputs=inputs, pool_size=3, strides=2, padding='same', name=name) if optional_shortcut: shortcut = tf.layers.conv1d(inputs=shortcut, filters=shortcut.get_shape()[2], kernel_size=1, strides=2, padding='same', use_bias=False) print("-"*5) print("Optional Downsampling Shortcut:", shortcut.get_shape()) print("-"*5) pool += shortcut pool = fixed_padding(inputs=pool) return tf.layers.conv1d(inputs=pool, filters=pool.get_shape()[2]*2, kernel_size=1, strides=1, padding='valid', use_bias=False) def fixed_padding(inputs, kernel_size=3): pad_total = kernel_size - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [0, 0]]) return padded_inputs class VDCNN(): def __init__(self, num_classes, sequence_max_length=20, num_quantized_chars=50000, tags_vocab_size=44, deps_vocab_size=47, embedding_size=300, depth=9, downsampling_type='maxpool', use_he_uniform=True, optional_shortcut=False): # Depth to No. Layers if depth == 9: num_layers = [2,2,2,2] elif depth == 5: num_layers = [1,1,1,1] elif depth == 17: num_layers = [4,4,4,4] elif depth == 29: num_layers = [10,10,4,4] elif depth == 49: num_layers = [16,16,10,6] else: raise ValueError('depth=%g is a not a valid setting!' % depth) # input tensors self.input_x = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_x") self.input_tags = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_tags") self.input_deps = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_dependency") self.input_head = tf.placeholder(tf.int32, [None, sequence_max_length], name="input_head") self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y") self.is_training = tf.placeholder(tf.bool) initializer = tf.contrib.layers.variance_scaling_initializer() # Embedding Lookup 16 with tf.device('/cpu:0'), tf.name_scope("embedding"): if use_he_uniform: self.embedding_W = tf.get_variable(name='lookup_W', shape=[num_quantized_chars, embedding_size], initializer=tf.contrib.layers.variance_scaling_initializer()) else: self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name="embedding_W") self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x) embedded_text_expand = tf.expand_dims(self.embedded_characters, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_tags"): W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer) embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags) embedded_tags_expanded = tf.expand_dims(embedded_tags, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_deps"): W_deps = tf.get_variable("embed_W_deps", [deps_vocab_size, embedding_size], initializer=initializer) embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps) embedded_deps_expanded = tf.expand_dims(embedded_deps, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_head"): W_head = tf.get_variable("embed_W_head", [num_quantized_chars, embedding_size], initializer=initializer) embedded_head = tf.nn.embedding_lookup(W_head, self.input_head) embedded_head_expanded = tf.expand_dims(embedded_head, -1) cnn_inputs = tf.concat( [embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded, embedded_head_expanded], -1) print("-" * 20) print("Embedded Lookup:", cnn_inputs.get_shape()) print("-" * 20) self.layers = [] # Temp(First) Conv Layer with tf.variable_scope("temp_conv") as scope: filter_shape = [3, embedding_size, 4, 64] W = tf.get_variable(name='W_1', shape=filter_shape, initializer=he_normal, regularizer=regularizer) paddings = [[0, 0], [1, 1], [0, 0], [0, 0]] cnn_inputs = tf.pad(cnn_inputs, paddings, "CONSTANT") #print("cnn_inputs shape:", cnn_inputs.shape) inputs = tf.nn.conv2d(cnn_inputs, W, strides=[1, 1, 1, 1], padding="VALID", name="first_conv") inputs = tf.layers.batch_normalization(inputs, axis=-1, training=self.is_training) inputs = tf.nn.relu(inputs, name="first_relu") #print("temp cnn output shape:", inputs.shape) inputs = tf.squeeze(inputs, axis=2) #print("squeeze shape", inputs.shape) #inputs = tf.nn.relu(inputs) print("Temp Conv", inputs.get_shape()) self.layers.append(inputs) # Conv Block 64 for i in range(num_layers[0]): if i < num_layers[0] - 1 and optional_shortcut: shortcut = self.layers[-1] else: shortcut = None conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=64, is_training=self.is_training, name=str(i+1)) self.layers.append(conv_block) pool1 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool1', optional_shortcut=optional_shortcut, shortcut=self.layers[-2]) self.layers.append(pool1) print("Pooling:", pool1.get_shape()) # Conv Block 128 for i in range(num_layers[1]): if i < num_layers[1] - 1 and optional_shortcut: shortcut = self.layers[-1] else: shortcut = None conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=128, is_training=self.is_training, name=str(i+1)) self.layers.append(conv_block) pool2 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool2', optional_shortcut=optional_shortcut, shortcut=self.layers[-2]) self.layers.append(pool2) print("Pooling:", pool2.get_shape()) # Conv Block 256 for i in range(num_layers[2]): if i < num_layers[2] - 1 and optional_shortcut: shortcut = self.layers[-1] else: shortcut = None conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=256, is_training=self.is_training, name=str(i+1)) self.layers.append(conv_block) pool3 = downsampling(self.layers[-1], downsampling_type=downsampling_type, name='pool3', optional_shortcut=optional_shortcut, shortcut=self.layers[-2]) self.layers.append(pool3) print("Pooling:", pool3.get_shape()) # Conv Block 512 for i in range(num_layers[3]): if i < num_layers[3] - 1 and optional_shortcut: shortcut = self.layers[-1] else: shortcut = None conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=512, is_training=self.is_training, name=str(i+1)) self.layers.append(conv_block) # Extract 8 most features as mentioned in paper self.k_pooled = tf.nn.top_k(tf.transpose(self.layers[-1], [0,2,1]), k=8, name='k_pool', sorted=False)[0] print("8-maxpooling:", self.k_pooled.get_shape()) self.flatten = tf.reshape(self.k_pooled, (-1, 512*8)) # fc1 with tf.variable_scope('fc1'): w = tf.get_variable('w', [self.flatten.get_shape()[1], 2048], initializer=he_normal, regularizer=regularizer) b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0)) out = tf.matmul(self.flatten, w) + b self.fc1 = tf.nn.relu(out) # fc2 with tf.variable_scope('fc2'): w = tf.get_variable('w', [self.fc1.get_shape()[1], 2048], initializer=he_normal, regularizer=regularizer) b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0)) out = tf.matmul(self.fc1, w) + b self.fc2 = tf.nn.relu(out) # fc3 with tf.variable_scope('fc3'): w = tf.get_variable('w', [self.fc2.get_shape()[1], num_classes], initializer=initializer, regularizer=regularizer) b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0)) self.fc3 = tf.matmul(self.fc2, w) + b # Calculate Mean cross-entropy loss with tf.name_scope("loss"): self.predictions = tf.argmax(self.fc3, 1, name="predictions") losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.fc3, labels=self.input_y) regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) self.loss = tf.reduce_mean(losses) + sum(regularization_losses) # Accuracy with tf.name_scope("accuracy"): correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
[ "tensorflow.device", "tensorflow.get_variable", "tensorflow.concat", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.contrib.keras.initializers.he_normal", "tensorflow.cast", "tensorflow.pad", "tensorflow.nn.conv1d", "tensorflow.nn.conv2d", "tensorflow.layers.max_pooling1d", "tensorflow.layers.batch_normalization", "tensorflow.contrib.layers.variance_scaling_initializer", "tensorflow.get_collection", "tensorflow.squeeze", "tensorflow.name_scope", "tensorflow.argmax", "tensorflow.matmul", "tensorflow.placeholder", "tensorflow.nn.embedding_lookup", "tensorflow.nn.relu", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.variable_scope", "tensorflow.random_uniform" ]
vdcnn.py
[(6, 'tensorflow.contrib.keras.initializers.he_normal', 'tf.contrib.keras.initializers.he_normal', ([], {}), True, 'import tensorflow as tf\n'), (8, 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['(0.0001)'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.pad', 'tf.pad', (['inputs', '[[0, 0], [pad_beg, pad_end], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.transpose', 'tf.transpose', (['pool', '[0, 2, 1]'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, sequence_max_length]'], {'name': '"""input_x"""'}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, sequence_max_length]'], {'name': '"""input_tags"""'}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, sequence_max_length]'], {'name': '"""input_dependency"""'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, sequence_max_length]'], {'name': '"""input_head"""'}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_classes]'], {'name': '"""input_y"""'}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.concat', 'tf.concat', (['[embedded_text_expand, embedded_tags_expanded, embedded_deps_expanded,\n embedded_head_expanded]', '(-1)'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.reshape', 'tf.reshape', (['self.k_pooled', '(-1, 512 * 8)'], {}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.layers.max_pooling1d', 'tf.layers.max_pooling1d', ([], {'inputs': 'inputs', 'pool_size': '(3)', 'strides': '(2)', 'padding': '"""same"""', 'name': 'name'}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.name_scope', 'tf.name_scope', (['"""embedding"""'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.embedding_W', 'self.input_x'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.expand_dims', 'tf.expand_dims', (['self.embedded_characters', '(-1)'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.name_scope', 'tf.name_scope', (['"""embedding_tags"""'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.get_variable', 'tf.get_variable', (['"""embed_W_tags"""', '[tags_vocab_size, embedding_size]'], {'initializer': 'initializer'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['W_tags', 'self.input_tags'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.expand_dims', 'tf.expand_dims', (['embedded_tags', '(-1)'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.name_scope', 'tf.name_scope', (['"""embedding_deps"""'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.get_variable', 'tf.get_variable', (['"""embed_W_deps"""', '[deps_vocab_size, embedding_size]'], {'initializer': 'initializer'}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['W_deps', 'self.input_deps'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.expand_dims', 'tf.expand_dims', (['embedded_deps', '(-1)'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.name_scope', 'tf.name_scope', (['"""embedding_head"""'], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.get_variable', 'tf.get_variable', (['"""embed_W_head"""', '[num_quantized_chars, embedding_size]'], {'initializer': 'initializer'}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['W_head', 'self.input_head'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.expand_dims', 'tf.expand_dims', (['embedded_head', '(-1)'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""temp_conv"""'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""W_1"""', 'shape': 'filter_shape', 'initializer': 'he_normal', 'regularizer': 'regularizer'}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.pad', 'tf.pad', (['cnn_inputs', 'paddings', '"""CONSTANT"""'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['cnn_inputs', 'W'], {'strides': '[1, 1, 1, 1]', 'padding': '"""VALID"""', 'name': '"""first_conv"""'}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', (['inputs'], {'axis': '(-1)', 'training': 'self.is_training'}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.nn.relu', 'tf.nn.relu', (['inputs'], {'name': '"""first_relu"""'}), True, 'import tensorflow as tf\n'), (142, 'tensorflow.squeeze', 'tf.squeeze', (['inputs'], {'axis': '(2)'}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fc1"""'], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.nn.relu', 'tf.nn.relu', (['out'], {}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fc2"""'], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.nn.relu', 'tf.nn.relu', (['out'], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fc3"""'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.name_scope', 'tf.name_scope', (['"""loss"""'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.argmax', 'tf.argmax', (['self.fc3', '(1)'], {'name': '"""predictions"""'}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'logits': 'self.fc3', 'labels': 'self.input_y'}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.name_scope', 'tf.name_scope', (['"""accuracy"""'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""W"""', 'shape': 'filter_shape', 'initializer': 'he_normal', 'regularizer': 'regularizer'}), True, 'import tensorflow as tf\n'), (21, 'tensorflow.nn.conv1d', 'tf.nn.conv1d', (['inputs', 'W'], {'stride': '(1)', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (22, 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', ([], {'inputs': 'inputs', 'momentum': '(0.997)', 'epsilon': '(1e-05)', 'center': '(True)', 'scale': '(True)', 'training': 'is_training'}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.nn.relu', 'tf.nn.relu', (['inputs'], {}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.transpose', 'tf.transpose', (['inputs', '[0, 2, 1]'], {}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.transpose', 'tf.transpose', (['self.layers[-1]', '[0, 2, 1]'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.matmul', 'tf.matmul', (['self.flatten', 'w'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.matmul', 'tf.matmul', (['self.fc1', 'w'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.matmul', 'tf.matmul', (['self.fc2', 'w'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['losses'], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.argmax', 'tf.argmax', (['self.input_y', '(1)'], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.cast', 'tf.cast', (['correct_predictions', '"""float"""'], {}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.random_uniform', 'tf.random_uniform', (['[num_quantized_chars, embedding_size]', '(-1.0)', '(1.0)'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.contrib.layers.variance_scaling_initializer', 'tf.contrib.layers.variance_scaling_initializer', ([], {}), True, 'import tensorflow as tf\n')]
Con-Mi/lambda-packs
b23a8464abdd88050b83310e1d0e99c54dac28ab
"""Python wrappers around Brain. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections from google.protobuf import text_format as _text_format from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 # Needed to trigger the call to _set_call_cpp_shape_fn. from tensorflow.python.framework import common_shapes as _common_shapes from tensorflow.python.framework import op_def_registry as _op_def_registry from tensorflow.python.framework import ops as _ops from tensorflow.python.framework import op_def_library as _op_def_library _graph_def_version_outputs = ["version"] def graph_def_version(name=None): r"""TODO: add doc. Args: name: A name for the operation (optional). Returns: A `Tensor` of type `int32`. """ result = _op_def_lib.apply_op("GraphDefVersion", name=name) return result _ops.RegisterShape("GraphDefVersion")(None) _kernel_label_outputs = ["result"] def kernel_label(name=None): r"""TODO: add doc. Args: name: A name for the operation (optional). Returns: A `Tensor` of type `string`. """ result = _op_def_lib.apply_op("KernelLabel", name=name) return result _ops.RegisterShape("KernelLabel")(None) _old_outputs = [""] def old(name=None): r"""TODO: add doc. Args: name: A name for the operation (optional). Returns: The created Operation. """ result = _op_def_lib.apply_op("Old", name=name) return result _ops.RegisterShape("Old")(None) _resource_create_op_outputs = [""] def resource_create_op(resource, name=None): r"""TODO: add doc. Args: resource: A `Tensor` of type `resource`. name: A name for the operation (optional). Returns: The created Operation. """ result = _op_def_lib.apply_op("ResourceCreateOp", resource=resource, name=name) return result _ops.RegisterShape("ResourceCreateOp")(None) _resource_initialized_op_outputs = ["initialized"] def resource_initialized_op(resource, name=None): r"""TODO: add doc. Args: resource: A `Tensor` of type `resource`. name: A name for the operation (optional). Returns: A `Tensor` of type `bool`. """ result = _op_def_lib.apply_op("ResourceInitializedOp", resource=resource, name=name) return result _ops.RegisterShape("ResourceInitializedOp")(None) _resource_using_op_outputs = [""] def resource_using_op(resource, name=None): r"""TODO: add doc. Args: resource: A `Tensor` of type `resource`. name: A name for the operation (optional). Returns: The created Operation. """ result = _op_def_lib.apply_op("ResourceUsingOp", resource=resource, name=name) return result _ops.RegisterShape("ResourceUsingOp")(None) _stub_resource_handle_op_outputs = ["resource"] def stub_resource_handle_op(container=None, shared_name=None, name=None): r"""Creates a handle to a StubResource Args: container: An optional `string`. Defaults to `""`. shared_name: An optional `string`. Defaults to `""`. name: A name for the operation (optional). Returns: A `Tensor` of type `resource`. """ result = _op_def_lib.apply_op("StubResourceHandleOp", container=container, shared_name=shared_name, name=name) return result _ops.RegisterShape("StubResourceHandleOp")(None) _test_string_output_outputs = ["output1", "output2"] _TestStringOutputOutput = _collections.namedtuple("TestStringOutput", _test_string_output_outputs) def test_string_output(input, name=None): r"""TODO: add doc. Args: input: A `Tensor` of type `float32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output1, output2). output1: A `Tensor` of type `float32`. output2: A `Tensor` of type `string`. """ result = _op_def_lib.apply_op("TestStringOutput", input=input, name=name) return _TestStringOutputOutput._make(result) _ops.RegisterShape("TestStringOutput")(None) def _InitOpDefLibrary(): op_list = _op_def_pb2.OpList() _text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list) _op_def_registry.register_op_list(op_list) op_def_lib = _op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib _InitOpDefLibrary.op_list_ascii = """op { name: "GraphDefVersion" output_arg { name: "version" type: DT_INT32 } is_stateful: true } op { name: "KernelLabel" output_arg { name: "result" type: DT_STRING } } op { name: "Old" deprecation { version: 8 explanation: "For reasons" } } op { name: "ResourceCreateOp" input_arg { name: "resource" type: DT_RESOURCE } } op { name: "ResourceInitializedOp" input_arg { name: "resource" type: DT_RESOURCE } output_arg { name: "initialized" type: DT_BOOL } } op { name: "ResourceUsingOp" input_arg { name: "resource" type: DT_RESOURCE } } op { name: "StubResourceHandleOp" output_arg { name: "resource" type: DT_RESOURCE } attr { name: "container" type: "string" default_value { s: "" } } attr { name: "shared_name" type: "string" default_value { s: "" } } is_stateful: true } op { name: "TestStringOutput" input_arg { name: "input" type: DT_FLOAT } output_arg { name: "output1" type: DT_FLOAT } output_arg { name: "output2" type: DT_STRING } } """ _op_def_lib = _InitOpDefLibrary()
[ "tensorflow.python.framework.ops.RegisterShape", "tensorflow.python.framework.op_def_registry.register_op_list", "tensorflow.core.framework.op_def_pb2.OpList", "tensorflow.python.framework.op_def_library.OpDefLibrary" ]
Keras_tensorflow/source/tensorflow/python/framework/test_ops.py
[(149, 'collections.namedtuple', '_collections.namedtuple', (['"""TestStringOutput"""', '_test_string_output_outputs'], {}), True, 'import collections as _collections\n'), (34, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""GraphDefVersion"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (51, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""KernelLabel"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (68, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""Old"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (87, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""ResourceCreateOp"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (106, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""ResourceInitializedOp"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (125, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""ResourceUsingOp"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (145, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""StubResourceHandleOp"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (169, 'tensorflow.python.framework.ops.RegisterShape', '_ops.RegisterShape', (['"""TestStringOutput"""'], {}), True, 'from tensorflow.python.framework import ops as _ops\n'), (171, 'tensorflow.core.framework.op_def_pb2.OpList', '_op_def_pb2.OpList', ([], {}), True, 'from tensorflow.core.framework import op_def_pb2 as _op_def_pb2\n'), (172, 'google.protobuf.text_format.Merge', '_text_format.Merge', (['_InitOpDefLibrary.op_list_ascii', 'op_list'], {}), True, 'from google.protobuf import text_format as _text_format\n'), (173, 'tensorflow.python.framework.op_def_registry.register_op_list', '_op_def_registry.register_op_list', (['op_list'], {}), True, 'from tensorflow.python.framework import op_def_registry as _op_def_registry\n'), (174, 'tensorflow.python.framework.op_def_library.OpDefLibrary', '_op_def_library.OpDefLibrary', ([], {}), True, 'from tensorflow.python.framework import op_def_library as _op_def_library\n')]
lemoner20/tensorlayer
69bd591f247b4a67f8968bd29c3660b22dbffae4
import gym, random, time import numpy as np import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import * import matplotlib.pyplot as plt """ Q-Network Q(a, s) - TD Learning, Off-Policy, e-Greedy Exploration (GLIE) Q(S, A) <- Q(S, A) + alpha * (R + lambda * Q(newS, newA) - Q(S, A)) delta_w = R + lambda * Q(newS, newA) See David Silver RL Tutorial Lecture 5 - Q-Learning for more details. EN: https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-0-q-learning-with-tables-and-neural-networks-d195264329d0#.5m3361vlw CN: https://zhuanlan.zhihu.com/p/25710327 Note: Policy Network has been proved to be better than Q-Learning, see tutorial_atari_pong.py """ ## The FrozenLake v0 environment # https://gym.openai.com/envs/FrozenLake-v0 # The agent controls the movement of a character in a grid world. Some tiles of # the grid are walkable, and others lead to the agent falling into the water. # Additionally, the movement direction of the agent is uncertain and only partially # depends on the chosen direction. The agent is rewarded for finding a walkable # path to a goal tile. # SFFF (S: starting point, safe) # FHFH (F: frozen surface, safe) # FFFH (H: hole, fall to your doom) # HFFG (G: goal, where the frisbee is located) # The episode ends when you reach the goal or fall in a hole. You receive a reward # of 1 if you reach the goal, and zero otherwise. env = gym.make('FrozenLake-v0') def to_one_hot(i, n_classes=None): a = np.zeros(n_classes, 'uint8') a[i] = 1 return a render = False # display the game environment running_reward = None tf.reset_default_graph() ## Define Q-network q(a,s) that ouput the rewards of 4 actions by given state, i.e. Action-Value Function. # 4x4 grid can be represented by one-hot vector with 16 integers. inputs = tf.placeholder(shape=[1, 16], dtype=tf.float32) net = InputLayer(inputs, name='observation') net = DenseLayer(net, n_units=4, act=tf.identity, W_init=tf.random_uniform_initializer(0, 0.01), b_init=None, name='q_a_s') y = net.outputs # action-value / rewards of 4 actions predict = tf.argmax(y, 1) # chose action greedily with reward. in Q-Learning, policy is greedy, so we use "max" to select the next action. ## Below we obtain the loss by taking the sum of squares difference between the target and prediction Q values. nextQ = tf.placeholder(shape=[1, 4], dtype=tf.float32) loss = tl.cost.mean_squared_error(nextQ, y, is_mean=False) # tf.reduce_sum(tf.square(nextQ - y)) train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) ## Set learning parameters lambd = .99 # decay factor e = 0.1 # e-Greedy Exploration, the larger the more random num_episodes = 10000 with tf.Session() as sess: tl.layers.initialize_global_variables(sess) for i in range(num_episodes): ## Reset environment and get first new observation episode_time = time.time() s = env.reset() # observation is state, integer 0 ~ 15 rAll = 0 for j in range(99): # step index, maximum step is 99 if render: env.render() ## Choose an action by greedily (with e chance of random action) from the Q-network a, allQ = sess.run([predict, y], feed_dict={inputs : [to_one_hot(s, 16)]}) ## e-Greedy Exploration !!! sample random action if np.random.rand(1) < e: a[0] = env.action_space.sample() ## Get new state and reward from environment s1, r, d, _ = env.step(a[0]) ## Obtain the Q' values by feeding the new state through our network Q1 = sess.run(y, feed_dict={inputs : [to_one_hot(s1, 16)]}) ## Obtain maxQ' and set our target value for chosen action. maxQ1 = np.max(Q1) # in Q-Learning, policy is greedy, so we use "max" to select the next action. targetQ = allQ targetQ[0, a[0]] = r + lambd * maxQ1 ## Train network using target and predicted Q values # it is not real target Q value, it is just an estimation, # but check the Q-Learning update formula: # Q'(s,a) <- Q(s,a) + alpha(r + lambd * maxQ(s',a') - Q(s, a)) # minimizing |r + lambd * maxQ(s',a') - Q(s, a)|^2 equal to force # Q'(s,a) ≈ Q(s,a) _ = sess.run(train_op, {inputs : [to_one_hot(s, 16)], nextQ : targetQ}) rAll += r s = s1 ## Reduce chance of random action if an episode is done. if d == True: e = 1./((i/50) + 10) # reduce e, GLIE: Greey in the limit with infinite Exploration break ## Note that, the rewards here with random action running_reward = rAll if running_reward is None else running_reward * 0.99 + rAll * 0.01 print("Episode [%d/%d] sum reward:%f running reward:%f took:%.5fs %s" % (i, num_episodes, rAll, running_reward, time.time()-episode_time, '' if rAll == 0 else ' !!!!!!!!'))
[ "tensorflow.random_uniform_initializer", "tensorflow.placeholder", "numpy.max", "tensorflow.reset_default_graph", "tensorflow.train.GradientDescentOptimizer", "numpy.random.rand", "tensorflow.Session", "tensorflow.argmax", "numpy.zeros" ]
example/tutorial_frozenlake_dqn.py
[(33, 'gym.make', 'gym.make', (['"""FrozenLake-v0"""'], {}), False, 'import gym, random, time\n'), (43, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[1, 16]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '[1, 4]', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (55, 'tensorlayer.cost.mean_squared_error', 'tl.cost.mean_squared_error', (['nextQ', 'y'], {'is_mean': '(False)'}), True, 'import tensorlayer as tl\n'), (36, 'numpy.zeros', 'np.zeros', (['n_classes', '"""uint8"""'], {}), True, 'import numpy as np\n'), (62, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (63, 'tensorlayer.layers.initialize_global_variables', 'tl.layers.initialize_global_variables', (['sess'], {}), True, 'import tensorlayer as tl\n'), (49, 'tensorflow.random_uniform_initializer', 'tf.random_uniform_initializer', (['(0)', '(0.01)'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.1)'}), True, 'import tensorflow as tf\n'), (66, 'time.time', 'time.time', ([], {}), False, 'import gym, random, time\n'), (81, 'numpy.max', 'np.max', (['Q1'], {}), True, 'import numpy as np\n'), (74, 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), True, 'import numpy as np\n'), (101, 'time.time', 'time.time', ([], {}), False, 'import gym, random, time\n')]
OsbornHu/tensorflow-ml
56c3051e7085a919a603481709b63e4a6614192a
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- # Author: NetworkRanger # Date: 2018/12/22 下午4:06 # 10.3 TensorFlow的并发执行 # 1. 为了能够找到TensorFlow的什么操作正在使用什么设备,我们在计算图会话中传入一个config参数,将log_device_placement设为True。当我们在命令行运行脚本时,会看到指定设备输出 import tensorflow as tf sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) a = tf.constant_initializer([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) # Runs the op. print(sess.run(c)) # 2. 从控制台运行下面的命令 """ $ python3 using_multpile_devices.py Device mapping: no known devices. I tensorflow/core/common_runtime/direct_session.cc:175] Device mapping: MatMul: /job:localhost/replica:0/task:0/cpu:0 b: /job:localhost/replica:0/task:0/cpu:0 I tensorflow/core/common_runtime/simple_placer.cc:818] b: /job:localhost/replica:0/task:0/cpu:0 I tensorflow/core/common_runtime/simple_placer.cc:818] a: /job:localhost/replica:0/task:0/cpu:0 [[22. 28.] [49. 64.] """ # 3. 有时,我们希望搞清楚TensorFlow正在使用的设备。当加载先前保存过的模型,并且该模型在计算图中已分配固定设备时,服务器可提供不同的设备给计算图使用。实现该功能只需在config设置软设备 config = tf.ConfigProto() config.allow_soft_placement = True sess_soft = tf.Session(config=config) # 4. 当使用CPU时,TensorFlow默认占据大部分CPU内存。虽然这也是时常期望的,但是我们能谨慎分配GPU内存。当TensorFlow一直不释放GPU内存时,如有必要,我们可以设置GPU内存增长选项让GPU内存分配缓慢增大到最大限制 config.gpu_options.allow_growth = True sess_grow = tf.Session(config=config) # 5. 如果希望限制死TensorFlow使用GPU内存的百分比,可以使用config设置per_process_gpu_memory_fraction config.gpu_options.per_process_gpu_memory_fraction = 0.4 sess_limited = tf.Session(config=config) # 6. 有时,我们希望代码健壮到可以决定运行多少GPU合适。TensorFlow有内建函数可以探测到。如果我们期望代码在GPU内存合适时利用GPU计算能力,并分配指定操作给GPU,那么该功能是有益的 if tf.test.is_built_with_cuda(): pass # 7. 我们希望分配指定操作给GPU。下面是一个示例代码,做了一些简单的计算,并将它们分配给主CPU和两个副GPU with tf.device('/cpu:0'): a = tf.constant([1.0, 3.0, 5.0], shape=[1,3]) b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1]) with tf.device('/gpu:0'): c = tf.matmul(a,b) c = tf.reshape(c, [-1]) with tf.device('/gpu:1'): d = tf.matmul(b, a) flat_d = tf.reshape(d, [-1]) combined = tf.multiply(c, flat_d) print(sess.run(combined))
[ "tensorflow.matmul", "tensorflow.device", "tensorflow.constant", "tensorflow.multiply", "tensorflow.test.is_built_with_cuda", "tensorflow.reshape", "tensorflow.constant_initializer", "tensorflow.ConfigProto", "tensorflow.Session" ]
chapter10/demo_10.3.py
[(12, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {'shape': '[2, 3]', 'name': '"""a"""'}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.constant', 'tf.constant', (['[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]'], {'shape': '[3, 2]', 'name': '"""b"""'}), True, 'import tensorflow as tf\n'), (14, 'tensorflow.matmul', 'tf.matmul', (['a', 'b'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (42, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.test.is_built_with_cuda', 'tf.test.is_built_with_cuda', ([], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.constant', 'tf.constant', (['[1.0, 3.0, 5.0]'], {'shape': '[1, 3]'}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.constant', 'tf.constant', (['[2.0, 4.0, 6.0]'], {'shape': '[3, 1]'}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.multiply', 'tf.multiply', (['c', 'flat_d'], {}), True, 'import tensorflow as tf\n'), (11, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'log_device_placement': '(True)'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.matmul', 'tf.matmul', (['a', 'b'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.reshape', 'tf.reshape', (['c', '[-1]'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.device', 'tf.device', (['"""/gpu:1"""'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.matmul', 'tf.matmul', (['b', 'a'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.reshape', 'tf.reshape', (['d', '[-1]'], {}), True, 'import tensorflow as tf\n')]
goan15910/ConvDet
6404622cc9d0c8e8b756260c4979b6842b2d0cb0
"""YOLO-v2 model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import joblib from utils import util from easydict import EasyDict as edict import numpy as np import tensorflow as tf from nn_skeleton import ModelSkeleton class YOLO_V2(ModelSkeleton): def __init__(self, mc, gpu_id): with tf.device('/gpu:{}'.format(gpu_id)): ModelSkeleton.__init__(self, mc) self.BN = mc.BN self._add_forward_graph() self._add_yolo_interpret_graph() #self._add_yolo_loss_graph() #self._add_train_graph() #self._add_viz_graph() def _add_forward_graph(self): """Build the VGG-16 model.""" if self.mc.LOAD_PRETRAINED_MODEL: assert tf.gfile.Exists(self.mc.PRETRAINED_MODEL_PATH), \ 'Cannot find pretrained model at the given path:' \ ' {}'.format(self.mc.PRETRAINED_MODEL_PATH) self.caffemodel_weight = joblib.load(self.mc.PRETRAINED_MODEL_PATH) with tf.variable_scope('darknet19') as scope: conv1 = self._conv_layer( 'conv1', self.image_input, filters=32, size=3, stride=1, bn=self.BN, act='lrelu', freeze=True) pool1 = self._pooling_layer( 'pool1', conv1, size=2, stride=2) conv2 = self._conv_layer( 'conv2', pool1, filters=64, size=3, stride=1, bn=self.BN, act='lrelu', freeze=True) pool2 = self._pooling_layer( 'pool2', conv2, size=2, stride=2) conv3 = self._conv_layer( 'conv3', pool2, filters=128, size=3, stride=1, bn=self.BN, act='lrelu') conv4 = self._conv_layer( 'conv4', conv3, filters=64, size=1, stride=1, bn=self.BN, act='lrelu') conv5 = self._conv_layer( 'conv5', conv4, filters=128, size=3, stride=1, bn=self.BN, act='lrelu') pool3 = self._pooling_layer( 'pool3', conv5, size=2, stride=2) conv6 = self._conv_layer( 'conv6', pool3, filters=256, size=3, stride=1, bn=self.BN, act='lrelu') conv7 = self._conv_layer( 'conv7', conv6, filters=128, size=1, stride=1, bn=self.BN, act='lrelu') conv8 = self._conv_layer( 'conv8', conv7, filters=256, size=3, stride=1, bn=self.BN, act='lrelu') pool4 = self._pooling_layer( 'pool4', conv8, size=2, stride=2) conv9 = self._conv_layer( 'conv9', pool4, filters=512, size=3, stride=1, bn=self.BN, act='lrelu') conv10 = self._conv_layer( 'conv10', conv9, filters=256, size=1, stride=1, bn=self.BN, act='lrelu') conv11 = self._conv_layer( 'conv11', conv10, filters=512, size=3, stride=1, bn=self.BN, act='lrelu') conv12 = self._conv_layer( 'conv12', conv11, filters=256, size=1, stride=1, bn=self.BN, act='lrelu') conv13 = self._conv_layer( 'conv13', conv12, filters=512, size=3, stride=1, bn=self.BN, act='lrelu') pool5 = self._pooling_layer( 'pool5', conv13, size=2, stride=2) conv14 = self._conv_layer( 'conv14', pool5, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') conv15 = self._conv_layer( 'conv15', conv14, filters=512, size=1, stride=1, bn=self.BN, act='lrelu') conv16 = self._conv_layer( 'conv16', conv15, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') conv17 = self._conv_layer( 'conv17', conv16, filters=512, size=1, stride=1, bn=self.BN, act='lrelu') conv18 = self._conv_layer( 'conv18', conv17, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') with tf.variable_scope('detector') as scope: conv19 = self._conv_layer( 'conv19', conv18, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') conv20 = self._conv_layer( 'conv20', conv19, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') reorg20 = self._reorg_layer('reorg20', conv13, stride=2) concat20 = self._concat_layer('concat20', conv20, reorg20) conv21 = self._conv_layer( 'conv21', concat20, filters=1024, size=3, stride=1, bn=self.BN, act='lrelu') num_output = self.mc.ANCHOR_PER_GRID * (self.mc.CLASSES + 1 + 4) self.preds = self._conv_layer( 'conv22', conv21, filters=num_output, size=1, stride=1, padding='SAME', xavier=False, act=None, stddev=0.0001) self.conv13 = conv13 self.conv20 = conv20 self.reorg20 = reorg20 self.concat20 = concat20
[ "tensorflow.gfile.Exists", "tensorflow.variable_scope" ]
src/nets/yolo_v2.py
[(22, 'nn_skeleton.ModelSkeleton.__init__', 'ModelSkeleton.__init__', (['self', 'mc'], {}), False, 'from nn_skeleton import ModelSkeleton\n'), (35, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['self.mc.PRETRAINED_MODEL_PATH'], {}), True, 'import tensorflow as tf\n'), (38, 'joblib.load', 'joblib.load', (['self.mc.PRETRAINED_MODEL_PATH'], {}), False, 'import joblib\n'), (40, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""darknet19"""'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""detector"""'], {}), True, 'import tensorflow as tf\n')]
Siddhant085/tensorflow
6f6161a0110d99b2655efc9d933b753dadadbc38
# 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 GBDT estimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile from tensorflow.contrib.boosted_trees.estimator_batch import estimator from tensorflow.contrib.boosted_trees.proto import learner_pb2 from tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.python.estimator.canned import head as head_lib from tensorflow.python.feature_column import feature_column_lib as core_feature_column from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.ops.losses import losses from tensorflow.python.platform import gfile from tensorflow.python.platform import googletest def _train_input_fn(): features = {"x": constant_op.constant([[2.], [1.], [1.]])} label = constant_op.constant([[1], [0], [0]], dtype=dtypes.int32) return features, label def _ranking_train_input_fn(): features = { "a.f1": constant_op.constant([[3.], [0.3], [1.]]), "a.f2": constant_op.constant([[0.1], [3.], [1.]]), "b.f1": constant_op.constant([[13.], [0.4], [5.]]), "b.f2": constant_op.constant([[1.], [3.], [0.01]]), } label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32) return features, label def _eval_input_fn(): features = {"x": constant_op.constant([[1.], [2.], [2.]])} label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32) return features, label def _infer_ranking_train_input_fn(): features = { "f1": constant_op.constant([[3.], [2], [1.]]), "f2": constant_op.constant([[0.1], [3.], [1.]]) } return features, None class BoostedTreeEstimatorTest(test_util.TensorFlowTestCase): def setUp(self): self._export_dir_base = tempfile.mkdtemp() + "export/" gfile.MkDir(self._export_dir_base) def testFitAndEvaluateDontThrowException(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[contrib_feature_column.real_valued_column("x")]) classifier.fit(input_fn=_train_input_fn, steps=15) classifier.evaluate(input_fn=_eval_input_fn, steps=1) classifier.export(self._export_dir_base) def testThatLeafIndexIsInPredictions(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[contrib_feature_column.real_valued_column("x")], output_leaf_index=True) classifier.fit(input_fn=_train_input_fn, steps=15) result_iter = classifier.predict(input_fn=_eval_input_fn) for prediction_dict in result_iter: self.assertTrue("leaf_index" in prediction_dict) self.assertTrue("logits" in prediction_dict) def testFitAndEvaluateDontThrowExceptionWithCoreForEstimator(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() # Use core head head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( loss_reduction=losses.Reduction.SUM_OVER_BATCH_SIZE) model = estimator.GradientBoostedDecisionTreeEstimator( head=head_fn, learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[core_feature_column.numeric_column("x")], use_core_libs=True) model.fit(input_fn=_train_input_fn, steps=15) model.evaluate(input_fn=_eval_input_fn, steps=1) model.export(self._export_dir_base) def testFitAndEvaluateDontThrowExceptionWithCoreForClassifier(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[core_feature_column.numeric_column("x")], use_core_libs=True) classifier.fit(input_fn=_train_input_fn, steps=15) classifier.evaluate(input_fn=_eval_input_fn, steps=1) classifier.export(self._export_dir_base) def testFitAndEvaluateDontThrowExceptionWithCoreForRegressor(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() regressor = estimator.GradientBoostedDecisionTreeRegressor( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[core_feature_column.numeric_column("x")], use_core_libs=True) regressor.fit(input_fn=_train_input_fn, steps=15) regressor.evaluate(input_fn=_eval_input_fn, steps=1) regressor.export(self._export_dir_base) def testRankingDontThrowExceptionForForEstimator(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS) model = estimator.GradientBoostedDecisionTreeRanker( head=head_fn, learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, use_core_libs=True, feature_columns=[ core_feature_column.numeric_column("f1"), core_feature_column.numeric_column("f2") ], ranking_model_pair_keys=("a", "b")) model.fit(input_fn=_ranking_train_input_fn, steps=1000) model.evaluate(input_fn=_ranking_train_input_fn, steps=1) model.predict(input_fn=_infer_ranking_train_input_fn) class CoreGradientBoostedDecisionTreeEstimator(test_util.TensorFlowTestCase): def testTrainEvaluateInferDoesNotThrowError(self): head_fn = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( loss_reduction=losses.Reduction.SUM_OVER_NONZERO_WEIGHTS) learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() est = estimator.CoreGradientBoostedDecisionTreeEstimator( head=head_fn, learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[core_feature_column.numeric_column("x")]) # Train for a few steps. est.train(input_fn=_train_input_fn, steps=1000) est.evaluate(input_fn=_eval_input_fn, steps=1) est.predict(input_fn=_eval_input_fn) if __name__ == "__main__": googletest.main()
[ "tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss", "tensorflow.python.platform.gfile.MkDir", "tensorflow.python.feature_column.feature_column_lib.numeric_column", "tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig", "tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig", "tensorflow.python.platform.googletest.main", "tensorflow.contrib.layers.python.layers.feature_column.real_valued_column", "tensorflow.python.framework.constant_op.constant" ]
tensorflow/contrib/boosted_trees/estimator_batch/estimator_test.py
[(36, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[1], [0], [0]]'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import constant_op\n'), (47, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0], [0], [1]]'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import constant_op\n'), (53, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0], [1], [1]]'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import constant_op\n'), (234, 'tensorflow.python.platform.googletest.main', 'googletest.main', ([], {}), False, 'from tensorflow.python.platform import googletest\n'), (35, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[2.0], [1.0], [1.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (42, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[3.0], [0.3], [1.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (43, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0.1], [3.0], [1.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (44, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[13.0], [0.4], [5.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (45, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[1.0], [3.0], [0.01]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (52, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[1.0], [2.0], [2.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (59, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[3.0], [2], [1.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (60, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['[[0.1], [3.0], [1.0]]'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (69, 'tensorflow.python.platform.gfile.MkDir', 'gfile.MkDir', (['self._export_dir_base'], {}), False, 'from tensorflow.python.platform import gfile\n'), (72, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (75, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (76, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (91, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (94, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (95, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (113, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (116, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (117, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (120, 'tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss', 'head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss', ([], {'loss_reduction': 'losses.Reduction.SUM_OVER_BATCH_SIZE'}), True, 'from tensorflow.python.estimator.canned import head as head_lib\n'), (138, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (141, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (142, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (158, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (161, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (162, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (178, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (181, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (182, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (184, 'tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss', 'head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss', ([], {'loss_reduction': 'losses.Reduction.SUM_OVER_NONZERO_WEIGHTS'}), True, 'from tensorflow.python.estimator.canned import head as head_lib\n'), (209, 'tensorflow.python.estimator.canned.head._binary_logistic_head_with_sigmoid_cross_entropy_loss', 'head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss', ([], {'loss_reduction': 'losses.Reduction.SUM_OVER_NONZERO_WEIGHTS'}), True, 'from tensorflow.python.estimator.canned import head as head_lib\n'), (212, 'tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig', 'learner_pb2.LearnerConfig', ([], {}), False, 'from tensorflow.contrib.boosted_trees.proto import learner_pb2\n'), (215, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (216, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (68, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (84, 'tensorflow.contrib.layers.python.layers.feature_column.real_valued_column', 'contrib_feature_column.real_valued_column', (['"""x"""'], {}), True, 'from tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column\n'), (103, 'tensorflow.contrib.layers.python.layers.feature_column.real_valued_column', 'contrib_feature_column.real_valued_column', (['"""x"""'], {}), True, 'from tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column\n'), (130, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""x"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n'), (150, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""x"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n'), (170, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""x"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n'), (196, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""f1"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n'), (197, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""f2"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n'), (225, 'tensorflow.python.feature_column.feature_column_lib.numeric_column', 'core_feature_column.numeric_column', (['"""x"""'], {}), True, 'from tensorflow.python.feature_column import feature_column_lib as core_feature_column\n')]
adsar/tensorflow
b4b2575ec4bf7e6da2686505f61b5f16cb9273ab
# Copyright 2015 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. # ============================================================================== """Wrappers for primitive Neural Net (NN) Operations.""" # pylint: disable=invalid-name from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.client import graph_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import common_shapes from tensorflow.python.ops import gen_nn_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops # pylint: disable=wildcard-import from tensorflow.python.ops.gen_nn_ops import * # pylint: enable=wildcard-import # Aliases for some automatically-generated names. local_response_normalization = gen_nn_ops.lrn def conv2d_transpose(value, filter, output_shape, strides, padding="SAME", name=None): """The transpose of `conv2d`. This operation is sometimes called "deconvolution" after (Deconvolutional Networks)[http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf], but is actually the transpose (gradient) of `conv2d` rather than an actual deconvolution. Args: value: A 4-D `Tensor` of type `float` and shape `[batch, height, width, in_channels]`. filter: A 4-D `Tensor` with the same type as `value` and shape `[height, width, output_channels, in_channels]`. `filter`'s `in_channels` dimension must match that of `value`. output_shape: A 1-D `Tensor` representing the output shape of the deconvolution op. strides: A list of ints. The stride of the sliding window for each dimension of the input tensor. padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. name: Optional name for the returned tensor. Returns: A `Tensor` with the same type as `value`. Raises: ValueError: If input/output depth does not match `filter`'s shape, or if padding is other than `'VALID'` or `'SAME'`. """ with ops.op_scope([value, filter, output_shape], name, "conv2d_transpose") as name: value = ops.convert_to_tensor(value, name="value") filter = ops.convert_to_tensor(filter, name="filter") if not value.get_shape()[3].is_compatible_with(filter.get_shape()[3]): raise ValueError( "input channels does not match filter's input channels, " "{} != {}".format(value.get_shape()[3], filter.get_shape()[3])) output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape") if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(4)): raise ValueError("output_shape must have shape (4,), got {}" .format(output_shape_.get_shape())) if isinstance(output_shape, (list, np.ndarray)): # output_shape's shape should be == [4] if reached this point. if not filter.get_shape()[2].is_compatible_with(output_shape[3]): raise ValueError( "output_shape does not match filter's output channels, " "{} != {}".format(output_shape[3], filter.get_shape()[2])) if padding != "VALID" and padding != "SAME": raise ValueError("padding must be either VALID or SAME:" " {}".format(padding)) return gen_nn_ops.conv2d_backprop_input(input_sizes=output_shape_, filter=filter, out_backprop=value, strides=strides, padding=padding, name=name) # pylint: disable=protected-access def bias_add(value, bias, data_format=None, name=None): """Adds `bias` to `value`. This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D. Broadcasting is supported, so `value` may have any number of dimensions. Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the case where both types are quantized. Args: value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, `int16`, `int8`, or `complex64`. bias: A 1-D `Tensor` with size matching the last dimension of `value`. Must be the same type as `value` unless `value` is a quantized type, in which case a different quantized type may be used. data_format: A string. 'NHWC' and 'NCHW" are supported. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `value`. """ with ops.op_scope([value, bias], name, "BiasAdd") as name: value = ops.convert_to_tensor(value, name="input") bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") return gen_nn_ops._bias_add(value, bias, data_format=data_format, name=name) ops.RegisterShape("BiasAdd")(common_shapes.bias_add_shape) ops.RegisterShape("BiasAddGrad")(common_shapes.bias_add_grad_shape) # pylint: disable=protected-access def bias_add_v1(value, bias, name=None): """Adds `bias` to `value`. This is a deprecated version of bias_add and will soon to be removed. This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D. Broadcasting is supported, so `value` may have any number of dimensions. Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the case where both types are quantized. Args: value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, `int16`, `int8`, or `complex64`. bias: A 1-D `Tensor` with size matching the last dimension of `value`. Must be the same type as `value` unless `value` is a quantized type, in which case a different quantized type may be used. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `value`. """ with ops.op_scope([value, bias], name, "BiasAddV1") as name: value = ops.convert_to_tensor(value, name="input") bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") return gen_nn_ops._bias_add_v1(value, bias, name=name) ops.RegisterShape("BiasAddV1")(common_shapes.bias_add_shape) ops.RegisterShape("BiasAddGradV1")(common_shapes.bias_add_grad_shape) def relu6(features, name=None): """Computes Rectified Linear 6: `min(max(features, 0), 6)`. Args: features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`, `int16`, or `int8`. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `features`. """ with ops.op_scope([features], name, "Relu6") as name: features = ops.convert_to_tensor(features, name="features") return gen_nn_ops._relu6(features, name=name) def softmax_cross_entropy_with_logits(logits, labels, name=None): """Computes softmax cross entropy between `logits` and `labels`. Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both. **NOTE:** While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of `labels` is a valid probability distribution. If using exclusive `labels` (wherein one and only one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`. **WARNING:** This op expects unscaled logits, since it performs a `softmax` on `logits` internally for efficiency. Do not call this op with the output of `softmax`, as it will produce incorrect results. `logits` and `labels` must have the same shape `[batch_size, num_classes]` and the same dtype (either `float32` or `float64`). Args: logits: Unscaled log probabilities. labels: Each row `labels[i]` must be a valid probability distribution. name: A name for the operation (optional). Returns: A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the softmax cross entropy loss. """ # The second output tensor contains the gradients. We use it in # _CrossEntropyGrad() in nn_grad but not here. cost, unused_backprop = gen_nn_ops._softmax_cross_entropy_with_logits( logits, labels, name=name) return cost def sparse_softmax_cross_entropy_with_logits(logits, labels, name=None): """Computes sparse softmax cross entropy between `logits` and `labels`. Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both. **NOTE:** For this operation, the probability of a given label is considered exclusive. That is, soft classes are not allowed, and the `labels` vector must provide a single specific index for the true class for each row of `logits` (each minibatch entry). For soft softmax classification with a probability distribution for each entry, see `softmax_cross_entropy_with_logits`. **WARNING:** This op expects unscaled logits, since it performs a `softmax` on `logits` internally for efficiency. Do not call this op with the output of `softmax`, as it will produce incorrect results. `logits` and must have the shape `[batch_size, num_classes]` and the dtype (either `float32` or `float64`). `labels` must have the shape `[batch_size]` and the dtype `int64`. Args: logits: Unscaled log probabilities. labels: Each entry `labels[i]` must be an index in `[0, num_classes)`. name: A name for the operation (optional). Returns: A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the softmax cross entropy loss. """ # The second output tensor contains the gradients. We use it in # _CrossEntropyGrad() in nn_grad but not here. cost, unused_backprop = gen_nn_ops._sparse_softmax_cross_entropy_with_logits( logits, labels, name=name) return cost @ops.RegisterShape("SparseSoftmaxCrossEntropyWithLogits") def _SparseSoftmaxCrossEntropyWithLogitsShape(op): """Shape function for SparseSoftmaxCrossEntropyWithLogits op.""" logits_shape = op.inputs[0].get_shape() input_shape = logits_shape.with_rank(2) batch_size = input_shape[0] # labels_shape op.inputs[1].get_shape().merge_with(tensor_shape.vector(batch_size)) return [tensor_shape.vector(batch_size.value), input_shape] @ops.RegisterShape("SoftmaxCrossEntropyWithLogits") def _SoftmaxCrossEntropyWithLogitsShape(op): """Shape function for SoftmaxCrossEntropyWithLogits op.""" logits_shape = op.inputs[0].get_shape() labels_shape = op.inputs[1].get_shape() input_shape = logits_shape.merge_with(labels_shape).with_rank(2) batch_size = input_shape[0] return [tensor_shape.vector(batch_size.value), input_shape] def avg_pool(value, ksize, strides, padding, data_format="NHWC", name=None): """Performs the average pooling on the input. Each entry in `output` is the mean of the corresponding size `ksize` window in `value`. Args: value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type `float32`, `float64`, `qint8`, `quint8`, or `qint32`. ksize: A list of ints that has length >= 4. The size of the window for each dimension of the input tensor. strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. data_format: A string. 'NHWC' and 'NCHW" are supported. name: Optional name for the operation. Returns: A `Tensor` with the same type as `value`. The average pooled output tensor. """ with ops.op_scope([value], name, "AvgPool") as name: value = ops.convert_to_tensor(value, name="input") return gen_nn_ops._avg_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name) def max_pool(value, ksize, strides, padding, data_format="NHWC", name=None): """Performs the max pooling on the input. Args: value: A 4-D `Tensor` with shape `[batch, height, width, channels]` and type `tf.float32`. ksize: A list of ints that has length >= 4. The size of the window for each dimension of the input tensor. strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. data_format: A string. 'NHWC' and 'NCHW" are supported. name: Optional name for the operation. Returns: A `Tensor` with type `tf.float32`. The max pooled output tensor. """ with ops.op_scope([value], name, "MaxPool") as name: value = ops.convert_to_tensor(value, name="input") return gen_nn_ops._max_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name) ops.RegisterShape("Relu")(common_shapes.unchanged_shape) ops.RegisterShape("Relu6")(common_shapes.unchanged_shape) ops.RegisterShape("Elu")(common_shapes.unchanged_shape) ops.RegisterShape("Softplus")(common_shapes.unchanged_shape) ops.RegisterShape("Softsign")(common_shapes.unchanged_shape) @ops.RegisterShape("ReluGrad") @ops.RegisterShape("Relu6Grad") @ops.RegisterShape("EluGrad") @ops.RegisterShape("SoftplusGrad") @ops.RegisterShape("SoftsignGrad") def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args: op: Input operation. Returns: Shape of both inputs to `op`. """ return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())] ops.RegisterShape("L2Loss")(common_shapes.scalar_shape) ops.RegisterShape("LRN")(common_shapes.unchanged_shape_with_rank(4)) @ops.RegisterShape("LRNGrad") def _LRNGradShape(op): """Shape function for LRNGrad op.""" in_grads_shape = op.inputs[0].get_shape().with_rank(4) in_image_shape = op.inputs[1].get_shape().with_rank(4) out_image_shape = op.inputs[2].get_shape().with_rank(4) return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)] ops.RegisterShape("Softmax")( common_shapes.unchanged_shape_with_rank(2)) @ops.RegisterShape("InTopK") def _InTopKShape(op): """Shape function for InTopK op.""" predictions_shape = op.inputs[0].get_shape().with_rank(2) targets_shape = op.inputs[1].get_shape().with_rank(1) batch_size = predictions_shape[0].merge_with(targets_shape[0]) return [tensor_shape.vector(batch_size.value)] @ops.RegisterShape("TopK") @ops.RegisterShape("TopKV2") def _TopKShape(op): """Shape function for TopK and TopKV2 ops.""" input_shape = op.inputs[0].get_shape().with_rank_at_least(1) if len(op.inputs) >= 2: k = tensor_util.constant_value(op.inputs[1]) else: k = op.get_attr("k") last = input_shape[-1].value if last is not None and k is not None and last < k: raise ValueError("input.shape %s must have last dimension >= k = %d" % (input_shape, k)) output_shape = input_shape[:-1].concatenate([k]) return [output_shape, output_shape] @ops.RegisterShape("BatchNormWithGlobalNormalization") def _BatchNormShape(op): """Shape function for BatchNormWithGlobalNormalization op.""" input_shape = op.inputs[0].get_shape().with_rank(4) mean_shape = op.inputs[1].get_shape().with_rank(1) var_shape = op.inputs[2].get_shape().with_rank(1) beta_shape = op.inputs[3].get_shape().with_rank(1) gamma_shape = op.inputs[4].get_shape().with_rank(1) mean_shape[0].merge_with(input_shape[3]) var_shape[0].merge_with(input_shape[3]) beta_shape[0].merge_with(input_shape[3]) gamma_shape[0].merge_with(input_shape[3]) return [input_shape] @ops.RegisterShape("BatchNormWithGlobalNormalizationGrad") def _BatchNormGradShape(op): """Shape function for BatchNormWithGlobalNormalizationGrad op.""" input_shape = op.inputs[0].get_shape().with_rank(4) mean_shape = op.inputs[1].get_shape().with_rank(1) var_shape = op.inputs[2].get_shape().with_rank(1) beta_shape = op.inputs[3].get_shape().with_rank(1) out_backprop_shape = op.inputs[4].get_shape().with_rank(4) input_shape = input_shape.merge_with(out_backprop_shape) vector_dim = input_shape[3] vector_dim = vector_dim.merge_with(mean_shape[0]) vector_dim = vector_dim.merge_with(var_shape[0]) vector_dim = vector_dim.merge_with(beta_shape[0]) return [input_shape] + ([tensor_shape.vector(vector_dim)] * 4) ops.RegisterShape("Conv2D")(common_shapes.conv2d_shape) ops.RegisterShape("DepthwiseConv2dNative")( common_shapes.depthwise_conv2d_native_shape) ops.RegisterShape("AvgPool")(common_shapes.avg_pool_shape) ops.RegisterShape("MaxPool")(common_shapes.max_pool_shape) @ops.RegisterShape("MaxPoolWithArgmax") def _MaxPoolWithArgMaxShape(op): """Shape function for MaxPoolWithArgmax op.""" return common_shapes.max_pool_shape(op) * 2 @ops.RegisterShape("AvgPoolGrad") def _AvgPoolGradShape(op): """Shape function for the AvgPoolGrad op.""" orig_input_shape = tensor_util.constant_value(op.inputs[0]) if orig_input_shape is not None: return [tensor_shape.TensorShape(orig_input_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know orig_input_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("Conv2DBackpropFilter") def _Conv2DBackpropFilterShape(op): """Shape function for the Conv2DBackpropFilter op.""" filter_shape = tensor_util.constant_value(op.inputs[1]) if filter_shape is not None: return [tensor_shape.TensorShape(filter_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know filter_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("Conv2DBackpropInput") def _Conv2DBackpropInputShape(op): """Shape function for the Conv2DBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None: return [tensor_shape.TensorShape(input_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know input_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("DepthwiseConv2dNativeBackpropFilter") def _DepthwiseConv2dNativeBackpropFilterShape(op): """Shape function for the DepthwiseConv2dNativeBackpropFilter op.""" filter_shape = tensor_util.constant_value(op.inputs[1]) if filter_shape is not None: return [tensor_shape.TensorShape(filter_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("DepthwiseConv2dNativeBackpropInput") def _DepthwiseConv2dNativeBackpropInputShape(op): """Shape function for the DepthwiseConv2dNativeBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None: return [tensor_shape.TensorShape(input_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("MaxPoolGrad") @ops.RegisterShape("MaxPoolGradWithArgmax") def _MaxPoolGradShape(op): """Shape function for the MaxPoolGrad op.""" orig_input_shape = op.inputs[0].get_shape().with_rank(4) return [orig_input_shape] @ops.RegisterStatistics("Conv2D", "flops") def _calc_conv_flops(graph, node): """Calculates the compute resources needed for Conv2D.""" input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) input_shape.assert_is_fully_defined() filter_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1]) filter_shape.assert_is_fully_defined() output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) output_shape.assert_is_fully_defined() filter_height = int(filter_shape[0]) filter_width = int(filter_shape[1]) filter_in_depth = int(filter_shape[2]) output_count = np.prod(output_shape.as_list()) return ops.OpStats("flops", (output_count * filter_in_depth * filter_height * filter_width * 2)) @ops.RegisterStatistics("Conv2D", "weight_parameters") def _calc_conv_weight_params(graph, node): """Calculates the on-disk size of the weights for Conv2D.""" input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) input_shape.assert_is_fully_defined() filter_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1]) filter_shape.assert_is_fully_defined() output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) output_shape.assert_is_fully_defined() filter_height = int(filter_shape[0]) filter_width = int(filter_shape[1]) filter_in_depth = int(filter_shape[2]) filter_out_depth = int(filter_shape[3]) return ops.OpStats("weight_parameters", (filter_height * filter_width * filter_in_depth * filter_out_depth)) @ops.RegisterStatistics("BiasAdd", "flops") def _calc_bias_add_flops(graph, node): """Calculates the computing needed for BiasAdd.""" input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) input_shape.assert_is_fully_defined() input_count = np.prod(input_shape.as_list()) return ops.OpStats("flops", input_count) @ops.RegisterStatistics("BiasAdd", "weight_parameters") def _calc_bias_add_weight_params(graph, node): """Calculates the on-disk weight parameters for BiasAdd.""" bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1]) bias_shape.assert_is_fully_defined() bias_count = np.prod(bias_shape.as_list()) return ops.OpStats("weight_parameters", bias_count) def xw_plus_b(x, weights, biases, name=None): # pylint: disable=invalid-name """Computes matmul(x, weights) + biases. Args: x: a 2D tensor. Dimensions typically: batch, in_units weights: a 2D tensor. Dimensions typically: in_units, out_units biases: a 1D tensor. Dimensions: out_units name: A name for the operation (optional). If not specified "xw_plus_b" is used. Returns: A 2-D Tensor computing matmul(x, weights) + biases. Dimensions typically: batch, out_units. """ with ops.op_scope([x, weights, biases], name, "xw_plus_b") as name: x = ops.convert_to_tensor(x, name="x") weights = ops.convert_to_tensor(weights, name="weights") biases = ops.convert_to_tensor(biases, name="biases") mm = math_ops.matmul(x, weights) return bias_add(mm, biases, name=name) def xw_plus_b_v1(x, weights, biases, name=None): # pylint: disable=invalid-name """Computes matmul(x, weights) + biases. This is a deprecated version of that will soon be removed. Args: x: a 2D tensor. Dimensions typically: batch, in_units weights: a 2D tensor. Dimensions typically: in_units, out_units biases: a 1D tensor. Dimensions: out_units name: A name for the operation (optional). If not specified "xw_plus_b_v1" is used. Returns: A 2-D Tensor computing matmul(x, weights) + biases. Dimensions typically: batch, out_units. """ with ops.op_scope([x, weights, biases], name, "xw_plus_b_v1") as name: x = ops.convert_to_tensor(x, name="x") weights = ops.convert_to_tensor(weights, name="weights") biases = ops.convert_to_tensor(biases, name="biases") mm = math_ops.matmul(x, weights) return bias_add_v1(mm, biases, name=name) # pylint: disable=invalid-name def dropout(x, keep_prob, noise_shape=None, seed=None, name=None): """Computes dropout. With probability `keep_prob`, outputs the input element scaled up by `1 / keep_prob`, otherwise outputs `0`. The scaling is so that the expected sum is unchanged. By default, each element is kept or dropped independently. If `noise_shape` is specified, it must be [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]` will make independent decisions. For example, if `shape(x) = [k, l, m, n]` and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be kept independently and each row and column will be kept or not kept together. Args: x: A tensor. keep_prob: A scalar `Tensor` with the same type as x. The probability that each element is kept. noise_shape: A 1-D `Tensor` of type `int32`, representing the shape for randomly generated keep/drop flags. seed: A Python integer. Used to create random seeds. See [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed) for behavior. name: A name for this operation (optional). Returns: A Tensor of the same shape of `x`. Raises: ValueError: If `keep_prob` is not in `(0, 1]`. """ with ops.op_scope([x], name, "dropout") as name: x = ops.convert_to_tensor(x, name="x") if isinstance(keep_prob, float) and not 0 < keep_prob <= 1: raise ValueError("keep_prob must be a scalar tensor or a float in the " "range (0, 1], got %g" % keep_prob) keep_prob = ops.convert_to_tensor( keep_prob, dtype=x.dtype, name="keep_prob") keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar()) noise_shape = noise_shape or array_ops.shape(x) # uniform [keep_prob, 1.0 + keep_prob) random_tensor = keep_prob random_tensor += random_ops.random_uniform( noise_shape, seed=seed, dtype=x.dtype) # 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob) binary_tensor = math_ops.floor(random_tensor) ret = x * math_ops.inv(keep_prob) * binary_tensor ret.set_shape(x.get_shape()) return ret def top_k(input, k=1, sorted=True, name=None): """Finds values and indices of the `k` largest entries for the last dimension. If the input is a vector (rank-1), finds the `k` largest entries in the vector and outputs their values and indices as vectors. Thus `values[j]` is the `j`-th largest entry in `input`, and its index is `indices[j]`. For matrices (resp. higher rank input), computes the top `k` entries in each row (resp. vector along the last dimension). Thus, values.shape = indices.shape = input.shape[:-1] + [k] If two elements are equal, the lower-index element appears first. Args: input: 1-D or higher `Tensor` with last dimension at least `k`. k: 0-D `int32` `Tensor`. Number of top elements to look for along the last dimension (along each row for matrices). sorted: If true the resulting `k` elements will be sorted by the values in descending order. name: Optional name for the operation. Returns: values: The `k` largest elements along each last dimensional slice. indices: The indices of `values` within the last dimension of `input`. """ return gen_nn_ops._top_kv2(input, k=k, sorted=sorted, name=name) # pylint: enable=invalid-name
[ "tensorflow.python.framework.tensor_shape.scalar", "tensorflow.python.ops.gen_nn_ops._sparse_softmax_cross_entropy_with_logits", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.common_shapes.unchanged_shape_with_rank", "tensorflow.python.ops.gen_nn_ops._softmax_cross_entropy_with_logits", "tensorflow.python.framework.ops.op_scope", "tensorflow.python.ops.gen_nn_ops._relu6", "tensorflow.python.client.graph_util.tensor_shape_from_node_def_name", "tensorflow.python.ops.math_ops.floor", "tensorflow.python.ops.math_ops.inv", "tensorflow.python.framework.ops.OpStats", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.ops.gen_nn_ops._avg_pool", "tensorflow.python.ops.gen_nn_ops._max_pool", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.gen_nn_ops._bias_add_v1", "tensorflow.python.ops.gen_nn_ops._bias_add", "tensorflow.python.framework.ops.RegisterShape", "tensorflow.python.ops.gen_nn_ops.conv2d_backprop_input", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.framework.tensor_shape.unknown_shape", "tensorflow.python.framework.ops.RegisterStatistics", "tensorflow.python.ops.gen_nn_ops._top_kv2", "tensorflow.python.ops.common_shapes.max_pool_shape", "tensorflow.python.framework.tensor_shape.vector", "tensorflow.python.ops.random_ops.random_uniform" ]
tensorflow/python/ops/nn_ops.py
[(266, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SparseSoftmaxCrossEntropyWithLogits"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (277, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SoftmaxCrossEntropyWithLogits"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (348, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""ReluGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (349, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Relu6Grad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (350, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""EluGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (351, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SoftplusGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (352, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""SoftsignGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (371, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LRNGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (384, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""InTopK"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (393, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""TopK"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (394, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""TopKV2"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (410, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BatchNormWithGlobalNormalization"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (425, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BatchNormWithGlobalNormalizationGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (448, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""MaxPoolWithArgmax"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (454, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""AvgPoolGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (468, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Conv2DBackpropFilter"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (482, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Conv2DBackpropInput"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (496, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""DepthwiseConv2dNativeBackpropFilter"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (506, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""DepthwiseConv2dNativeBackpropInput"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (516, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""MaxPoolGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (517, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""MaxPoolGradWithArgmax"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (524, 'tensorflow.python.framework.ops.RegisterStatistics', 'ops.RegisterStatistics', (['"""Conv2D"""', '"""flops"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (542, 'tensorflow.python.framework.ops.RegisterStatistics', 'ops.RegisterStatistics', (['"""Conv2D"""', '"""weight_parameters"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (560, 'tensorflow.python.framework.ops.RegisterStatistics', 'ops.RegisterStatistics', (['"""BiasAdd"""', '"""flops"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (569, 'tensorflow.python.framework.ops.RegisterStatistics', 'ops.RegisterStatistics', (['"""BiasAdd"""', '"""weight_parameters"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (132, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BiasAdd"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (135, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BiasAddGrad"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (166, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BiasAddV1"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (169, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""BiasAddGradV1"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (221, 'tensorflow.python.ops.gen_nn_ops._softmax_cross_entropy_with_logits', 'gen_nn_ops._softmax_cross_entropy_with_logits', (['logits', 'labels'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (261, 'tensorflow.python.ops.gen_nn_ops._sparse_softmax_cross_entropy_with_logits', 'gen_nn_ops._sparse_softmax_cross_entropy_with_logits', (['logits', 'labels'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (341, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Relu"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (342, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Relu6"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (343, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Elu"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (344, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Softplus"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (345, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Softsign"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (365, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""L2Loss"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (368, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""LRN"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (368, 'tensorflow.python.ops.common_shapes.unchanged_shape_with_rank', 'common_shapes.unchanged_shape_with_rank', (['(4)'], {}), False, 'from tensorflow.python.ops import common_shapes\n'), (380, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Softmax"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (381, 'tensorflow.python.ops.common_shapes.unchanged_shape_with_rank', 'common_shapes.unchanged_shape_with_rank', (['(2)'], {}), False, 'from tensorflow.python.ops import common_shapes\n'), (441, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""Conv2D"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (442, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""DepthwiseConv2dNative"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (444, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""AvgPool"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (445, 'tensorflow.python.framework.ops.RegisterShape', 'ops.RegisterShape', (['"""MaxPool"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (457, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[0]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (471, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (485, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[0]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (499, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (509, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[0]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (527, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[0]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (529, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[1]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (532, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.name'], {}), False, 'from tensorflow.python.client import graph_util\n'), (538, 'tensorflow.python.framework.ops.OpStats', 'ops.OpStats', (['"""flops"""', '(output_count * filter_in_depth * filter_height * filter_width * 2)'], {}), False, 'from tensorflow.python.framework import ops\n'), (545, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[0]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (547, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[1]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (550, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.name'], {}), False, 'from tensorflow.python.client import graph_util\n'), (556, 'tensorflow.python.framework.ops.OpStats', 'ops.OpStats', (['"""weight_parameters"""', '(filter_height * filter_width * filter_in_depth * filter_out_depth)'], {}), False, 'from tensorflow.python.framework import ops\n'), (563, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[0]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (566, 'tensorflow.python.framework.ops.OpStats', 'ops.OpStats', (['"""flops"""', 'input_count'], {}), False, 'from tensorflow.python.framework import ops\n'), (572, 'tensorflow.python.client.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[1]'], {}), False, 'from tensorflow.python.client import graph_util\n'), (575, 'tensorflow.python.framework.ops.OpStats', 'ops.OpStats', (['"""weight_parameters"""', 'bias_count'], {}), False, 'from tensorflow.python.framework import ops\n'), (704, 'tensorflow.python.ops.gen_nn_ops._top_kv2', 'gen_nn_ops._top_kv2', (['input'], {'k': 'k', 'sorted': 'sorted', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (73, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[value, filter, output_shape]', 'name', '"""conv2d_transpose"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (75, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['value'], {'name': '"""value"""'}), False, 'from tensorflow.python.framework import ops\n'), (76, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['filter'], {'name': '"""filter"""'}), False, 'from tensorflow.python.framework import ops\n'), (82, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['output_shape'], {'name': '"""output_shape"""'}), False, 'from tensorflow.python.framework import ops\n'), (98, 'tensorflow.python.ops.gen_nn_ops.conv2d_backprop_input', 'gen_nn_ops.conv2d_backprop_input', ([], {'input_sizes': 'output_shape_', 'filter': 'filter', 'out_backprop': 'value', 'strides': 'strides', 'padding': 'padding', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (127, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[value, bias]', 'name', '"""BiasAdd"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (128, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['value'], {'name': '"""input"""'}), False, 'from tensorflow.python.framework import ops\n'), (129, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['bias'], {'dtype': 'value.dtype', 'name': '"""bias"""'}), False, 'from tensorflow.python.framework import ops\n'), (130, 'tensorflow.python.ops.gen_nn_ops._bias_add', 'gen_nn_ops._bias_add', (['value', 'bias'], {'data_format': 'data_format', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (160, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[value, bias]', 'name', '"""BiasAddV1"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (161, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['value'], {'name': '"""input"""'}), False, 'from tensorflow.python.framework import ops\n'), (162, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['bias'], {'dtype': 'value.dtype', 'name': '"""bias"""'}), False, 'from tensorflow.python.framework import ops\n'), (163, 'tensorflow.python.ops.gen_nn_ops._bias_add_v1', 'gen_nn_ops._bias_add_v1', (['value', 'bias'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (184, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[features]', 'name', '"""Relu6"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (185, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['features'], {'name': '"""features"""'}), False, 'from tensorflow.python.framework import ops\n'), (186, 'tensorflow.python.ops.gen_nn_ops._relu6', 'gen_nn_ops._relu6', (['features'], {'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (273, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['batch_size'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (274, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['batch_size.value'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (284, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['batch_size.value'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (308, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[value]', 'name', '"""AvgPool"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (309, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['value'], {'name': '"""input"""'}), False, 'from tensorflow.python.framework import ops\n'), (310, 'tensorflow.python.ops.gen_nn_ops._avg_pool', 'gen_nn_ops._avg_pool', (['value'], {'ksize': 'ksize', 'strides': 'strides', 'padding': 'padding', 'data_format': 'data_format', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (333, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[value]', 'name', '"""MaxPool"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (334, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['value'], {'name': '"""input"""'}), False, 'from tensorflow.python.framework import ops\n'), (335, 'tensorflow.python.ops.gen_nn_ops._max_pool', 'gen_nn_ops._max_pool', (['value'], {'ksize': 'ksize', 'strides': 'strides', 'padding': 'padding', 'data_format': 'data_format', 'name': 'name'}), False, 'from tensorflow.python.ops import gen_nn_ops\n'), (390, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['batch_size.value'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (399, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['op.inputs[1]'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (451, 'tensorflow.python.ops.common_shapes.max_pool_shape', 'common_shapes.max_pool_shape', (['op'], {}), False, 'from tensorflow.python.ops import common_shapes\n'), (592, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, weights, biases]', 'name', '"""xw_plus_b"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (593, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (594, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['weights'], {'name': '"""weights"""'}), False, 'from tensorflow.python.framework import ops\n'), (595, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['biases'], {'name': '"""biases"""'}), False, 'from tensorflow.python.framework import ops\n'), (596, 'tensorflow.python.ops.math_ops.matmul', 'math_ops.matmul', (['x', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (616, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x, weights, biases]', 'name', '"""xw_plus_b_v1"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (617, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (618, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['weights'], {'name': '"""weights"""'}), False, 'from tensorflow.python.framework import ops\n'), (619, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['biases'], {'name': '"""biases"""'}), False, 'from tensorflow.python.framework import ops\n'), (620, 'tensorflow.python.ops.math_ops.matmul', 'math_ops.matmul', (['x', 'weights'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (657, 'tensorflow.python.framework.ops.op_scope', 'ops.op_scope', (['[x]', 'name', '"""dropout"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (658, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (662, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['keep_prob'], {'dtype': 'x.dtype', 'name': '"""keep_prob"""'}), False, 'from tensorflow.python.framework import ops\n'), (669, 'tensorflow.python.ops.random_ops.random_uniform', 'random_ops.random_uniform', (['noise_shape'], {'seed': 'seed', 'dtype': 'x.dtype'}), False, 'from tensorflow.python.ops import random_ops\n'), (672, 'tensorflow.python.ops.math_ops.floor', 'math_ops.floor', (['random_tensor'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (465, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(4)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (479, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(4)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (493, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(4)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (503, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(4)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (513, 'tensorflow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', ([], {'ndims': '(4)'}), False, 'from tensorflow.python.framework import tensor_shape\n'), (664, 'tensorflow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', ([], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (666, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['x'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (83, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['(4)'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (438, 'tensorflow.python.framework.tensor_shape.vector', 'tensor_shape.vector', (['vector_dim'], {}), False, 'from tensorflow.python.framework import tensor_shape\n'), (673, 'tensorflow.python.ops.math_ops.inv', 'math_ops.inv', (['keep_prob'], {}), False, 'from tensorflow.python.ops import math_ops\n')]
yanndupis/tf-encrypted
cfaea3ba87520f73979ed4e4f397eba3beb0a535
import sys import tensorflow as tf import tf_encrypted as tfe from convert import decode if len(sys.argv) > 1: # config file was specified config_file = sys.argv[1] config = tfe.RemoteConfig.load(config_file) tfe.set_config(config) tfe.set_protocol(tfe.protocol.Pond()) session_target = sys.argv[2] if len(sys.argv) > 2 else None class ModelOwner: LEARNING_RATE = 0.1 ITERATIONS = 60000 // 30 def __init__(self, player_name): self.player_name = player_name with tf.device(tfe.get_config().get_player(player_name).device_name): self._initialize_weights() def _initialize_weights(self): with tf.name_scope('parameters'): self.w0 = tf.Variable(tf.random_normal([28 * 28, 512])) self.b0 = tf.Variable(tf.zeros([512])) self.w1 = tf.Variable(tf.random_normal([512, 10])) self.b1 = tf.Variable(tf.zeros([10])) def _build_model(self, x, y): w0 = self.w0.read_value() b0 = self.b0.read_value() w1 = self.w1.read_value() b1 = self.b1.read_value() params = (w0, b0, w1, b1) layer0 = tf.matmul(x, w0) + b0 layer1 = tf.nn.sigmoid(layer0) layer2 = tf.matmul(layer1, w1) + b1 predictions = layer2 loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits=predictions, labels=y)) grads = tf.gradients(ys=loss, xs=params) return predictions, loss, grads def build_training_model(self, x, y): """ This method will be called once by all data owners to create a local gradient computation on their machine. """ _, _, grads = self._build_model(x, y) return grads def _build_validation_model(self, x, y): predictions, loss, _ = self._build_model(x, y) most_likely = tf.argmax(predictions, axis=1) return most_likely, loss def _build_data_pipeline(self): def normalize(image, label): image = tf.cast(image, tf.float32) / 255.0 return image, label dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"]) dataset = dataset.map(decode) dataset = dataset.map(normalize) dataset = dataset.batch(50) dataset = dataset.take(1) # keep validating on the same items dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() return iterator.get_next() def update_model(self, *grads): params = [self.w0, self.b0, self.w1, self.b1] grads = [tf.cast(grad, tf.float32) for grad in grads] with tf.name_scope('update'): update_op = tf.group(*[ param.assign(param - grad * self.LEARNING_RATE) for param, grad in zip(params, grads) ]) # return update_op with tf.name_scope('validate'): x, y = self._build_data_pipeline() y_hat, loss = self._build_validation_model(x, y) with tf.control_dependencies([update_op]): return tf.print('expect', loss, y, y_hat, summarize=50) class DataOwner: BATCH_SIZE = 30 def __init__(self, player_name, build_training_model): self.player_name = player_name self._build_training_model = build_training_model def _build_data_pipeline(self): def normalize(image, label): image = tf.cast(image, tf.float32) / 255.0 return image, label dataset = tf.data.TFRecordDataset(["./data/train.tfrecord"]) dataset = dataset.map(decode) dataset = dataset.map(normalize) dataset = dataset.repeat() dataset = dataset.batch(self.BATCH_SIZE) iterator = dataset.make_one_shot_iterator() return iterator.get_next() def compute_gradient(self): with tf.name_scope('data_loading'): x, y = self._build_data_pipeline() with tf.name_scope('gradient_computation'): grads = self._build_training_model(x, y) return grads model_owner = ModelOwner('model-owner') data_owners = [ DataOwner('data-owner-0', model_owner.build_training_model), DataOwner('data-owner-1', model_owner.build_training_model), DataOwner('data-owner-2', model_owner.build_training_model), ] model_grads = zip(*( tfe.define_private_input(data_owner.player_name, data_owner.compute_gradient) for data_owner in data_owners )) with tf.name_scope('secure_aggregation'): aggregated_model_grads = [ tfe.add_n(grads) / len(grads) for grads in model_grads ] iteration_op = tfe.define_output(model_owner.player_name, aggregated_model_grads, model_owner.update_model) with tfe.Session(target=session_target) as sess: sess.run(tf.global_variables_initializer(), tag='init') for i in range(model_owner.ITERATIONS): if i % 100 == 0: print("Iteration {}".format(i)) sess.run(iteration_op, tag='iteration') else: sess.run(iteration_op)
[ "tensorflow.matmul", "tensorflow.nn.sigmoid", "tensorflow.losses.sparse_softmax_cross_entropy", "tensorflow.zeros", "tensorflow.control_dependencies", "tensorflow.data.TFRecordDataset", "tensorflow.cast", "tensorflow.gradients", "tensorflow.global_variables_initializer", "tensorflow.print", "tensorflow.name_scope", "tensorflow.argmax", "tensorflow.random_normal" ]
examples/federated-learning/run.py
[(151, 'tf_encrypted.define_output', 'tfe.define_output', (['model_owner.player_name', 'aggregated_model_grads', 'model_owner.update_model'], {}), True, 'import tf_encrypted as tfe\n'), (11, 'tf_encrypted.RemoteConfig.load', 'tfe.RemoteConfig.load', (['config_file'], {}), True, 'import tf_encrypted as tfe\n'), (12, 'tf_encrypted.set_config', 'tfe.set_config', (['config'], {}), True, 'import tf_encrypted as tfe\n'), (145, 'tensorflow.name_scope', 'tf.name_scope', (['"""secure_aggregation"""'], {}), True, 'import tensorflow as tf\n'), (153, 'tf_encrypted.Session', 'tfe.Session', ([], {'target': 'session_target'}), True, 'import tf_encrypted as tfe\n'), (13, 'tf_encrypted.protocol.Pond', 'tfe.protocol.Pond', ([], {}), True, 'import tf_encrypted as tfe\n'), (44, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['layer0'], {}), True, 'import tensorflow as tf\n'), (49, 'tensorflow.gradients', 'tf.gradients', ([], {'ys': 'loss', 'xs': 'params'}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.argmax', 'tf.argmax', (['predictions'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (["['./data/train.tfrecord']"], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (["['./data/train.tfrecord']"], {}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.name_scope', 'tf.name_scope', (['"""parameters"""'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.matmul', 'tf.matmul', (['x', 'w0'], {}), True, 'import tensorflow as tf\n'), (45, 'tensorflow.matmul', 'tf.matmul', (['layer1', 'w1'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.losses.sparse_softmax_cross_entropy', 'tf.losses.sparse_softmax_cross_entropy', ([], {'logits': 'predictions', 'labels': 'y'}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.cast', 'tf.cast', (['grad', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.name_scope', 'tf.name_scope', (['"""update"""'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.name_scope', 'tf.name_scope', (['"""validate"""'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.name_scope', 'tf.name_scope', (['"""data_loading"""'], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.name_scope', 'tf.name_scope', (['"""gradient_computation"""'], {}), True, 'import tensorflow as tf\n'), (141, 'tf_encrypted.define_private_input', 'tfe.define_private_input', (['data_owner.player_name', 'data_owner.compute_gradient'], {}), True, 'import tf_encrypted as tfe\n'), (147, 'tf_encrypted.add_n', 'tfe.add_n', (['grads'], {}), True, 'import tf_encrypted as tfe\n'), (31, 'tensorflow.random_normal', 'tf.random_normal', (['[28 * 28, 512]'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.zeros', 'tf.zeros', (['[512]'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.random_normal', 'tf.random_normal', (['[512, 10]'], {}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.zeros', 'tf.zeros', (['[10]'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.cast', 'tf.cast', (['image', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_op]'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.print', 'tf.print', (['"""expect"""', 'loss', 'y', 'y_hat'], {'summarize': '(50)'}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.cast', 'tf.cast', (['image', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (26, 'tf_encrypted.get_config', 'tfe.get_config', ([], {}), True, 'import tf_encrypted as tfe\n')]
whfh3900/Tacotron-2-korea-example
2799394f14e5d52bed2e5f7495bbd89e020a350a
import os import threading import time import numpy as np import tensorflow as tf from datasets import audio from infolog import log from keras.utils import np_utils from sklearn.model_selection import train_test_split from .util import is_mulaw_quantize, is_scalar_input _batches_per_group = 64 class Feeder: """ Feeds batches of data into queue in a background thread. """ def __init__(self, coordinator, metadata_filename, base_dir, hparams): super(Feeder, self).__init__() self._coord = coordinator self._hparams = hparams self._train_offset = 0 self._test_offset = 0 if hparams.symmetric_mels: self._spec_pad = -hparams.max_abs_value else: self._spec_pad = 0. #Base directory of the project (to map files from different locations) self._base_dir = base_dir #Load metadata self._data_dir = os.path.dirname(metadata_filename) with open(metadata_filename, 'r', encoding='utf-8') as f: self._metadata = [line.strip().split('|') for line in f] #Train test split if hparams.wavenet_test_size is None: assert hparams.wavenet_test_batches is not None test_size = (hparams.wavenet_test_size if hparams.wavenet_test_size is not None else hparams.wavenet_test_batches * hparams.wavenet_batch_size) indices = np.arange(len(self._metadata)) train_indices, test_indices = train_test_split(indices, test_size=test_size, random_state=hparams.wavenet_data_random_state) #Make sure test size is a multiple of batch size else round up len_test_indices = _round_down(len(test_indices), hparams.wavenet_batch_size) extra_test = test_indices[len_test_indices:] test_indices = test_indices[:len_test_indices] train_indices = np.concatenate([train_indices, extra_test]) self._train_meta = list(np.array(self._metadata)[train_indices]) self._test_meta = list(np.array(self._metadata)[test_indices]) self.test_steps = len(self._test_meta) // hparams.wavenet_batch_size if hparams.wavenet_test_size is None: assert hparams.wavenet_test_batches == self.test_steps #Get conditioning status self.local_condition, self.global_condition = self._check_conditions() with tf.device('/cpu:0'): # Create placeholders for inputs and targets. Don't specify batch size because we want # to be able to feed different batch sizes at eval time. if is_scalar_input(hparams.input_type): input_placeholder = tf.placeholder(tf.float32, shape=(None, 1, None), name='audio_inputs') target_placeholder = tf.placeholder(tf.float32, shape=(None, None, 1), name='audio_targets') target_type = tf.float32 else: input_placeholder = tf.placeholder(tf.float32, shape=(None, hparams.quantize_channels, None), name='audio_inputs') target_placeholder = tf.placeholder(tf.int32, shape=(None, None, 1), name='audio_targets') target_type = tf.int32 self._placeholders = [ input_placeholder, target_placeholder, tf.placeholder(tf.int32, shape=(None, ), name='input_lengths'), ] queue_types = [tf.float32, target_type, tf.int32] if self.local_condition: self._placeholders.append(tf.placeholder(tf.float32, shape=(None, hparams.num_mels, None), name='local_condition_features')) queue_types.append(tf.float32) if self.global_condition: self._placeholders.append(tf.placeholder(tf.int32, shape=(None, 1), name='global_condition_features')) queue_types.append(tf.int32) # Create queue for buffering data queue = tf.FIFOQueue(8, queue_types, name='input_queue') self._enqueue_op = queue.enqueue(self._placeholders) variables = queue.dequeue() self.inputs = variables[0] self.inputs.set_shape(self._placeholders[0].shape) self.targets = variables[1] self.targets.set_shape(self._placeholders[1].shape) self.input_lengths = variables[2] self.input_lengths.set_shape(self._placeholders[2].shape) idx = 3 #If local conditioning disabled override c inputs with None if hparams.cin_channels < 0: self.local_condition_features = None else: self.local_condition_features = variables[idx] self.local_condition_features.set_shape(self._placeholders[idx].shape) idx += 1 #If global conditioning disabled override g inputs with None if hparams.gin_channels < 0: self.global_condition_features = None else: self.global_condition_features = variables[idx] self.global_condition_features.set_shape(self._placeholders[idx].shape) # Create queue for buffering eval data eval_queue = tf.FIFOQueue(1, queue_types, name='eval_queue') self._eval_enqueue_op = eval_queue.enqueue(self._placeholders) eval_variables = eval_queue.dequeue() self.eval_inputs = eval_variables[0] self.eval_inputs.set_shape(self._placeholders[0].shape) self.eval_targets = eval_variables[1] self.eval_targets.set_shape(self._placeholders[1].shape) self.eval_input_lengths = eval_variables[2] self.eval_input_lengths.set_shape(self._placeholders[2].shape) eval_idx = 3 #If local conditioning disabled override c inputs with None if hparams.cin_channels < 0: self.eval_local_condition_features = None else: self.eval_local_condition_features = eval_variables[eval_idx] self.eval_local_condition_features.set_shape(self._placeholders[eval_idx].shape) eval_idx += 1 #If global conditioning disabled override g inputs with None if hparams.gin_channels < 0: self.eval_global_condition_features = None else: self.eval_global_condition_features = eval_variables[eval_idx] self.eval_global_condition_features.set_shape(self._placeholders[eval_idx].shape) def start_threads(self, session): self._session = session thread = threading.Thread(name='background', target=self._enqueue_next_train_group) thread.daemon = True #Thread will close when parent quits thread.start() thread = threading.Thread(name='background', target=self._enqueue_next_test_group) thread.daemon = True #Thread will close when parent quits thread.start() def _get_test_groups(self): meta = self._test_meta[self._test_offset] self._test_offset += 1 if self._hparams.train_with_GTA: mel_file = meta[2] else: mel_file = meta[1] audio_file = meta[0] input_data = np.load(os.path.join(self._base_dir, audio_file)) if self.local_condition: local_condition_features = np.load(os.path.join(self._base_dir, mel_file)) else: local_condition_features = None if self.global_condition: global_condition_features = meta[3] if global_condition_features == '<no_g>': raise RuntimeError('Please redo the wavenet preprocessing (or GTA synthesis) to assign global condition features!') else: global_condition_features = None return (input_data, local_condition_features, global_condition_features, len(input_data)) def make_test_batches(self): start = time.time() #Read one example for evaluation n = 1 #Test on entire test set (one sample at an evaluation step) examples = [self._get_test_groups() for i in range(len(self._test_meta))] batches = [examples[i: i+n] for i in range(0, len(examples), n)] np.random.shuffle(batches) print('\nGenerated {} test batches of size {} in {:.3f} sec'.format(len(batches), n, time.time() - start)) log('\nGenerated {} test batches of size {} in {:.3f} sec'.format(len(batches), n, time.time() - start)) return batches def _enqueue_next_train_group(self): while not self._coord.should_stop(): start = time.time() # Read a group of examples n = self._hparams.wavenet_batch_size examples = [self._get_next_example() for i in range(n * _batches_per_group)] # Bucket examples base on similiar output length for efficiency examples.sort(key=lambda x: x[-1]) batches = [examples[i: i+n] for i in range(0, len(examples), n)] np.random.shuffle(batches) print('\nGenerated {} train batches of size {} in {:.3f} sec'.format(len(batches), n, time.time() - start)) log('\nGenerated {} train batches of size {} in {:.3f} sec'.format(len(batches), n, time.time() - start)) for batch in batches: feed_dict = dict(zip(self._placeholders, self._prepare_batch(batch))) self._session.run(self._enqueue_op, feed_dict=feed_dict) def _enqueue_next_test_group(self): test_batches = self.make_test_batches() while not self._coord.should_stop(): for batch in test_batches: feed_dict = dict(zip(self._placeholders, self._prepare_batch(batch))) self._session.run(self._eval_enqueue_op, feed_dict=feed_dict) def _get_next_example(self): '''Get a single example (input, output, len_output) from disk ''' if self._train_offset >= len(self._train_meta): self._train_offset = 0 np.random.shuffle(self._train_meta) meta = self._train_meta[self._train_offset] self._train_offset += 1 if self._hparams.train_with_GTA: mel_file = meta[2] if 'linear' in mel_file: raise RuntimeError('Linear spectrogram files selected instead of GTA mels, did you specify the wrong metadata?') else: mel_file = meta[1] audio_file = meta[0] input_data = np.load(os.path.join(self._base_dir, audio_file)) if self.local_condition: local_condition_features = np.load(os.path.join(self._base_dir, mel_file)) else: local_condition_features = None if self.global_condition: global_condition_features = meta[3] if global_condition_features == '<no_g>': raise RuntimeError('Please redo the wavenet preprocessing (or GTA synthesis) to assign global condition features!') else: global_condition_features = None return (input_data, local_condition_features, global_condition_features, len(input_data)) def _prepare_batch(self, batches): assert 0 == len(batches) % self._hparams.wavenet_num_gpus size_per_device = int(len(batches) / self._hparams.wavenet_num_gpus) np.random.shuffle(batches) #Limit time steps to save GPU Memory usage max_time_steps = self._limit_time() #Adjust time resolution for upsampling batches = self._adjust_time_resolution(batches, self.local_condition, max_time_steps) #time lengths input_lengths = np.asarray([len(x[0]) for x in batches], np.int32) max_input_length = max(input_lengths) #Since all inputs/targets will have the same lengths for all GPUs, we can simply treat all GPUs batches as one big batch and stack all data. (fixed length) inputs = self._prepare_inputs([x[0] for x in batches], max_input_length) targets = self._prepare_targets([x[0] for x in batches], max_input_length) local_condition_features = self._prepare_local_conditions(self.local_condition, [x[1] for x in batches]) global_condition_features = self._prepare_global_conditions(self.global_condition, [x[2] for x in batches]) #Create final batches new_batches = (inputs, targets, input_lengths) if local_condition_features is not None: new_batches += (local_condition_features, ) if global_condition_features is not None: new_batches += (global_condition_features, ) return new_batches def _prepare_inputs(self, inputs, maxlen): if is_mulaw_quantize(self._hparams.input_type): #[batch_size, time_steps, quantize_channels] x_batch = np.stack([_pad_inputs(np_utils.to_categorical( x, num_classes=self._hparams.quantize_channels), maxlen) for x in inputs]).astype(np.float32) else: #[batch_size, time_steps, 1] x_batch = np.stack([_pad_inputs(x.reshape(-1, 1), maxlen) for x in inputs]).astype(np.float32) assert len(x_batch.shape) == 3 #Convert to channels first [batch_size, quantize_channels (or 1), time_steps] x_batch = np.transpose(x_batch, (0, 2, 1)) return x_batch def _prepare_targets(self, targets, maxlen): #[batch_size, time_steps] if is_mulaw_quantize(self._hparams.input_type): y_batch = np.stack([_pad_targets(x, maxlen) for x in targets]).astype(np.int32) else: y_batch = np.stack([_pad_targets(x, maxlen) for x in targets]).astype(np.float32) assert len(y_batch.shape) == 2 #Add extra axis (make 3 dimension) y_batch = np.expand_dims(y_batch, axis=-1) return y_batch def _prepare_local_conditions(self, local_condition, c_features): if local_condition: maxlen = max([len(x) for x in c_features]) #[-max, max] or [0,max] T2_output_range = (-self._hparams.max_abs_value, self._hparams.max_abs_value) if self._hparams.symmetric_mels else (0, self._hparams.max_abs_value) if self._hparams.clip_for_wavenet: c_features = [np.clip(x, T2_output_range[0], T2_output_range[1]) for x in c_features] c_batch = np.stack([_pad_inputs(x, maxlen, _pad=T2_output_range[0]) for x in c_features]).astype(np.float32) assert len(c_batch.shape) == 3 #[batch_size, c_channels, time_steps] c_batch = np.transpose(c_batch, (0, 2, 1)) if self._hparams.normalize_for_wavenet: #rerange to [0, 1] c_batch = _interp(c_batch, T2_output_range).astype(np.float32) else: c_batch = None return c_batch def _prepare_global_conditions(self, global_condition, g_features): if global_condition: g_batch = np.array(g_features).astype(np.int32).reshape(-1, 1) else: g_batch = None return g_batch def _check_conditions(self): local_condition = self._hparams.cin_channels > 0 global_condition = self._hparams.gin_channels > 0 return local_condition, global_condition def _limit_time(self): '''Limit time resolution to save GPU memory. ''' if self._hparams.max_time_sec is not None: return int(self._hparams.max_time_sec * self._hparams.sample_rate) elif self._hparams.max_time_steps is not None: return self._hparams.max_time_steps else: return None def _adjust_time_resolution(self, batch, local_condition, max_time_steps): '''Adjust time resolution between audio and local condition ''' if local_condition: new_batch = [] for b in batch: x, c, g, l = b self._assert_ready_for_upsample(x, c) if max_time_steps is not None: max_steps = _ensure_divisible(max_time_steps, audio.get_hop_size(self._hparams), True) if len(x) > max_time_steps: max_time_frames = max_steps // audio.get_hop_size(self._hparams) start = np.random.randint(0, len(c) - max_time_frames) time_start = start * audio.get_hop_size(self._hparams) x = x[time_start: time_start + max_time_frames * audio.get_hop_size(self._hparams)] c = c[start: start + max_time_frames, :] self._assert_ready_for_upsample(x, c) new_batch.append((x, c, g, l)) return new_batch else: new_batch = [] for b in batch: x, c, g, l = b x = audio.trim_silence(x, hparams) if max_time_steps is not None and len(x) > max_time_steps: start = np.random.randint(0, len(c) - max_time_steps) x = x[start: start + max_time_steps] new_batch.append((x, c, g, l)) return new_batch def _assert_ready_for_upsample(self, x, c): assert len(x) % len(c) == 0 and len(x) // len(c) == audio.get_hop_size(self._hparams) def _pad_inputs(x, maxlen, _pad=0): return np.pad(x, [(0, maxlen - len(x)), (0, 0)], mode='constant', constant_values=_pad) def _pad_targets(x, maxlen, _pad=0): return np.pad(x, (0, maxlen - len(x)), mode='constant', constant_values=_pad) def _round_up(x, multiple): remainder = x % multiple return x if remainder == 0 else x + multiple - remainder def _round_down(x, multiple): remainder = x % multiple return x if remainder == 0 else x - remainder def _ensure_divisible(length, divisible_by=256, lower=True): if length % divisible_by == 0: return length if lower: return length - length % divisible_by else: return length + (divisible_by - length % divisible_by) def _interp(feats, in_range): #rescales from [-max, max] (or [0, max]) to [0, 1] return (feats - in_range[0]) / (in_range[1] - in_range[0])
[ "tensorflow.device", "numpy.expand_dims", "tensorflow.FIFOQueue", "numpy.clip", "sklearn.model_selection.train_test_split", "numpy.random.shuffle", "tensorflow.placeholder", "numpy.concatenate", "numpy.transpose", "numpy.array" ]
wavenet_vocoder/feeder.py
[(40, 'os.path.dirname', 'os.path.dirname', (['metadata_filename'], {}), False, 'import os\n'), (51, 'sklearn.model_selection.train_test_split', 'train_test_split', (['indices'], {'test_size': 'test_size', 'random_state': 'hparams.wavenet_data_random_state'}), False, 'from sklearn.model_selection import train_test_split\n'), (58, 'numpy.concatenate', 'np.concatenate', (['[train_indices, extra_test]'], {}), True, 'import numpy as np\n'), (159, 'threading.Thread', 'threading.Thread', ([], {'name': '"""background"""', 'target': 'self._enqueue_next_train_group'}), False, 'import threading\n'), (163, 'threading.Thread', 'threading.Thread', ([], {'name': '"""background"""', 'target': 'self._enqueue_next_test_group'}), False, 'import threading\n'), (194, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (202, 'numpy.random.shuffle', 'np.random.shuffle', (['batches'], {}), True, 'import numpy as np\n'), (271, 'numpy.random.shuffle', 'np.random.shuffle', (['batches'], {}), True, 'import numpy as np\n'), (307, 'numpy.transpose', 'np.transpose', (['x_batch', '(0, 2, 1)'], {}), True, 'import numpy as np\n'), (318, 'numpy.expand_dims', 'np.expand_dims', (['y_batch'], {'axis': '(-1)'}), True, 'import numpy as np\n'), (71, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.FIFOQueue', 'tf.FIFOQueue', (['(8)', 'queue_types'], {'name': '"""input_queue"""'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.FIFOQueue', 'tf.FIFOQueue', (['(1)', 'queue_types'], {'name': '"""eval_queue"""'}), True, 'import tensorflow as tf\n'), (177, 'os.path.join', 'os.path.join', (['self._base_dir', 'audio_file'], {}), False, 'import os\n'), (210, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (219, 'numpy.random.shuffle', 'np.random.shuffle', (['batches'], {}), True, 'import numpy as np\n'), (239, 'numpy.random.shuffle', 'np.random.shuffle', (['self._train_meta'], {}), True, 'import numpy as np\n'), (251, 'os.path.join', 'os.path.join', (['self._base_dir', 'audio_file'], {}), False, 'import os\n'), (333, 'numpy.transpose', 'np.transpose', (['c_batch', '(0, 2, 1)'], {}), True, 'import numpy as np\n'), (60, 'numpy.array', 'np.array', (['self._metadata'], {}), True, 'import numpy as np\n'), (61, 'numpy.array', 'np.array', (['self._metadata'], {}), True, 'import numpy as np\n'), (75, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, 1, None)', 'name': '"""audio_inputs"""'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, 1)', 'name': '"""audio_targets"""'}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, hparams.quantize_channels, None)', 'name': '"""audio_inputs"""'}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '(None, None, 1)', 'name': '"""audio_targets"""'}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '(None,)', 'name': '"""input_lengths"""'}), True, 'import tensorflow as tf\n'), (180, 'os.path.join', 'os.path.join', (['self._base_dir', 'mel_file'], {}), False, 'import os\n'), (254, 'os.path.join', 'os.path.join', (['self._base_dir', 'mel_file'], {}), False, 'import os\n'), (395, 'datasets.audio.trim_silence', 'audio.trim_silence', (['x', 'hparams'], {}), False, 'from datasets import audio\n'), (403, 'datasets.audio.get_hop_size', 'audio.get_hop_size', (['self._hparams'], {}), False, 'from datasets import audio\n'), (92, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, hparams.num_mels, None)', 'name': '"""local_condition_features"""'}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '(None, 1)', 'name': '"""global_condition_features"""'}), True, 'import tensorflow as tf\n'), (204, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (205, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (328, 'numpy.clip', 'np.clip', (['x', 'T2_output_range[0]', 'T2_output_range[1]'], {}), True, 'import numpy as np\n'), (221, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (222, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (379, 'datasets.audio.get_hop_size', 'audio.get_hop_size', (['self._hparams'], {}), False, 'from datasets import audio\n'), (346, 'numpy.array', 'np.array', (['g_features'], {}), True, 'import numpy as np\n'), (381, 'datasets.audio.get_hop_size', 'audio.get_hop_size', (['self._hparams'], {}), False, 'from datasets import audio\n'), (383, 'datasets.audio.get_hop_size', 'audio.get_hop_size', (['self._hparams'], {}), False, 'from datasets import audio\n'), (300, 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['x'], {'num_classes': 'self._hparams.quantize_channels'}), False, 'from keras.utils import np_utils\n'), (384, 'datasets.audio.get_hop_size', 'audio.get_hop_size', (['self._hparams'], {}), False, 'from datasets import audio\n')]
Brian-ZhenLiu/CNN_models
7cc646b181d86facf19b4129762504ea7b8f1409
import tensorflow as tf import os #from PIL import Image import random import numpy as np from datetime import datetime from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report slim = tf.contrib.slim global first first = True classnum=12 testnum = tf.placeholder(tf.int32) trainnum = tf.placeholder(tf.int32) validnum = tf.placeholder(tf.int32) learnrate = tf.placeholder(tf.float32) def getinputs(path): filename_queue=tf.train.string_input_producer([path]) reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1]) return image,label def get_batch(image,label,batch_size,crop_size): #print(image.shape) #print(label.shape) images,labels=tf.train.shuffle_batch([image,label], batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_test_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_valid_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) class trainwork(object): def __init__(self): with tf.variable_scope('scop'): self.w1=tf.get_variable('w1', [4096,1024],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w2=tf.get_variable('w2', [1024,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.b1 = tf.get_variable('b1', [1024],initializer=tf.constant_initializer(0.0)) self.b2 = tf.get_variable('b2', [classnum],initializer=tf.constant_initializer(0.0)) def inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) out = tf.matmul(l1, self.w2)+self.b2 return out def test_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) out = tf.matmul(l1, self.w2)+self.b2 return out def valid_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) out = tf.matmul(l1, self.w2)+self.b2 return out def softmax_loss(self,predicts,labels): predicts=tf.nn.softmax(predicts) labels=tf.one_hot(labels,classnum) loss=-tf.reduce_sum(labels*tf.log(predicts)) return loss def optimer(self,loss,lr=0.001): train_step=tf.train.GradientDescentOptimizer(lr).minimize(loss) return train_step path=r'C:\JC\test\train_model.ckpt' image,label=getinputs(r'C:\JC\tfrecord\64_shuffle/train.tfrecords') test_image,test_label=getinputs(r'C:\JC\tfrecord\64_shuffle/test.tfrecords') valid_image,valid_label= getinputs(r'C:\JC\tfrecord\64_shuffle\validation.tfrecords') batch_image,batch_label=get_batch(image,label,trainnum,0) work=trainwork() inf=work.inference(batch_image) loss=work.softmax_loss(inf,batch_label) opti=work.optimer(loss,learnrate) test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum) test_inf=work.test_inference(test_image_batch) test_labels=tf.one_hot(test_label_batch,classnum) test_pre = tf.reshape(test_inf, [testnum, classnum]) correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) test_pre = tf.argmax(test_pre, 1) test_true = tf.argmax(test_labels, 1) valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum) valid_inf=work.valid_inference(valid_image_batch) valid_labels=tf.one_hot(valid_label_batch,classnum) #train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy) valid_pre = tf.reshape(valid_inf, [validnum, classnum]) valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1)) valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32)) valid_pre = tf.argmax(valid_pre, 1) valid_true = tf.argmax(valid_labels, 1) target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj', 'class no', 'class yh', 'class fb'] init = tf.initialize_all_variables() config=tf.ConfigProto() config.gpu_options.allow_growth=True #init=tf.initialize_all_variables() def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False): with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) if restore: tf.train.Saver().restore(sess,path) feed_dict={ testnum: test_num, trainnum: train_num, learnrate:lr } for i in range(loop_count): loss_np, _, label_np, image_np, inf_np = sess.run( [loss, opti, batch_label, batch_image, inf],feed_dict=feed_dict) if i > 0 and i % report_step == 0: accuracy_np = sess.run([accuracy],feed_dict=feed_dict) print(i, accuracy_np, loss_np) if i > 0 and i % save_step == 0: tf.train.Saver().save(sess, path) tf.train.Saver().save(sess, path) coord.request_stop() coord.join(threads) def test_and_valid(test_loop=1,valid_loop=1,test_num=64,valid_num=64): feed_dict={ testnum: test_num, validnum: valid_num } with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) tf.train.Saver().restore(sess,path) #test test_acc_avg = 0.0 test_true_total=np.array([]) test_pre_total=np.array([]) for i in range(0, test_loop): accuracy_np = sess.run([accuracy],feed_dict=feed_dict) test_pre_1, test_true_1 = sess.run([test_pre, test_true],feed_dict=feed_dict) test_pre_1 = np.array(test_pre_1) test_true_1 = np.array(test_true_1) test_acc_avg = test_acc_avg + accuracy_np[0] test_true_total = np.concatenate((test_true_total,test_true_1),axis=0) test_pre_total = np.concatenate((test_pre_total,test_pre_1), axis=0) print('------test_accuracy-----') print(test_acc_avg / test_loop) print('------test_accuracy-----') print('------test_classification_report-----') print(classification_report(test_true_total, test_pre_total, target_names=target_names)) print('------test_classification_report-----') print('------test_confusion_matrix-----') cm = confusion_matrix(y_true=test_true_total, y_pred=test_pre_total) print(cm) print('------test_confusion_matrix-----') #valid if valid_loop>0: valid_acc_avg = 0.0 valid_true_total=np.array([]) valid_pre_total=np.array([]) for i in range(0, valid_loop): accuracy_np = sess.run([valid_accuracy],feed_dict=feed_dict) valid_pre_1, valid_true_1 = sess.run([valid_pre, valid_true],feed_dict=feed_dict) valid_pre_1 = np.array(valid_pre_1) valid_true_1 = np.array(valid_true_1) valid_acc_avg = valid_acc_avg + accuracy_np[0] valid_true_total = np.concatenate((valid_true_total,valid_true_1),axis=0) valid_pre_total = np.concatenate((valid_pre_total,valid_pre_1), axis=0) print('------valid_accuracy-----') print(valid_acc_avg / valid_loop) print('------valid_accuracy-----') print('------valid_classification_report-----') print(classification_report(valid_true_total, valid_pre_total, target_names=target_names)) print('------valid_classification_report-----') print('------valid_confusion_matrix-----') cm = confusion_matrix(y_true=valid_true_total, y_pred=valid_pre_total) print(cm) print('------valid_confusion_matrix-----') coord.request_stop() coord.join(threads) def predict_time(loop=100): feed_dict={ testnum:1 } with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) tf.train.Saver().restore(sess,path) total=0.0 for i in range(loop): a = datetime.now() accuracy_np = sess.run([accuracy],feed_dict=feed_dict) b = datetime.now() c = (b - a).microseconds total+=c print('predict_time(ms): ',total/(loop*1000)) coord.request_stop() coord.join(threads) train(train_num=128,loop_count=1200) test_and_valid(10,10,200,200) predict_time(1000)
[ "tensorflow.FixedLenFeature", "tensorflow.cast", "sklearn.metrics.confusion_matrix", "numpy.concatenate", "tensorflow.TFRecordReader", "tensorflow.train.batch", "sklearn.metrics.classification_report", "tensorflow.decode_raw", "tensorflow.ConfigProto", "tensorflow.initialize_all_variables", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.train.shuffle_batch", "tensorflow.matmul", "tensorflow.train.Coordinator", "tensorflow.placeholder", "tensorflow.train.GradientDescentOptimizer", "tensorflow.train.string_input_producer", "tensorflow.one_hot", "tensorflow.contrib.layers.xavier_initializer_conv2d", "numpy.array", "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.train.start_queue_runners", "tensorflow.reshape", "tensorflow.constant_initializer", "tensorflow.log", "tensorflow.variable_scope" ]
Model_Code/train_dnn_002.py
[(16, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.one_hot', 'tf.one_hot', (['test_label_batch', 'classnum'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.reshape', 'tf.reshape', (['test_inf', '[testnum, classnum]'], {}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.argmax', 'tf.argmax', (['test_pre', '(1)'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.argmax', 'tf.argmax', (['test_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.one_hot', 'tf.one_hot', (['valid_label_batch', 'classnum'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.reshape', 'tf.reshape', (['valid_inf', '[validnum, classnum]'], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.argmax', 'tf.argmax', (['valid_pre', '(1)'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.argmax', 'tf.argmax', (['valid_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (22, 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['[path]'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.decode_raw', 'tf.decode_raw', (["features['img_raw']", 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.cast', 'tf.cast', (["features['label']", 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.reshape', 'tf.reshape', (['image', '[4096, 1]'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.train.shuffle_batch', 'tf.train.shuffle_batch', (['[image, label]'], {'batch_size': 'batch_size', 'num_threads': '(10)', 'capacity': '(10000)', 'min_after_dequeue': '(200)'}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.train.batch', 'tf.train.batch', (['[image, label]'], {'batch_size': 'batch_size'}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.train.batch', 'tf.train.batch', (['[image, label]'], {'batch_size': 'batch_size'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.argmax', 'tf.argmax', (['test_inf', '(1)'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.argmax', 'tf.argmax', (['test_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.argmax', 'tf.argmax', (['valid_inf', '(1)'], {}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.argmax', 'tf.argmax', (['valid_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.cast', 'tf.cast', (['valid_correct_prediction', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['predicts'], {}), True, 'import tensorflow as tf\n'), (81, 'tensorflow.one_hot', 'tf.one_hot', (['labels', 'classnum'], {}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (159, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (164, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (165, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (183, 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'test_true_total', 'y_pred': 'test_pre_total'}), False, 'from sklearn.metrics import confusion_matrix\n'), (221, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""scop"""'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (73, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (169, 'numpy.array', 'np.array', (['test_pre_1'], {}), True, 'import numpy as np\n'), (170, 'numpy.array', 'np.array', (['test_true_1'], {}), True, 'import numpy as np\n'), (173, 'numpy.concatenate', 'np.concatenate', (['(test_true_total, test_true_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (174, 'numpy.concatenate', 'np.concatenate', (['(test_pre_total, test_pre_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (180, 'sklearn.metrics.classification_report', 'classification_report', (['test_true_total', 'test_pre_total'], {'target_names': 'target_names'}), False, 'from sklearn.metrics import classification_report\n'), (190, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (191, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (210, 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'valid_true_total', 'y_pred': 'valid_pre_total'}), False, 'from sklearn.metrics import confusion_matrix\n'), (228, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (230, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (27, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['lr'], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (195, 'numpy.array', 'np.array', (['valid_pre_1'], {}), True, 'import numpy as np\n'), (196, 'numpy.array', 'np.array', (['valid_true_1'], {}), True, 'import numpy as np\n'), (199, 'numpy.concatenate', 'np.concatenate', (['(valid_true_total, valid_true_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (200, 'numpy.concatenate', 'np.concatenate', (['(valid_pre_total, valid_pre_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (207, 'sklearn.metrics.classification_report', 'classification_report', (['valid_true_total', 'valid_pre_total'], {'target_names': 'target_names'}), False, 'from sklearn.metrics import classification_report\n'), (225, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (82, 'tensorflow.log', 'tf.log', (['predicts'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n')]
Brian-ZhenLiu/CNN_models
7cc646b181d86facf19b4129762504ea7b8f1409
import tensorflow as tf import os #from PIL import Image import random import numpy as np from datetime import datetime from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report slim = tf.contrib.slim global first first = True classnum=12 testnum = tf.placeholder(tf.int32) trainnum = tf.placeholder(tf.int32) validnum = tf.placeholder(tf.int32) learnrate = tf.placeholder(tf.float32) def getinputs(path): filename_queue=tf.train.string_input_producer([path]) reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1]) return image,label def get_batch(image,label,batch_size,crop_size): #print(image.shape) #print(label.shape) images,labels=tf.train.shuffle_batch([image,label], batch_size=batch_size,num_threads=10,capacity=10000,min_after_dequeue=200) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_test_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) def get_valid_batch(image,label,batch_size): images,labels=tf.train.batch([image,label],batch_size=batch_size) return tf.reshape(images,[batch_size,4096]),tf.reshape(labels,[batch_size]) class trainwork(object): def __init__(self): with tf.variable_scope('scop'): self.w1=tf.get_variable('w1', [4096,2048],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w2=tf.get_variable('w2', [2048,3072],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w3=tf.get_variable('w3', [3072,512],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.w4=tf.get_variable('w4', [512,classnum],initializer=tf.contrib.layers.xavier_initializer_conv2d()) self.b1 = tf.get_variable('b1', [2048],initializer=tf.constant_initializer(0.0)) self.b2 = tf.get_variable('b2', [3072],initializer=tf.constant_initializer(0.0)) self.b3 = tf.get_variable('b3', [512],initializer=tf.constant_initializer(0.0)) self.b4 = tf.get_variable('b4', [classnum],initializer=tf.constant_initializer(0.0)) def inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def test_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def valid_inference(self,images): images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def softmax_loss(self,predicts,labels): predicts=tf.nn.softmax(predicts) labels=tf.one_hot(labels,classnum) loss=-tf.reduce_sum(labels*tf.log(predicts)) return loss def optimer(self,loss,lr=0.001): train_step=tf.train.GradientDescentOptimizer(lr).minimize(loss) return train_step path=r'C:\JC\test\train_model.ckpt' image,label=getinputs(r'C:\JC\tfrecord\64_shuffle/train.tfrecords') test_image,test_label=getinputs(r'C:\JC\tfrecord\64_shuffle/test.tfrecords') valid_image,valid_label= getinputs(r'C:\JC\tfrecord\64_shuffle\validation.tfrecords') batch_image,batch_label=get_batch(image,label,trainnum,0) work=trainwork() inf=work.inference(batch_image) loss=work.softmax_loss(inf,batch_label) opti=work.optimer(loss,learnrate) test_image_batch,test_label_batch=get_test_batch(test_image,test_label,testnum) test_inf=work.test_inference(test_image_batch) test_labels=tf.one_hot(test_label_batch,classnum) test_pre = tf.reshape(test_inf, [testnum, classnum]) correct_prediction=tf.equal(tf.argmax(test_inf,1),tf.argmax(test_labels,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) test_pre = tf.argmax(test_pre, 1) test_true = tf.argmax(test_labels, 1) valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum) valid_inf=work.valid_inference(valid_image_batch) valid_labels=tf.one_hot(valid_label_batch,classnum) #train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy) valid_pre = tf.reshape(valid_inf, [validnum, classnum]) valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1)) valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32)) valid_pre = tf.argmax(valid_pre, 1) valid_true = tf.argmax(valid_labels, 1) target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj', 'class no', 'class yh', 'class fb'] init = tf.initialize_all_variables() config=tf.ConfigProto() config.gpu_options.allow_growth=True #init=tf.initialize_all_variables() def train(train_num=64,test_num=32,lr=1e-4,loop_count=10000,report_step=100,save_step=1000,restore=False): with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) if restore: tf.train.Saver().restore(sess,path) feed_dict={ testnum: test_num, trainnum: train_num, learnrate:lr } for i in range(loop_count): loss_np, _, label_np, image_np, inf_np = sess.run( [loss, opti, batch_label, batch_image, inf],feed_dict=feed_dict) if i > 0 and i % report_step == 0: accuracy_np = sess.run([accuracy],feed_dict=feed_dict) print(i, accuracy_np, loss_np) if i > 0 and i % save_step == 0: tf.train.Saver().save(sess, path) tf.train.Saver().save(sess, path) coord.request_stop() coord.join(threads) def test_and_valid(test_loop=1,valid_loop=1,test_num=64,valid_num=64): feed_dict={ testnum: test_num, validnum: valid_num } with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) tf.train.Saver().restore(sess,path) #test test_acc_avg = 0.0 test_true_total=np.array([]) test_pre_total=np.array([]) for i in range(0, test_loop): accuracy_np = sess.run([accuracy],feed_dict=feed_dict) test_pre_1, test_true_1 = sess.run([test_pre, test_true],feed_dict=feed_dict) test_pre_1 = np.array(test_pre_1) test_true_1 = np.array(test_true_1) test_acc_avg = test_acc_avg + accuracy_np[0] test_true_total = np.concatenate((test_true_total,test_true_1),axis=0) test_pre_total = np.concatenate((test_pre_total,test_pre_1), axis=0) print('------test_accuracy-----') print(test_acc_avg / test_loop) print('------test_accuracy-----') print('------test_classification_report-----') print(classification_report(test_true_total, test_pre_total, target_names=target_names)) print('------test_classification_report-----') print('------test_confusion_matrix-----') cm = confusion_matrix(y_true=test_true_total, y_pred=test_pre_total) print(cm) print('------test_confusion_matrix-----') #valid if valid_loop>0: valid_acc_avg = 0.0 valid_true_total=np.array([]) valid_pre_total=np.array([]) for i in range(0, valid_loop): accuracy_np = sess.run([valid_accuracy],feed_dict=feed_dict) valid_pre_1, valid_true_1 = sess.run([valid_pre, valid_true],feed_dict=feed_dict) valid_pre_1 = np.array(valid_pre_1) valid_true_1 = np.array(valid_true_1) valid_acc_avg = valid_acc_avg + accuracy_np[0] valid_true_total = np.concatenate((valid_true_total,valid_true_1),axis=0) valid_pre_total = np.concatenate((valid_pre_total,valid_pre_1), axis=0) print('------valid_accuracy-----') print(valid_acc_avg / valid_loop) print('------valid_accuracy-----') print('------valid_classification_report-----') print(classification_report(valid_true_total, valid_pre_total, target_names=target_names)) print('------valid_classification_report-----') print('------valid_confusion_matrix-----') cm = confusion_matrix(y_true=valid_true_total, y_pred=valid_pre_total) print(cm) print('------valid_confusion_matrix-----') coord.request_stop() coord.join(threads) def predict_time(loop=100): feed_dict={ testnum:1 } with tf.Session(config=config) as sess: sess.run(init) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) tf.train.Saver().restore(sess,path) total=0.0 for i in range(loop): a = datetime.now() accuracy_np = sess.run([accuracy],feed_dict=feed_dict) b = datetime.now() c = (b - a).microseconds total+=c print('predict_time(ms): ',total/(loop*1000)) coord.request_stop() coord.join(threads) train(train_num=128,loop_count=1200) test_and_valid(10,10,200,200) predict_time(1000)
[ "tensorflow.FixedLenFeature", "tensorflow.cast", "sklearn.metrics.confusion_matrix", "numpy.concatenate", "tensorflow.TFRecordReader", "tensorflow.train.batch", "sklearn.metrics.classification_report", "tensorflow.decode_raw", "tensorflow.ConfigProto", "tensorflow.initialize_all_variables", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.train.shuffle_batch", "tensorflow.matmul", "tensorflow.train.Coordinator", "tensorflow.placeholder", "tensorflow.train.GradientDescentOptimizer", "tensorflow.train.string_input_producer", "tensorflow.one_hot", "tensorflow.contrib.layers.xavier_initializer_conv2d", "numpy.array", "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.train.start_queue_runners", "tensorflow.reshape", "tensorflow.constant_initializer", "tensorflow.log", "tensorflow.variable_scope" ]
Model_Code/train_dnn_004.py
[(16, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.one_hot', 'tf.one_hot', (['test_label_batch', 'classnum'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.reshape', 'tf.reshape', (['test_inf', '[testnum, classnum]'], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.argmax', 'tf.argmax', (['test_pre', '(1)'], {}), True, 'import tensorflow as tf\n'), (123, 'tensorflow.argmax', 'tf.argmax', (['test_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.one_hot', 'tf.one_hot', (['valid_label_batch', 'classnum'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.reshape', 'tf.reshape', (['valid_inf', '[validnum, classnum]'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.argmax', 'tf.argmax', (['valid_pre', '(1)'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.argmax', 'tf.argmax', (['valid_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (138, 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (22, 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['[path]'], {}), True, 'import tensorflow as tf\n'), (23, 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.decode_raw', 'tf.decode_raw', (["features['img_raw']", 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.cast', 'tf.cast', (["features['label']", 'tf.int32'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.reshape', 'tf.reshape', (['image', '[4096, 1]'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.train.shuffle_batch', 'tf.train.shuffle_batch', (['[image, label]'], {'batch_size': 'batch_size', 'num_threads': '(10)', 'capacity': '(10000)', 'min_after_dequeue': '(200)'}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.train.batch', 'tf.train.batch', (['[image, label]'], {'batch_size': 'batch_size'}), True, 'import tensorflow as tf\n'), (47, 'tensorflow.train.batch', 'tf.train.batch', (['[image, label]'], {'batch_size': 'batch_size'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.argmax', 'tf.argmax', (['test_inf', '(1)'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.argmax', 'tf.argmax', (['test_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.argmax', 'tf.argmax', (['valid_inf', '(1)'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.argmax', 'tf.argmax', (['valid_labels', '(1)'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.cast', 'tf.cast', (['valid_correct_prediction', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.reshape', 'tf.reshape', (['images', '[batch_size, 4096]'], {}), True, 'import tensorflow as tf\n'), (48, 'tensorflow.reshape', 'tf.reshape', (['labels', '[batch_size]'], {}), True, 'import tensorflow as tf\n'), (65, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.nn.relu', 'tf.nn.relu', (['l2'], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.nn.relu', 'tf.nn.relu', (['l3'], {}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.nn.relu', 'tf.nn.relu', (['l2'], {}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.nn.relu', 'tf.nn.relu', (['l3'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.nn.relu', 'tf.nn.relu', (['l1'], {}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.nn.relu', 'tf.nn.relu', (['l2'], {}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.nn.relu', 'tf.nn.relu', (['l3'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['predicts'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.one_hot', 'tf.one_hot', (['labels', 'classnum'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (176, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (180, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (181, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (199, 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'test_true_total', 'y_pred': 'test_pre_total'}), False, 'from sklearn.metrics import confusion_matrix\n'), (237, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.train.Coordinator', 'tf.train.Coordinator', ([], {}), True, 'import tensorflow as tf\n'), (240, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'coord': 'coord'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""scop"""'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.matmul', 'tf.matmul', (['l2', 'self.w3'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.matmul', 'tf.matmul', (['l3', 'self.w4'], {}), True, 'import tensorflow as tf\n'), (74, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (77, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (79, 'tensorflow.matmul', 'tf.matmul', (['l2', 'self.w3'], {}), True, 'import tensorflow as tf\n'), (81, 'tensorflow.matmul', 'tf.matmul', (['l3', 'self.w4'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.matmul', 'tf.matmul', (['images', 'self.w1'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.matmul', 'tf.matmul', (['l1', 'self.w2'], {}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.matmul', 'tf.matmul', (['l2', 'self.w3'], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.matmul', 'tf.matmul', (['l3', 'self.w4'], {}), True, 'import tensorflow as tf\n'), (185, 'numpy.array', 'np.array', (['test_pre_1'], {}), True, 'import numpy as np\n'), (186, 'numpy.array', 'np.array', (['test_true_1'], {}), True, 'import numpy as np\n'), (189, 'numpy.concatenate', 'np.concatenate', (['(test_true_total, test_true_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (190, 'numpy.concatenate', 'np.concatenate', (['(test_pre_total, test_pre_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (196, 'sklearn.metrics.classification_report', 'classification_report', (['test_true_total', 'test_pre_total'], {'target_names': 'target_names'}), False, 'from sklearn.metrics import classification_report\n'), (206, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (207, 'numpy.array', 'np.array', (['[]'], {}), True, 'import numpy as np\n'), (226, 'sklearn.metrics.confusion_matrix', 'confusion_matrix', ([], {'y_true': 'valid_true_total', 'y_pred': 'valid_pre_total'}), False, 'from sklearn.metrics import confusion_matrix\n'), (244, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (246, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (27, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['lr'], {}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (211, 'numpy.array', 'np.array', (['valid_pre_1'], {}), True, 'import numpy as np\n'), (212, 'numpy.array', 'np.array', (['valid_true_1'], {}), True, 'import numpy as np\n'), (215, 'numpy.concatenate', 'np.concatenate', (['(valid_true_total, valid_true_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (216, 'numpy.concatenate', 'np.concatenate', (['(valid_pre_total, valid_pre_1)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (223, 'sklearn.metrics.classification_report', 'classification_report', (['valid_true_total', 'valid_pre_total'], {'target_names': 'target_names'}), False, 'from sklearn.metrics import classification_report\n'), (241, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (58, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (60, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.log', 'tf.log', (['predicts'], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (162, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n')]
danielgordon10/tensorflow
395cfc42ee3c5842f5383f4049674c012998b133
# 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. # ============================================================================== """A helper class for inferring Distribution shape.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util 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 class _DistributionShape(object): """Manage and manipulate `Distribution` shape. Terminology: Recall that a `Tensor` has: - `shape`: size of `Tensor` dimensions, - `ndims`: size of `shape`; number of `Tensor` dimensions, - `dims`: indexes into `shape`; useful for transpose, reduce. `Tensor`s sampled from a `Distribution` can be partitioned by `sample_dims`, `batch_dims`, and `event_dims`. To understand the semantics of these dimensions, consider when two of the three are fixed and the remaining is varied: - `sample_dims`: indexes independent draws from identical parameterizations of the `Distribution`. - `batch_dims`: indexes independent draws from non-identical parameterizations of the `Distribution`. - `event_dims`: indexes event coordinates from one sample. The `sample`, `batch`, and `event` dimensions constitute the entirety of a `Distribution` `Tensor`'s shape. The dimensions are always in `sample`, `batch`, `event` order. Purpose: This class partitions `Tensor` notions of `shape`, `ndims`, and `dims` into `Distribution` notions of `sample,` `batch,` and `event` dimensions. That is, it computes any of: ``` sample_shape batch_shape event_shape sample_dims batch_dims event_dims sample_ndims batch_ndims event_ndims ``` for a given `Tensor`, e.g., the result of `Distribution.sample(sample_shape=...)`. For a given `Tensor`, this class computes the above table using minimal information: `batch_ndims` and `event_ndims`. Examples of `Distribution` `shape` semantics: - Sample dimensions: Computing summary statistics, i.e., the average is a reduction over sample dimensions. ```python sample_dims = [0] tf.reduce_mean(Normal(mu=1.3, sigma=1.).sample_n(1000), reduction_indices=sample_dims) # ~= 1.3 ``` - Batch dimensions: Monte Carlo estimation of a marginal probability: Average over batch dimensions where batch dimensions are associated with random draws from a prior. E.g., suppose we want to find the Monte Carlo estimate of the marginal distribution of a `Normal` with a random `Laplace` location: ``` P(X=x) = integral P(X=x|y) P(Y=y) dy ~= 1/n sum_{i=1}^n P(X=x|y_i), y_i ~iid Laplace(0,1) = tf.reduce_mean(Normal(mu=Laplace(0., 1.).sample_n(n=1000), sigma=tf.ones(1000)).pdf(x), reduction_indices=batch_dims) ``` The `Laplace` distribution generates a `Tensor` of shape `[1000]`. When fed to a `Normal`, this is interpreted as 1000 different locations, i.e., 1000 non-identical Normals. Therefore a single call to `pdf(x)` yields 1000 probabilities, one for every location. The average over this batch yields the marginal. - Event dimensions: Computing the determinant of the Jacobian of a function of a random variable involves a reduction over event dimensions. E.g., Jacobian of the transform `Y = g(X) = exp(X)`: ```python tf.div(1., tf.reduce_prod(x, event_dims)) ``` Examples using this class: Write `S, B, E` for `sample_shape`, `batch_shape`, and `event_shape`. ```python # 150 iid samples from one multivariate Normal with two degrees of freedom. mu = [0., 0] sigma = [[1., 0], [0, 1]] mvn = MultivariateNormal(mu, sigma) rand_mvn = mvn.sample(sample_shape=[3, 50]) shaper = DistributionShape(batch_ndims=0, event_ndims=1) S, B, E = shaper.get_shape(rand_mvn) # S = [3, 50] # B = [] # E = [2] # 12 iid samples from one Wishart with 2x2 events. sigma = [[1., 0], [2, 1]] wishart = Wishart(df=5, scale=sigma) rand_wishart = wishart.sample(sample_shape=[3, 4]) shaper = DistributionShape(batch_ndims=0, event_ndims=2) S, B, E = shaper.get_shape(rand_wishart) # S = [3, 4] # B = [] # E = [2, 2] # 100 iid samples from two, non-identical trivariate Normal distributions. mu = ... # shape(2, 3) sigma = ... # shape(2, 3, 3) X = MultivariateNormal(mu, sigma).sample(shape=[4, 25]) # S = [4, 25] # B = [2] # E = [3] ``` Argument Validation: When `validate_args=False`, checks that cannot be done during graph construction are performed at graph execution. This may result in a performance degradation because data must be switched from GPU to CPU. For example, when `validate_args=False` and `event_ndims` is a non-constant `Tensor`, it is checked to be a non-negative integer at graph execution. (Same for `batch_ndims`). Constant `Tensor`s and non-`Tensor` arguments are always checked for correctness since this can be done for "free," i.e., during graph construction. """ def __init__(self, batch_ndims=None, event_ndims=None, validate_args=False, name="DistributionShape"): """Construct `DistributionShape` with fixed `batch_ndims`, `event_ndims`. `batch_ndims` and `event_ndims` are fixed throughout the lifetime of a `Distribution`. They may only be known at graph execution. If both `batch_ndims` and `event_ndims` are python scalars (rather than either being a `Tensor`), functions in this class automatically perform sanity checks during graph construction. Args: batch_ndims: `Tensor`. Number of `dims` (`rank`) of the batch portion of indexes of a `Tensor`. A "batch" is a non-identical distribution, i.e, Normal with different parameters. event_ndims: `Tensor`. Number of `dims` (`rank`) of the event portion of indexes of a `Tensor`. An "event" is what is sampled from a distribution, i.e., a trivariate Normal has an event shape of [3] and a 4 dimensional Wishart has an event shape of [4, 4]. validate_args: `Boolean`, default `False`. When `True`, non-`tf.constant` `Tensor` arguments are checked for correctness. (`tf.constant` arguments are always checked.) name: `String`. The name prepended to Ops created by this class. Raises: ValueError: if either `batch_ndims` or `event_ndims` are: `None`, negative, not `int32`. """ if batch_ndims is None: raise ValueError("batch_ndims cannot be None") if event_ndims is None: raise ValueError("event_ndims cannot be None") self._batch_ndims = batch_ndims self._event_ndims = event_ndims self._validate_args = validate_args with ops.name_scope(name) as ns: self._name = ns with ops.name_scope("init"): self._batch_ndims = self._assert_non_negative_int32_scalar( ops.convert_to_tensor( batch_ndims, name="batch_ndims")) self._batch_ndims_static, self._batch_ndims_is_0 = ( self._introspect_ndims(self._batch_ndims)) self._event_ndims = self._assert_non_negative_int32_scalar( ops.convert_to_tensor( event_ndims, name="event_ndims")) self._event_ndims_static, self._event_ndims_is_0 = ( self._introspect_ndims(self._event_ndims)) @property def name(self): """Name given to ops created by this class.""" return self._name @property def batch_ndims(self): """Returns number of dimensions corresponding to non-identical draws.""" return self._batch_ndims @property def event_ndims(self): """Returns number of dimensions needed to index a sample's coordinates.""" return self._event_ndims @property def validate_args(self): """Returns True if graph-runtime `Tensor` checks are enabled.""" return self._validate_args def get_ndims(self, x, name="get_ndims"): """Get `Tensor` number of dimensions (rank). Args: x: `Tensor`. name: `String`. The name to give this op. Returns: ndims: Scalar number of dimensions associated with a `Tensor`. """ with self._name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") ndims = x.get_shape().ndims if ndims is None: return array_ops.rank(x, name="ndims") return ops.convert_to_tensor(ndims, dtype=dtypes.int32, name="ndims") def get_sample_ndims(self, x, name="get_sample_ndims"): """Returns number of dimensions corresponding to iid draws ("sample"). Args: x: `Tensor`. name: `String`. The name to give this op. Returns: sample_ndims: `Tensor` (0D, `int32`). Raises: ValueError: if `sample_ndims` is calculated to be negative. """ with self._name_scope(name, values=[x]): ndims = self.get_ndims(x, name=name) if self._is_all_constant_helper(ndims, self.batch_ndims, self.event_ndims): ndims = tensor_util.constant_value(ndims) sample_ndims = (ndims - self._batch_ndims_static - self._event_ndims_static) if sample_ndims < 0: raise ValueError( "expected batch_ndims(%d) + event_ndims(%d) <= ndims(%d)" % (self._batch_ndims_static, self._event_ndims_static, ndims)) return ops.convert_to_tensor(sample_ndims, name="sample_ndims") else: with ops.name_scope(name="sample_ndims"): sample_ndims = ndims - self.batch_ndims - self.event_ndims if self.validate_args: sample_ndims = control_flow_ops.with_dependencies( [check_ops.assert_non_negative(sample_ndims)], sample_ndims) return sample_ndims def get_dims(self, x, name="get_dims"): """Returns dimensions indexing `sample_shape`, `batch_shape`, `event_shape`. Example: ```python x = ... # Tensor with shape [4, 3, 2, 1] sample_dims, batch_dims, event_dims = _DistributionShape( batch_ndims=2, event_ndims=1).get_dims(x) # sample_dims == [0] # batch_dims == [1, 2] # event_dims == [3] # Note that these are not the shape parts, but rather indexes into shape. ``` Args: x: `Tensor`. name: `String`. The name to give this op. Returns: sample_dims: `Tensor` (1D, `int32`). batch_dims: `Tensor` (1D, `int32`). event_dims: `Tensor` (1D, `int32`). """ with self._name_scope(name, values=[x]): def make_dims(start_sum, size, name): """Closure to make dims range.""" start_sum = start_sum if start_sum else ( array_ops.zeros((), dtype=dtypes.int32, name="zero"),) if self._is_all_constant_helper(size, *start_sum): start = sum(tensor_util.constant_value(s) for s in start_sum) stop = start + tensor_util.constant_value(size) return ops.convert_to_tensor( list(range(start, stop)), dtype=dtypes.int32, name=name) else: start = sum(start_sum) return math_ops.range(start, start + size) sample_ndims = self.get_sample_ndims(x, name=name) return (make_dims((), sample_ndims, name="sample_dims"), make_dims((sample_ndims,), self.batch_ndims, name="batch_dims"), make_dims((sample_ndims, self.batch_ndims), self.event_ndims, name="event_dims")) def get_shape(self, x, name="get_shape"): """Returns `Tensor`'s shape partitioned into `sample`, `batch`, `event`. Args: x: `Tensor`. name: `String`. The name to give this op. Returns: sample_shape: `Tensor` (1D, `int32`). batch_shape: `Tensor` (1D, `int32`). event_shape: `Tensor` (1D, `int32`). """ with self._name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") def slice_shape(start_sum, size, name): """Closure to slice out shape.""" start_sum = start_sum if start_sum else ( array_ops.zeros((), dtype=dtypes.int32, name="zero"),) if (x.get_shape().ndims is not None and self._is_all_constant_helper(size, *start_sum)): start = sum(tensor_util.constant_value(s) for s in start_sum) stop = start + tensor_util.constant_value(size) slice_ = x.get_shape()[start:stop].as_list() if all(s is not None for s in slice_): return ops.convert_to_tensor(slice_, dtype=dtypes.int32, name=name) # Fall-through intended. return array_ops.slice(array_ops.shape(x), (sum(start_sum),), (size,)) sample_ndims = self.get_sample_ndims(x, name=name) return (slice_shape((), sample_ndims, name="sample_shape"), slice_shape((sample_ndims,), self.batch_ndims, name="batch_shape"), slice_shape((sample_ndims, self.batch_ndims), self.event_ndims, name="event_shape")) def make_batch_of_event_sample_matrices( self, x, name="make_batch_of_event_sample_matrices"): """Reshapes/transposes `Distribution` `Tensor` from S+B+E to B_+E_+S_. Where: - `B_ = B if B else [1]`, - `E_ = E if E else [1]`, - `S_ = [tf.reduce_prod(S)]`. Args: x: `Tensor`. name: `String`. The name to give this op. Returns: x: `Tensor`. Input transposed/reshaped to `B_+E_+S_`. sample_shape: `Tensor` (1D, `int32`). """ with self._name_scope(name, values=[x]): x = ops.convert_to_tensor(x, name="x") sample_shape, batch_shape, event_shape = self.get_shape(x) event_shape = distribution_util.pick_vector( self._event_ndims_is_0, (1,), event_shape) batch_shape = distribution_util.pick_vector( self._batch_ndims_is_0, (1,), batch_shape) new_shape = array_ops.concat(0, ((-1,), batch_shape, event_shape)) x = array_ops.reshape(x, shape=new_shape) x = distribution_util.rotate_transpose(x, shift=-1) return x, sample_shape def undo_make_batch_of_event_sample_matrices( self, x, sample_shape, name="undo_make_batch_of_event_sample_matrices"): """Reshapes/transposes `Distribution` `Tensor` from B_+E_+S_ to S+B+E. Where: - `B_ = B if B else [1]`, - `E_ = E if E else [1]`, - `S_ = [tf.reduce_prod(S)]`. This function "reverses" `make_batch_of_event_sample_matrices`. Args: x: `Tensor` of shape `B_+E_+S_`. sample_shape: `Tensor` (1D, `int32`). name: `String`. The name to give this op. Returns: x: `Tensor`. Input transposed/reshaped to `S+B+E`. """ with self._name_scope(name, values=[x, sample_shape]): x = ops.convert_to_tensor(x, name="x") sample_shape = ops.convert_to_tensor(sample_shape, name="sample_shape") x = distribution_util.rotate_transpose(x, shift=1) if self._is_all_constant_helper(self.batch_ndims, self.event_ndims): if self._batch_ndims_is_0 or self._event_ndims_is_0: b = ((min(-2, -1 - self._event_ndims_static),) if self._batch_ndims_is_0 else ()) e = (-1,) if self._event_ndims_is_0 else () x = array_ops.squeeze(x, squeeze_dims=b + e) _, batch_shape, event_shape = self.get_shape(x) else: s = (x.get_shape().as_list() if x.get_shape().is_fully_defined() else array_ops.shape(x)) batch_shape = array_ops.slice(s, (1,), (self.batch_ndims,)) # Since sample_dims=1 and is left-most, we add 1 to the number of # batch_ndims to get the event start dim. event_start = array_ops.where( self._batch_ndims_is_0, 2, 1 + self.batch_ndims) event_shape = array_ops.slice(s, (event_start,), (self.event_ndims,)) new_shape = array_ops.concat(0, (sample_shape, batch_shape, event_shape)) x = array_ops.reshape(x, shape=new_shape) return x @contextlib.contextmanager def _name_scope(self, name=None, values=None): """Helper function to standardize op scope.""" with ops.name_scope(self.name): with ops.name_scope(name, values=( (values or []) + [self.batch_ndims, self.event_ndims])) as scope: yield scope def _is_all_constant_helper(self, *args): """Helper which returns True if all inputs are constant_value.""" return all(tensor_util.constant_value(x) is not None for x in args) def _assert_non_negative_int32_scalar(self, x): """Helper which ensures that input is a non-negative, int32, scalar.""" x = ops.convert_to_tensor(x, name="x") if x.dtype.base_dtype != dtypes.int32.base_dtype: raise TypeError("%s.dtype=%s is not %s" % (x.name, x.dtype, dtypes.int32)) x_value_static = tensor_util.constant_value(x) if x.get_shape().ndims is not None and x_value_static is not None: if x.get_shape().ndims != 0: raise ValueError("%s.ndims=%d is not 0 (scalar)" % (x.name, x.get_shape().ndims)) if x_value_static < 0: raise ValueError("%s.value=%d cannot be negative" % (x.name, x_value_static)) return x if self.validate_args: x = control_flow_ops.with_dependencies([ check_ops.assert_rank(x, 0), check_ops.assert_non_negative(x)], x) return x def _introspect_ndims(self, ndims): """Helper to establish some properties of input ndims args.""" if self._is_all_constant_helper(ndims): return (tensor_util.constant_value(ndims), tensor_util.constant_value(ndims) == 0) return None, math_ops.equal(ndims, 0)
[ "tensorflow.contrib.distributions.python.ops.distribution_util.pick_vector", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.check_ops.assert_rank", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.slice", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.where", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.contrib.distributions.python.ops.distribution_util.rotate_transpose", "tensorflow.python.ops.check_ops.assert_non_negative" ]
tensorflow/contrib/distributions/python/ops/shape.py
[(446, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (449, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['x'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (198, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name'], {}), False, 'from tensorflow.python.framework import ops\n'), (243, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (247, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['ndims'], {'dtype': 'dtypes.int32', 'name': '"""ndims"""'}), False, 'from tensorflow.python.framework import ops\n'), (338, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (378, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (380, 'tensorflow.contrib.distributions.python.ops.distribution_util.pick_vector', 'distribution_util.pick_vector', (['self._event_ndims_is_0', '(1,)', 'event_shape'], {}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (382, 'tensorflow.contrib.distributions.python.ops.distribution_util.pick_vector', 'distribution_util.pick_vector', (['self._batch_ndims_is_0', '(1,)', 'batch_shape'], {}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (384, 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['(0)', '((-1,), batch_shape, event_shape)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (385, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['x'], {'shape': 'new_shape'}), False, 'from tensorflow.python.ops import array_ops\n'), (386, 'tensorflow.contrib.distributions.python.ops.distribution_util.rotate_transpose', 'distribution_util.rotate_transpose', (['x'], {'shift': '(-1)'}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (409, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['x'], {'name': '"""x"""'}), False, 'from tensorflow.python.framework import ops\n'), (410, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['sample_shape'], {'name': '"""sample_shape"""'}), False, 'from tensorflow.python.framework import ops\n'), (411, 'tensorflow.contrib.distributions.python.ops.distribution_util.rotate_transpose', 'distribution_util.rotate_transpose', (['x'], {'shift': '(1)'}), False, 'from tensorflow.contrib.distributions.python.ops import distribution_util\n'), (428, 'tensorflow.python.ops.array_ops.concat', 'array_ops.concat', (['(0)', '(sample_shape, batch_shape, event_shape)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (429, 'tensorflow.python.ops.array_ops.reshape', 'array_ops.reshape', (['x'], {'shape': 'new_shape'}), False, 'from tensorflow.python.ops import array_ops\n'), (435, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['self.name'], {}), False, 'from tensorflow.python.framework import ops\n'), (469, 'tensorflow.python.ops.math_ops.equal', 'math_ops.equal', (['ndims', '(0)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (200, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['"""init"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (246, 'tensorflow.python.ops.array_ops.rank', 'array_ops.rank', (['x'], {'name': '"""ndims"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (266, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['ndims'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (273, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['sample_ndims'], {'name': '"""sample_ndims"""'}), False, 'from tensorflow.python.framework import ops\n'), (422, 'tensorflow.python.ops.array_ops.slice', 'array_ops.slice', (['s', '(1,)', '(self.batch_ndims,)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (425, 'tensorflow.python.ops.array_ops.where', 'array_ops.where', (['self._batch_ndims_is_0', '(2)', '(1 + self.batch_ndims)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (427, 'tensorflow.python.ops.array_ops.slice', 'array_ops.slice', (['s', '(event_start,)', '(self.event_ndims,)'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (436, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', (['name'], {'values': '((values or []) + [self.batch_ndims, self.event_ndims])'}), False, 'from tensorflow.python.framework import ops\n'), (467, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['ndims'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (202, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['batch_ndims'], {'name': '"""batch_ndims"""'}), False, 'from tensorflow.python.framework import ops\n'), (207, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['event_ndims'], {'name': '"""event_ndims"""'}), False, 'from tensorflow.python.framework import ops\n'), (275, 'tensorflow.python.framework.ops.name_scope', 'ops.name_scope', ([], {'name': '"""sample_ndims"""'}), False, 'from tensorflow.python.framework import ops\n'), (318, 'tensorflow.python.ops.math_ops.range', 'math_ops.range', (['start', '(start + size)'], {}), False, 'from tensorflow.python.ops import math_ops\n'), (351, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['x'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (417, 'tensorflow.python.ops.array_ops.squeeze', 'array_ops.squeeze', (['x'], {'squeeze_dims': '(b + e)'}), False, 'from tensorflow.python.ops import array_ops\n'), (421, 'tensorflow.python.ops.array_ops.shape', 'array_ops.shape', (['x'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (442, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['x'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (460, 'tensorflow.python.ops.check_ops.assert_rank', 'check_ops.assert_rank', (['x', '(0)'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (461, 'tensorflow.python.ops.check_ops.assert_non_negative', 'check_ops.assert_non_negative', (['x'], {}), False, 'from tensorflow.python.ops import check_ops\n'), (468, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['ndims'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (310, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['()'], {'dtype': 'dtypes.int32', 'name': '"""zero"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (313, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['size'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (342, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['()'], {'dtype': 'dtypes.int32', 'name': '"""zero"""'}), False, 'from tensorflow.python.ops import array_ops\n'), (346, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['size'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (349, 'tensorflow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', (['slice_'], {'dtype': 'dtypes.int32', 'name': 'name'}), False, 'from tensorflow.python.framework import ops\n'), (312, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['s'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (345, 'tensorflow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', (['s'], {}), False, 'from tensorflow.python.framework import tensor_util\n'), (279, 'tensorflow.python.ops.check_ops.assert_non_negative', 'check_ops.assert_non_negative', (['sample_ndims'], {}), False, 'from tensorflow.python.ops import check_ops\n')]
danielgordon10/tensorflow
395cfc42ee3c5842f5383f4049674c012998b133
# 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 functional style sequence-to-sequence models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import random import numpy as np import tensorflow as tf class Seq2SeqTest(tf.test.TestCase): def testRNNDecoder(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 _, enc_state = tf.nn.rnn( tf.nn.rnn_cell.GRUCell(2), inp, dtype=tf.float32) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 cell = tf.nn.rnn_cell.OutputProjectionWrapper( tf.nn.rnn_cell.GRUCell(2), 4) dec, mem = tf.nn.seq2seq.rnn_decoder(dec_inp, enc_state, cell) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testBasicRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 cell = tf.nn.rnn_cell.OutputProjectionWrapper( tf.nn.rnn_cell.GRUCell(2), 4) dec, mem = tf.nn.seq2seq.basic_rnn_seq2seq(inp, dec_inp, cell) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testTiedRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 cell = tf.nn.rnn_cell.OutputProjectionWrapper( tf.nn.rnn_cell.GRUCell(2), 4) dec, mem = tf.nn.seq2seq.tied_rnn_seq2seq(inp, dec_inp, cell) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(1, len(res)) self.assertEqual((2, 2), res[0].shape) def testEmbeddingRNNDecoder(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) _, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] dec, mem = tf.nn.seq2seq.embedding_rnn_decoder( dec_inp, enc_state, cell, num_symbols=4, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) res = sess.run([mem]) self.assertEqual(1, len(res)) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) def testEmbeddingRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with tf.variable_scope("no_tuple"): cell1 = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell1, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testEmbeddingTiedRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) dec, mem = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test when num_decoder_symbols is provided, the size of decoder output # is num_decoder_symbols. with tf.variable_scope("decoder_symbols_seq2seq"): dec, mem = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, num_decoder_symbols=3, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 3), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2])] * 3 with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testAttentionDecoder1(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testAttentionDecoder2(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4, num_heads=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testDynamicAttentionDecoder1(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = tf.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32) attn_states = enc_outputs dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testDynamicAttentionDecoder2(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = tf.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = tf.nn.dynamic_rnn(cell, inp, dtype=tf.float32) attn_states = enc_outputs dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4, num_heads=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testAttentionDecoderStateIsTuple(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2, state_is_tuple=True) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(2, len(res[0])) self.assertEqual((2, 2), res[0][0].c.shape) self.assertEqual((2, 2), res[0][0].h.shape) self.assertEqual((2, 2), res[0][1].c.shape) self.assertEqual((2, 2), res[0][1].h.shape) # pylint: disable=unused-variable,invalid-name def testDynamicAttentionDecoderStateIsTuple(self): with self.test_session() as sess: with tf.variable_scope( "root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) cell = tf.nn.rnn_cell.MultiRNNCell(cells=[cell] * 2, state_is_tuple=True) inp = tf.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(2, len(res[0])) self.assertEqual((2, 2), res[0][0].c.shape) self.assertEqual((2, 2), res[0][0].h.shape) self.assertEqual((2, 2), res[0][1].c.shape) self.assertEqual((2, 2), res[0][1].h.shape) def testEmbeddingAttentionDecoder(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 cell = tf.nn.rnn_cell.GRUCell(2) enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] dec, mem = tf.nn.seq2seq.embedding_attention_decoder( dec_inp, enc_state, attn_states, cell, num_symbols=4, embedding_size=2, output_size=3) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 3), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testEmbeddingAttentionSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with tf.variable_scope("no_tuple"): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testOne2ManyRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): enc_inp = [tf.constant(1, tf.int32, shape=[2]) for i in range(2)] dec_inp_dict = {} dec_inp_dict["0"] = [ tf.constant(i, tf.int32, shape=[2]) for i in range(3)] dec_inp_dict["1"] = [ tf.constant(i, tf.int32, shape=[2]) for i in range(4)] dec_symbols_dict = {"0": 5, "1": 6} cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) outputs_dict, state_dict = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(outputs_dict["0"]) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run(outputs_dict["1"]) self.assertEqual(4, len(res)) self.assertEqual((2, 6), res[0].shape) res = sess.run([state_dict["0"]]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) res = sess.run([state_dict["1"]]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test that previous-feeding model ignores inputs after the first, i.e. # dec_inp_dict2 has different inputs from dec_inp_dict after the first # time-step. dec_inp_dict2 = {} dec_inp_dict2["0"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] dec_inp_dict2["1"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(4)] with tf.variable_scope("other"): outputs_dict3, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() outputs_dict1, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) outputs_dict2, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) res1 = sess.run(outputs_dict1["0"]) res2 = sess.run(outputs_dict2["0"]) res3 = sess.run(outputs_dict3["0"]) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testSequenceLoss(self): with self.test_session() as sess: logits = [tf.constant(i + 0.5, shape=[2, 5]) for i in range(3)] targets = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] weights = [tf.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = tf.nn.seq2seq.sequence_loss( logits, targets, weights, average_across_timesteps=True, average_across_batch=True) res = sess.run(average_loss_per_example) self.assertAllClose(1.60944, res) average_loss_per_sequence = tf.nn.seq2seq.sequence_loss( logits, targets, weights, average_across_timesteps=False, average_across_batch=True) res = sess.run(average_loss_per_sequence) self.assertAllClose(4.828314, res) total_loss = tf.nn.seq2seq.sequence_loss( logits, targets, weights, average_across_timesteps=False, average_across_batch=False) res = sess.run(total_loss) self.assertAllClose(9.656628, res) def testSequenceLossByExample(self): with self.test_session() as sess: output_classes = 5 logits = [tf.constant(i + 0.5, shape=[2, output_classes]) for i in range(3)] targets = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] weights = [tf.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = tf.nn.seq2seq.sequence_loss_by_example( logits, targets, weights, average_across_timesteps=True) res = sess.run(average_loss_per_example) self.assertAllClose(np.asarray([1.609438, 1.609438]), res) loss_per_sequence = tf.nn.seq2seq.sequence_loss_by_example( logits, targets, weights, average_across_timesteps=False) res = sess.run(loss_per_sequence) self.assertAllClose(np.asarray([4.828314, 4.828314]), res) def testModelWithBucketsScopeAndLoss(self): """Test that variable scope reuse is not reset after model_with_buckets.""" classes = 10 buckets = [(4, 4), (8, 8)] with self.test_session(): # Here comes a sample Seq2Seq model using GRU cells. def SampleGRUSeq2Seq(enc_inp, dec_inp, weights, per_example_loss): """Example sequence-to-sequence model that uses GRU cells.""" def GRUSeq2Seq(enc_inp, dec_inp): cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2, state_is_tuple=True) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=classes, num_decoder_symbols=classes, embedding_size=24) targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0] return tf.nn.seq2seq.model_with_buckets( enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq, per_example_loss=per_example_loss) # Now we construct the copy model. inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)] with tf.variable_scope("root"): _, losses1 = SampleGRUSeq2Seq(inp, out, weights, per_example_loss=False) # Now check that we did not accidentally set reuse. self.assertEqual(False, tf.get_variable_scope().reuse) # Construct one more model with per-example loss. tf.get_variable_scope().reuse_variables() _, losses2 = SampleGRUSeq2Seq(inp, out, weights, per_example_loss=True) # First loss is scalar, the second one is a 1-dimensinal tensor. self.assertEqual([], losses1[0].get_shape().as_list()) self.assertEqual([None], losses2[0].get_shape().as_list()) def testModelWithBuckets(self): """Larger tests that does full sequence-to-sequence model training.""" # We learn to copy 10 symbols in 2 buckets: length 4 and length 8. classes = 10 buckets = [(4, 4), (8, 8)] perplexities = [[], []] # Results for each bucket. tf.set_random_seed(111) random.seed(111) np.random.seed(111) with self.test_session() as sess: # We use sampled softmax so we keep output projection separate. w = tf.get_variable("proj_w", [24, classes]) w_t = tf.transpose(w) b = tf.get_variable("proj_b", [classes]) # Here comes a sample Seq2Seq model using GRU cells. def SampleGRUSeq2Seq(enc_inp, dec_inp, weights): """Example sequence-to-sequence model that uses GRU cells.""" def GRUSeq2Seq(enc_inp, dec_inp): cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2, state_is_tuple=True) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=classes, num_decoder_symbols=classes, embedding_size=24, output_projection=(w, b)) targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0] def SampledLoss(labels, inputs): labels = tf.reshape(labels, [-1, 1]) return tf.nn.sampled_softmax_loss(w_t, b, inputs, labels, 8, classes) return tf.nn.seq2seq.model_with_buckets( enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq, softmax_loss_function=SampledLoss) # Now we construct the copy model. batch_size = 8 inp = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] out = [tf.placeholder(tf.int32, shape=[None]) for _ in range(8)] weights = [tf.ones_like(inp[0], dtype=tf.float32) for _ in range(8)] with tf.variable_scope("root"): _, losses = SampleGRUSeq2Seq(inp, out, weights) updates = [] params = tf.global_variables() optimizer = tf.train.AdamOptimizer(0.03, epsilon=1e-5) for i in range(len(buckets)): full_grads = tf.gradients(losses[i], params) grads, _ = tf.clip_by_global_norm(full_grads, 30.0) update = optimizer.apply_gradients(zip(grads, params)) updates.append(update) sess.run([tf.global_variables_initializer()]) steps = 6 for _ in range(steps): bucket = random.choice(np.arange(len(buckets))) length = buckets[bucket][0] i = [np.array([np.random.randint(9) + 1 for _ in range(batch_size)], dtype=np.int32) for _ in range(length)] # 0 is our "GO" symbol here. o = [np.array([0] * batch_size, dtype=np.int32)] + i feed = {} for i1, i2, o1, o2 in zip(inp[:length], i[:length], out[:length], o[:length]): feed[i1.name] = i2 feed[o1.name] = o2 if length < 8: # For the 4-bucket, we need the 5th as target. feed[out[length].name] = o[length] res = sess.run([updates[bucket], losses[bucket]], feed) perplexities[bucket].append(math.exp(float(res[1]))) for bucket in range(len(buckets)): if len(perplexities[bucket]) > 1: # Assert that perplexity went down. self.assertLess(perplexities[bucket][-1], perplexities[bucket][0]) def testModelWithBooleanFeedPrevious(self): """Test the model behavior when feed_previous is True. For example, the following two cases have the same effect: - Train `embedding_rnn_seq2seq` with `feed_previous=True`, which contains a `embedding_rnn_decoder` with `feed_previous=True` and `update_embedding_for_previous=True`. The decoder is fed with "<Go>" and outputs "A, B, C". - Train `embedding_rnn_seq2seq` with `feed_previous=False`. The decoder is fed with "<Go>, A, B". """ num_encoder_symbols = 3 num_decoder_symbols = 5 batch_size = 2 num_enc_timesteps = 2 num_dec_timesteps = 3 def TestModel(seq2seq): with self.test_session(graph=tf.Graph()) as sess: tf.set_random_seed(111) random.seed(111) np.random.seed(111) enc_inp = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_enc_timesteps)] dec_inp_fp_true = [tf.constant(i, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] dec_inp_holder_fp_false = [tf.placeholder(tf.int32, shape=[batch_size]) for _ in range(num_dec_timesteps)] targets = [tf.constant(i + 1, tf.int32, shape=[batch_size]) for i in range(num_dec_timesteps)] weights = [tf.constant(1.0, shape=[batch_size]) for i in range(num_dec_timesteps)] def ForwardBackward(enc_inp, dec_inp, feed_previous): scope_name = "fp_{}".format(feed_previous) with tf.variable_scope(scope_name): dec_op, _ = seq2seq(enc_inp, dec_inp, feed_previous=feed_previous) net_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope_name) optimizer = tf.train.AdamOptimizer(0.03, epsilon=1e-5) update_op = optimizer.minimize( tf.nn.seq2seq.sequence_loss(dec_op, targets, weights), var_list=net_variables) return dec_op, update_op, net_variables dec_op_fp_true, update_fp_true, variables_fp_true = ForwardBackward( enc_inp, dec_inp_fp_true, feed_previous=True) _, update_fp_false, variables_fp_false = ForwardBackward( enc_inp, dec_inp_holder_fp_false, feed_previous=False) sess.run(tf.global_variables_initializer()) # We only check consistencies between the variables existing in both # the models with True and False feed_previous. Variables created by # the loop_function in the model with True feed_previous are ignored. v_false_name_dict = {v.name.split("/", 1)[-1]: v for v in variables_fp_false} matched_variables = [(v, v_false_name_dict[v.name.split("/", 1)[-1]]) for v in variables_fp_true] for v_true, v_false in matched_variables: sess.run(tf.assign(v_false, v_true)) # Take the symbols generated by the decoder with feed_previous=True as # the true input symbols for the decoder with feed_previous=False. dec_fp_true = sess.run(dec_op_fp_true) output_symbols_fp_true = np.argmax(dec_fp_true, axis=2) dec_inp_fp_false = np.vstack((dec_inp_fp_true[0].eval(), output_symbols_fp_true[:-1])) sess.run(update_fp_true) sess.run(update_fp_false, {holder: inp for holder, inp in zip(dec_inp_holder_fp_false, dec_inp_fp_false)}) for v_true, v_false in matched_variables: self.assertAllClose(v_true.eval(), v_false.eval()) def EmbeddingRNNSeq2SeqF(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) return tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingRNNSeq2SeqNoTupleF(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) return tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingTiedRNNSeq2Seq(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) return tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingTiedRNNSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) return tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingAttentionSeq2Seq(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=True) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingAttentionSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) for model in (EmbeddingRNNSeq2SeqF, EmbeddingRNNSeq2SeqNoTupleF, EmbeddingTiedRNNSeq2Seq, EmbeddingTiedRNNSeq2SeqNoTuple, EmbeddingAttentionSeq2Seq, EmbeddingAttentionSeq2SeqNoTuple): TestModel(model) if __name__ == "__main__": tf.test.main()
[ "tensorflow.get_variable", "tensorflow.nn.dynamic_rnn", "numpy.asarray", "tensorflow.global_variables", "tensorflow.train.AdamOptimizer", "numpy.random.randint", "tensorflow.nn.seq2seq.model_with_buckets", "tensorflow.Graph", "tensorflow.nn.seq2seq.one2many_rnn_seq2seq", "tensorflow.get_collection", "tensorflow.nn.seq2seq.embedding_attention_seq2seq", "tensorflow.test.main", "tensorflow.gradients", "numpy.argmax", "tensorflow.nn.seq2seq.embedding_rnn_decoder", "tensorflow.nn.rnn_cell.MultiRNNCell", "tensorflow.nn.seq2seq.embedding_attention_decoder", "tensorflow.nn.seq2seq.sequence_loss", "tensorflow.nn.rnn_cell.GRUCell", "tensorflow.nn.rnn_cell.BasicLSTMCell", "tensorflow.nn.seq2seq.attention_decoder", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.nn.seq2seq.rnn_decoder", "tensorflow.nn.seq2seq.embedding_rnn_seq2seq", "tensorflow.set_random_seed", "numpy.array", "tensorflow.nn.seq2seq.sequence_loss_by_example", "tensorflow.nn.seq2seq.tied_rnn_seq2seq", "tensorflow.nn.seq2seq.basic_rnn_seq2seq", "tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq", "tensorflow.transpose", "tensorflow.constant", "numpy.random.seed", "tensorflow.nn.rnn", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.assign", "tensorflow.nn.sampled_softmax_loss", "tensorflow.constant_initializer", "tensorflow.clip_by_global_norm", "tensorflow.variable_scope", "tensorflow.get_variable_scope" ]
tensorflow/python/kernel_tests/seq2seq_test.py
[(770, 'tensorflow.test.main', 'tf.test.main', ([], {}), True, 'import tensorflow as tf\n'), (586, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(111)'], {}), True, 'import tensorflow as tf\n'), (587, 'random.seed', 'random.seed', (['(111)'], {}), False, 'import random\n'), (588, 'numpy.random.seed', 'np.random.seed', (['(111)'], {}), True, 'import numpy as np\n'), (504, 'tensorflow.nn.seq2seq.sequence_loss', 'tf.nn.seq2seq.sequence_loss', (['logits', 'targets', 'weights'], {'average_across_timesteps': '(True)', 'average_across_batch': '(True)'}), True, 'import tensorflow as tf\n'), (511, 'tensorflow.nn.seq2seq.sequence_loss', 'tf.nn.seq2seq.sequence_loss', (['logits', 'targets', 'weights'], {'average_across_timesteps': '(False)', 'average_across_batch': '(True)'}), True, 'import tensorflow as tf\n'), (518, 'tensorflow.nn.seq2seq.sequence_loss', 'tf.nn.seq2seq.sequence_loss', (['logits', 'targets', 'weights'], {'average_across_timesteps': '(False)', 'average_across_batch': '(False)'}), True, 'import tensorflow as tf\n'), (533, 'tensorflow.nn.seq2seq.sequence_loss_by_example', 'tf.nn.seq2seq.sequence_loss_by_example', (['logits', 'targets', 'weights'], {'average_across_timesteps': '(True)'}), True, 'import tensorflow as tf\n'), (539, 'tensorflow.nn.seq2seq.sequence_loss_by_example', 'tf.nn.seq2seq.sequence_loss_by_example', (['logits', 'targets', 'weights'], {'average_across_timesteps': '(False)'}), True, 'import tensorflow as tf\n'), (592, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_w"""', '[24, classes]'], {}), True, 'import tensorflow as tf\n'), (593, 'tensorflow.transpose', 'tf.transpose', (['w'], {}), True, 'import tensorflow as tf\n'), (594, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_b"""', '[classes]'], {}), True, 'import tensorflow as tf\n'), (728, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (729, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_encoder_symbols', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (734, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(False)'}), True, 'import tensorflow as tf\n'), (735, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_encoder_symbols', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (740, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (741, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (746, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(False)'}), True, 'import tensorflow as tf\n'), (747, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (752, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (753, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_encoder_symbols', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (758, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(False)'}), True, 'import tensorflow as tf\n'), (759, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell', 'num_encoder_symbols', 'num_decoder_symbols'], {'embedding_size': '(2)', 'feed_previous': 'feed_previous'}), True, 'import tensorflow as tf\n'), (39, 'tensorflow.nn.seq2seq.rnn_decoder', 'tf.nn.seq2seq.rnn_decoder', (['dec_inp', 'enc_state', 'cell'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.nn.seq2seq.basic_rnn_seq2seq', 'tf.nn.seq2seq.basic_rnn_seq2seq', (['inp', 'dec_inp', 'cell'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.nn.seq2seq.tied_rnn_seq2seq', 'tf.nn.seq2seq.tied_rnn_seq2seq', (['inp', 'dec_inp', 'cell'], {}), True, 'import tensorflow as tf\n'), (85, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (86, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.nn.seq2seq.embedding_rnn_decoder', 'tf.nn.seq2seq.embedding_rnn_decoder', (['dec_inp', 'enc_state', 'cell'], {'num_symbols': '(4)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_w"""', '[2, 5]'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_b"""', '[5]'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp2', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (170, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_symbols': '(5)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_w"""', '[2, 5]'], {}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_b"""', '[5]'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp2', 'cell'], {'num_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)'}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)', 'num_heads': '(2)'}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2, 2]'}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (274, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)'}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2, 2]'}), True, 'import tensorflow as tf\n'), (290, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (293, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)', 'num_heads': '(2)'}), True, 'import tensorflow as tf\n'), (308, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (309, 'tensorflow.nn.rnn_cell.MultiRNNCell', 'tf.nn.rnn_cell.MultiRNNCell', ([], {'cells': '([cell] * 2)', 'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (312, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (316, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)'}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (364, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (368, 'tensorflow.nn.seq2seq.embedding_attention_decoder', 'tf.nn.seq2seq.embedding_attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'num_symbols': '(4)', 'embedding_size': '(2)', 'output_size': '(3)'}), True, 'import tensorflow as tf\n'), (384, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (385, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (412, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_w"""', '[2, 5]'], {}), True, 'import tensorflow as tf\n'), (413, 'tensorflow.get_variable', 'tf.get_variable', (['"""proj_b"""', '[5]'], {}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (435, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp2', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (454, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (455, 'tensorflow.nn.seq2seq.one2many_rnn_seq2seq', 'tf.nn.seq2seq.one2many_rnn_seq2seq', (['enc_inp', 'dec_inp_dict', 'cell', '(2)', 'dec_symbols_dict'], {'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (486, 'tensorflow.nn.seq2seq.one2many_rnn_seq2seq', 'tf.nn.seq2seq.one2many_rnn_seq2seq', (['enc_inp', 'dec_inp_dict', 'cell', '(2)', 'dec_symbols_dict'], {'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (489, 'tensorflow.nn.seq2seq.one2many_rnn_seq2seq', 'tf.nn.seq2seq.one2many_rnn_seq2seq', (['enc_inp', 'dec_inp_dict2', 'cell', '(2)', 'dec_symbols_dict'], {'embedding_size': '(2)', 'feed_previous': '(True)'}), True, 'import tensorflow as tf\n'), (500, 'tensorflow.constant', 'tf.constant', (['(i + 0.5)'], {'shape': '[2, 5]'}), True, 'import tensorflow as tf\n'), (501, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (502, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (528, 'tensorflow.constant', 'tf.constant', (['(i + 0.5)'], {'shape': '[2, output_classes]'}), True, 'import tensorflow as tf\n'), (530, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (531, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (537, 'numpy.asarray', 'np.asarray', (['[1.609438, 1.609438]'], {}), True, 'import numpy as np\n'), (543, 'numpy.asarray', 'np.asarray', (['[4.828314, 4.828314]'], {}), True, 'import numpy as np\n'), (561, 'tensorflow.nn.seq2seq.model_with_buckets', 'tf.nn.seq2seq.model_with_buckets', (['enc_inp', 'dec_inp', 'targets', 'weights', 'buckets', 'GRUSeq2Seq'], {'per_example_loss': 'per_example_loss'}), True, 'import tensorflow as tf\n'), (566, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (567, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (568, 'tensorflow.ones_like', 'tf.ones_like', (['inp[0]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (569, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""root"""'], {}), True, 'import tensorflow as tf\n'), (609, 'tensorflow.nn.seq2seq.model_with_buckets', 'tf.nn.seq2seq.model_with_buckets', (['enc_inp', 'dec_inp', 'targets', 'weights', 'buckets', 'GRUSeq2Seq'], {'softmax_loss_function': 'SampledLoss'}), True, 'import tensorflow as tf\n'), (615, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (616, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None]'}), True, 'import tensorflow as tf\n'), (617, 'tensorflow.ones_like', 'tf.ones_like', (['inp[0]'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (618, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""root"""'], {}), True, 'import tensorflow as tf\n'), (621, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (622, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.03)'], {'epsilon': '(1e-05)'}), True, 'import tensorflow as tf\n'), (669, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(111)'], {}), True, 'import tensorflow as tf\n'), (670, 'random.seed', 'random.seed', (['(111)'], {}), False, 'import random\n'), (671, 'numpy.random.seed', 'np.random.seed', (['(111)'], {}), True, 'import numpy as np\n'), (716, 'numpy.argmax', 'np.argmax', (['dec_fp_true'], {'axis': '(2)'}), True, 'import numpy as np\n'), (35, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(2)'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""no_tuple"""'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(False)'}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell1'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""proj_seq2seq"""'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.nn.seq2seq.embedding_rnn_seq2seq', 'tf.nn.seq2seq.embedding_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'output_projection': '(w, b)'}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""other"""'], {}), True, 'import tensorflow as tf\n'), (168, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (184, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder_symbols_seq2seq"""'], {}), True, 'import tensorflow as tf\n'), (185, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_symbols': '(5)', 'num_decoder_symbols': '(3)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""proj_seq2seq"""'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.nn.seq2seq.embedding_tied_rnn_seq2seq', 'tf.nn.seq2seq.embedding_tied_rnn_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_symbols': '(5)', 'embedding_size': '(2)', 'output_projection': '(w, b)'}), True, 'import tensorflow as tf\n'), (207, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""other"""'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (337, 'tensorflow.nn.rnn_cell.MultiRNNCell', 'tf.nn.rnn_cell.MultiRNNCell', ([], {'cells': '([cell] * 2)', 'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (339, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2, 2]'}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.nn.rnn', 'tf.nn.rnn', (['cell', 'inp'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.nn.seq2seq.attention_decoder', 'tf.nn.seq2seq.attention_decoder', (['dec_inp', 'enc_state', 'attn_states', 'cell'], {'output_size': '(4)'}), True, 'import tensorflow as tf\n'), (367, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (382, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (383, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (398, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""no_tuple"""'], {}), True, 'import tensorflow as tf\n'), (399, 'tensorflow.nn.rnn_cell.BasicLSTMCell', 'tf.nn.rnn_cell.BasicLSTMCell', (['(2)'], {'state_is_tuple': '(False)'}), True, 'import tensorflow as tf\n'), (400, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)'}), True, 'import tensorflow as tf\n'), (414, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""proj_seq2seq"""'], {}), True, 'import tensorflow as tf\n'), (415, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': '(2)', 'num_decoder_symbols': '(5)', 'embedding_size': '(2)', 'output_projection': '(w, b)'}), True, 'import tensorflow as tf\n'), (424, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (425, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""other"""'], {}), True, 'import tensorflow as tf\n'), (447, 'tensorflow.constant', 'tf.constant', (['(1)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (450, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (452, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (477, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (479, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (480, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""other"""'], {}), True, 'import tensorflow as tf\n'), (557, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': 'classes', 'num_decoder_symbols': 'classes', 'embedding_size': '(24)'}), True, 'import tensorflow as tf\n'), (601, 'tensorflow.nn.seq2seq.embedding_attention_seq2seq', 'tf.nn.seq2seq.embedding_attention_seq2seq', (['enc_inp', 'dec_inp', 'cell'], {'num_encoder_symbols': 'classes', 'num_decoder_symbols': 'classes', 'embedding_size': '(24)', 'output_projection': '(w, b)'}), True, 'import tensorflow as tf\n'), (607, 'tensorflow.reshape', 'tf.reshape', (['labels', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (608, 'tensorflow.nn.sampled_softmax_loss', 'tf.nn.sampled_softmax_loss', (['w_t', 'b', 'inputs', 'labels', '(8)', 'classes'], {}), True, 'import tensorflow as tf\n'), (624, 'tensorflow.gradients', 'tf.gradients', (['losses[i]', 'params'], {}), True, 'import tensorflow as tf\n'), (625, 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['full_grads', '(30.0)'], {}), True, 'import tensorflow as tf\n'), (673, 'tensorflow.constant', 'tf.constant', (['(i + 1)', 'tf.int32'], {'shape': '[batch_size]'}), True, 'import tensorflow as tf\n'), (675, 'tensorflow.constant', 'tf.constant', (['i', 'tf.int32'], {'shape': '[batch_size]'}), True, 'import tensorflow as tf\n'), (677, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[batch_size]'}), True, 'import tensorflow as tf\n'), (679, 'tensorflow.constant', 'tf.constant', (['(i + 1)', 'tf.int32'], {'shape': '[batch_size]'}), True, 'import tensorflow as tf\n'), (681, 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[batch_size]'}), True, 'import tensorflow as tf\n'), (690, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.03)'], {'epsilon': '(1e-05)'}), True, 'import tensorflow as tf\n'), (701, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (50, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (51, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (52, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (66, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (90, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (139, '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'), (152, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {'shape': '[2]'}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (212, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (247, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (249, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (287, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (297, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (307, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (311, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (313, 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), True, 'import tensorflow as tf\n'), (315, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (319, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (361, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (362, 'tensorflow.constant', 'tf.constant', (['(0.5)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (365, 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (381, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (388, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (418, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (430, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (431, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (446, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (458, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (484, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (485, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (572, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (574, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (628, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (636, 'numpy.array', 'np.array', (['([0] * batch_size)'], {'dtype': 'np.int32'}), True, 'import numpy as np\n'), (668, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (686, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope_name'], {}), True, 'import tensorflow as tf\n'), (688, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.GLOBAL_VARIABLES', 'scope_name'], {}), True, 'import tensorflow as tf\n'), (692, 'tensorflow.nn.seq2seq.sequence_loss', 'tf.nn.seq2seq.sequence_loss', (['dec_op', 'targets', 'weights'], {}), True, 'import tensorflow as tf\n'), (711, 'tensorflow.assign', 'tf.assign', (['v_false', 'v_true'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.constant', 'tf.constant', (['(True)'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.constant', 'tf.constant', (['(True)'], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.5)'], {}), True, 'import tensorflow as tf\n'), (341, 'tensorflow.reshape', 'tf.reshape', (['e', '[-1, 1, cell.output_size]'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.constant', 'tf.constant', (['(0.4)'], {'shape': '[2, 2]'}), True, 'import tensorflow as tf\n'), (347, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (403, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (429, 'tensorflow.constant', 'tf.constant', (['(True)'], {}), True, 'import tensorflow as tf\n'), (483, 'tensorflow.constant', 'tf.constant', (['(True)'], {}), True, 'import tensorflow as tf\n'), (555, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(24)'], {}), True, 'import tensorflow as tf\n'), (599, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['(24)'], {}), True, 'import tensorflow as tf\n'), (633, 'numpy.random.randint', 'np.random.randint', (['(9)'], {}), True, 'import numpy as np\n')]
vishwas1234567/tensor2tensor
d62e2ee1b069d3d9b327d4d2dd6f9e50b7e62bb3
# 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. """Glow generative model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.layers import common_hparams from tensor2tensor.layers import common_layers from tensor2tensor.models.research import glow_init_hook from tensor2tensor.models.research import glow_ops from tensor2tensor.utils import contrib from tensor2tensor.utils import registry from tensor2tensor.utils import t2t_model import tensorflow as tf arg_scope = contrib.framework().arg_scope add_arg_scope = contrib.framework().add_arg_scope GLOW_DECODE_HPARAMS = ("identity_output=True,log_results=False," "decode_in_memory=True,display_decoded_images=True") @registry.register_hparams def glow_hparams(): """Glow Hparams.""" hparams = common_hparams.basic_params1() hparams.clip_grad_norm = None hparams.weight_decay = 0.0 hparams.learning_rate_constant = 3e-4 hparams.batch_size = 32 # can be prev_level, prev_step or normal. # see: glow_ops.merge_level_and_latent_dist hparams.add_hparam("level_scale", "prev_level") hparams.add_hparam("n_levels", 3) hparams.add_hparam("n_bits_x", 8) hparams.add_hparam("depth", 32) # Activation - Relu or Gatu hparams.add_hparam("activation", "relu") # Coupling layer, additive or affine. hparams.add_hparam("coupling", "affine") hparams.add_hparam("coupling_width", 512) hparams.add_hparam("coupling_dropout", 0.0) hparams.add_hparam("top_prior", "single_conv") # init_batch_size denotes the number of examples used for data-dependent # initialization. A higher init_batch_size is required for training # stability especially when hparams.batch_size is low. hparams.add_hparam("init_batch_size", 256) hparams.add_hparam("temperature", 1.0) return hparams @registry.register_model class Glow(t2t_model.T2TModel): """Glow generative model. Reference: https://arxiv.org/abs/1807.03039""" def init_preprocess(self, features): """Preprocessing as per the input modality.""" return features def preprocess(self, x): """Normalize x. Args: x: 4-D Tensor. Returns: x: Scaled such that x lies in-between -0.5 and 0.5 """ n_bits_x = self.hparams.n_bits_x n_bins = 2**n_bits_x x = tf.cast(x, dtype=tf.float32) if n_bits_x < 8: x = tf.floor(x / 2 ** (8 - n_bits_x)) x = x / n_bins - 0.5 return x @property def temperature(self): if self.is_predicting: return self.hparams.temperature return 1.0 @property def is_training(self): return self.hparams.mode == tf.estimator.ModeKeys.TRAIN def infer(self, features, *args, **kwargs): # pylint: disable=arguments-differ del args, kwargs x = features["inputs"] batch_size = common_layers.shape_list(x)[0] features["targets"] = tf.zeros(shape=(batch_size, 1, 1, 1)) _, _ = self(features) # pylint: disable=not-callable ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout] var_scope = tf.variable_scope("glow/body", reuse=True) # If eps=None, images are sampled from the prior. with arg_scope(ops, init=False), var_scope: predictions, _, _, _ = glow_ops.encoder_decoder( "codec", self.z_sample, self.hparams, eps=None, reverse=True, temperature=self.temperature) return glow_ops.postprocess(predictions, self.hparams.n_bits_x) def create_init_batch(self, features): """Returns a batch of size "hparams.init_batch_size" for initialization. Args: features: input features. Returns: init_features: initialization features. """ train_dataset = self.hparams.problem.dataset( tf.estimator.ModeKeys.TRAIN, hparams=self.hparams) train_dataset = train_dataset.batch(self.hparams.init_batch_size) train_dataset = self.init_preprocess(train_dataset) return train_dataset.make_one_shot_iterator().get_next() @staticmethod def train_hooks(hook_context): del hook_context return [glow_init_hook.GlowInitHook()] def top_prior(self): """Objective based on the prior over latent z. Returns: dist: instance of tfp.distributions.Normal, prior distribution. """ return glow_ops.top_prior( "top_prior", self.z_top_shape, learn_prior=self.hparams.top_prior, temperature=self.temperature) def body(self, features): exp_coupling = ["affine", "additive"] if self.hparams.coupling not in exp_coupling: raise ValueError("Expected hparams.coupling to be in %s, got %s" % (exp_coupling, self.hparams.coupling)) if self.is_training: init_features = self.create_init_batch(features) init_op = self.objective_tower(init_features, init=True) init_op = tf.Print( init_op, [init_op], message="Triggering data-dependent init.", first_n=20) tf.add_to_collection("glow_init_op", init_op) train_op = self.objective_tower(features, init=False) return tf.zeros_like(features["targets"]), {"training": train_op} def objective_tower(self, features, init=True): """Objective in terms of bits-per-pixel. Args: features: dict of tensors with "features" and "targets" keys. init: Whether or not to run data-dependent init. Returns: objective: float, bits-per-pixel. """ x = features["inputs"] # Scale x such that the pixels lie in-between -0.5 and.0.5 x = self.preprocess(x) x, objective = glow_ops.uniform_binning_correction(x) # The arg_scope call ensures that the actnorm parameters are set such that # the per-channel output activations have zero mean and unit variance # ONLY during the first step. After that the parameters are learned # through optimisation. ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout] with arg_scope(ops, init=init): encoder = glow_ops.encoder_decoder self.z, encoder_objective, self.eps, _, _ = encoder( "codec", x, self.hparams, eps=None, reverse=False) objective += encoder_objective self.z_top_shape = common_layers.shape_list(self.z) prior_dist = self.top_prior() prior_objective = tf.reduce_sum( prior_dist.log_prob(self.z), axis=[1, 2, 3]) self.z_sample = prior_dist.sample() objective += prior_objective # bits per pixel _, h, w, c = common_layers.shape_list(x) objective = -objective / (np.log(2) * h * w * c) return objective
[ "numpy.log", "tensorflow.Print", "tensorflow.zeros", "tensorflow.cast", "tensorflow.floor", "tensorflow.zeros_like", "tensorflow.variable_scope", "tensorflow.add_to_collection" ]
tensor2tensor/models/research/glow.py
[(32, 'tensor2tensor.utils.contrib.framework', 'contrib.framework', ([], {}), False, 'from tensor2tensor.utils import contrib\n'), (33, 'tensor2tensor.utils.contrib.framework', 'contrib.framework', ([], {}), False, 'from tensor2tensor.utils import contrib\n'), (42, 'tensor2tensor.layers.common_hparams.basic_params1', 'common_hparams.basic_params1', ([], {}), False, 'from tensor2tensor.layers import common_hparams\n'), (90, 'tensorflow.cast', 'tf.cast', (['x'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': '(batch_size, 1, 1, 1)'}), True, 'import tensorflow as tf\n'), (114, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""glow/body"""'], {'reuse': '(True)'}), True, 'import tensorflow as tf\n'), (121, 'tensor2tensor.models.research.glow_ops.postprocess', 'glow_ops.postprocess', (['predictions', 'self.hparams.n_bits_x'], {}), False, 'from tensor2tensor.models.research import glow_ops\n'), (148, 'tensor2tensor.models.research.glow_ops.top_prior', 'glow_ops.top_prior', (['"""top_prior"""', 'self.z_top_shape'], {'learn_prior': 'self.hparams.top_prior', 'temperature': 'self.temperature'}), False, 'from tensor2tensor.models.research import glow_ops\n'), (180, 'tensor2tensor.models.research.glow_ops.uniform_binning_correction', 'glow_ops.uniform_binning_correction', (['x'], {}), False, 'from tensor2tensor.models.research import glow_ops\n'), (203, 'tensor2tensor.layers.common_layers.shape_list', 'common_layers.shape_list', (['x'], {}), False, 'from tensor2tensor.layers import common_layers\n'), (92, 'tensorflow.floor', 'tf.floor', (['(x / 2 ** (8 - n_bits_x))'], {}), True, 'import tensorflow as tf\n'), (109, 'tensor2tensor.layers.common_layers.shape_list', 'common_layers.shape_list', (['x'], {}), False, 'from tensor2tensor.layers import common_layers\n'), (117, 'tensor2tensor.models.research.glow_ops.encoder_decoder', 'glow_ops.encoder_decoder', (['"""codec"""', 'self.z_sample', 'self.hparams'], {'eps': 'None', 'reverse': '(True)', 'temperature': 'self.temperature'}), False, 'from tensor2tensor.models.research import glow_ops\n'), (140, 'tensor2tensor.models.research.glow_init_hook.GlowInitHook', 'glow_init_hook.GlowInitHook', ([], {}), False, 'from tensor2tensor.models.research import glow_init_hook\n'), (160, 'tensorflow.Print', 'tf.Print', (['init_op', '[init_op]'], {'message': '"""Triggering data-dependent init."""', 'first_n': '(20)'}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['"""glow_init_op"""', 'init_op'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.zeros_like', 'tf.zeros_like', (["features['targets']"], {}), True, 'import tensorflow as tf\n'), (195, 'tensor2tensor.layers.common_layers.shape_list', 'common_layers.shape_list', (['self.z'], {}), False, 'from tensor2tensor.layers import common_layers\n'), (204, 'numpy.log', 'np.log', (['(2)'], {}), True, 'import numpy as np\n')]
andreandradecosta/Adversarial_Autoencoder
255a5cc021a46d9f8320a8608f15370d3e89e29e
import tensorflow as tf import numpy as np import datetime import os import argparse import matplotlib.pyplot as plt from matplotlib import gridspec from tensorflow.examples.tutorials.mnist import input_data # Get the MNIST data mnist = input_data.read_data_sets('./Data', one_hot=True) # Parameters input_dim = 784 n_l1 = 1000 n_l2 = 1000 z_dim = 10 batch_size = 100 n_epochs = 1000 learning_rate = 0.001 beta1 = 0.9 results_path = './Results/Semi_Supervised' n_labels = 10 n_labeled = 1000 # Placeholders for input data and the targets x_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Input') x_input_l = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Labeled_Input') y_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels], name='Labels') x_target = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Target') real_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, z_dim], name='Real_distribution') categorial_distribution = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels], name='Categorical_distribution') manual_decoder_input = tf.placeholder(dtype=tf.float32, shape=[1, z_dim + n_labels], name='Decoder_input') def form_results(): """ Forms folders for each run to store the tensorboard files, saved models and the log files. :return: three string pointing to tensorboard, saved models and log paths respectively. """ folder_name = "/{0}_{1}_{2}_{3}_{4}_{5}_Semi_Supervised". \ format(datetime.datetime.now(), z_dim, learning_rate, batch_size, n_epochs, beta1) tensorboard_path = results_path + folder_name + '/Tensorboard' saved_model_path = results_path + folder_name + '/Saved_models/' log_path = results_path + folder_name + '/log' if not os.path.exists(results_path + folder_name): os.mkdir(results_path + folder_name) os.mkdir(tensorboard_path) os.mkdir(saved_model_path) os.mkdir(log_path) return tensorboard_path, saved_model_path, log_path def generate_image_grid(sess, op): """ Generates a grid of images by passing a set of numbers to the decoder and getting its output. :param sess: Tensorflow Session required to get the decoder output :param op: Operation that needs to be called inorder to get the decoder output :return: None, displays a matplotlib window with all the merged images. """ nx, ny = 10, 10 random_inputs = np.random.randn(10, z_dim) * 5. sample_y = np.identity(10) plt.subplot() gs = gridspec.GridSpec(nx, ny, hspace=0.05, wspace=0.05) i = 0 for r in random_inputs: for t in sample_y: r, t = np.reshape(r, (1, z_dim)), np.reshape(t, (1, n_labels)) dec_input = np.concatenate((t, r), 1) x = sess.run(op, feed_dict={manual_decoder_input: dec_input}) ax = plt.subplot(gs[i]) i += 1 img = np.array(x.tolist()).reshape(28, 28) ax.imshow(img, cmap='gray') ax.set_xticks([]) ax.set_yticks([]) ax.set_aspect('auto') plt.show() def dense(x, n1, n2, name): """ Used to create a dense layer. :param x: input tensor to the dense layer :param n1: no. of input neurons :param n2: no. of output neurons :param name: name of the entire dense layer.i.e, variable scope name. :return: tensor with shape [batch_size, n2] """ with tf.variable_scope(name, reuse=None): weights = tf.get_variable("weights", shape=[n1, n2], initializer=tf.random_normal_initializer(mean=0., stddev=0.01)) bias = tf.get_variable("bias", shape=[n2], initializer=tf.constant_initializer(0.0)) out = tf.add(tf.matmul(x, weights), bias, name='matmul') return out # The autoencoder network def encoder(x, reuse=False, supervised=False): """ Encode part of the autoencoder. :param x: input to the autoencoder :param reuse: True -> Reuse the encoder variables, False -> Create or search of variables before creating :param supervised: True -> returns output without passing it through softmax, False -> returns output after passing it through softmax. :return: tensor which is the classification output and a hidden latent variable of the autoencoder. """ if reuse: tf.get_variable_scope().reuse_variables() with tf.name_scope('Encoder'): e_dense_1 = tf.nn.relu(dense(x, input_dim, n_l1, 'e_dense_1')) e_dense_2 = tf.nn.relu(dense(e_dense_1, n_l1, n_l2, 'e_dense_2')) latent_variable = dense(e_dense_2, n_l2, z_dim, 'e_latent_variable') cat_op = dense(e_dense_2, n_l2, n_labels, 'e_label') if not supervised: softmax_label = tf.nn.softmax(logits=cat_op, name='e_softmax_label') else: softmax_label = cat_op return softmax_label, latent_variable def decoder(x, reuse=False): """ Decoder part of the autoencoder. :param x: input to the decoder :param reuse: True -> Reuse the decoder variables, False -> Create or search of variables before creating :return: tensor which should ideally be the input given to the encoder. """ if reuse: tf.get_variable_scope().reuse_variables() with tf.name_scope('Decoder'): d_dense_1 = tf.nn.relu(dense(x, z_dim + n_labels, n_l2, 'd_dense_1')) d_dense_2 = tf.nn.relu(dense(d_dense_1, n_l2, n_l1, 'd_dense_2')) output = tf.nn.sigmoid(dense(d_dense_2, n_l1, input_dim, 'd_output')) return output def discriminator_gauss(x, reuse=False): """ Discriminator that is used to match the posterior distribution with a given gaussian distribution. :param x: tensor of shape [batch_size, z_dim] :param reuse: True -> Reuse the discriminator variables, False -> Create or search of variables before creating :return: tensor of shape [batch_size, 1] """ if reuse: tf.get_variable_scope().reuse_variables() with tf.name_scope('Discriminator_Gauss'): dc_den1 = tf.nn.relu(dense(x, z_dim, n_l1, name='dc_g_den1')) dc_den2 = tf.nn.relu(dense(dc_den1, n_l1, n_l2, name='dc_g_den2')) output = dense(dc_den2, n_l2, 1, name='dc_g_output') return output def discriminator_categorical(x, reuse=False): """ Discriminator that is used to match the posterior distribution with a given categorical distribution. :param x: tensor of shape [batch_size, n_labels] :param reuse: True -> Reuse the discriminator variables, False -> Create or search of variables before creating :return: tensor of shape [batch_size, 1] """ if reuse: tf.get_variable_scope().reuse_variables() with tf.name_scope('Discriminator_Categorial'): dc_den1 = tf.nn.relu(dense(x, n_labels, n_l1, name='dc_c_den1')) dc_den2 = tf.nn.relu(dense(dc_den1, n_l1, n_l2, name='dc_c_den2')) output = dense(dc_den2, n_l2, 1, name='dc_c_output') return output def next_batch(x, y, batch_size): """ Used to return a random batch from the given inputs. :param x: Input images of shape [None, 784] :param y: Input labels of shape [None, 10] :param batch_size: integer, batch size of images and labels to return :return: x -> [batch_size, 784], y-> [batch_size, 10] """ index = np.arange(n_labeled) random_index = np.random.permutation(index)[:batch_size] return x[random_index], y[random_index] def train(train_model=True): """ Used to train the autoencoder by passing in the necessary inputs. :param train_model: True -> Train the model, False -> Load the latest trained model and show the image grid. :return: does not return anything """ # Reconstruction Phase with tf.variable_scope(tf.get_variable_scope()): encoder_output_label, encoder_output_latent = encoder(x_input) # Concat class label and the encoder output decoder_input = tf.concat([encoder_output_label, encoder_output_latent], 1) decoder_output = decoder(decoder_input) # Regularization Phase with tf.variable_scope(tf.get_variable_scope()): d_g_real = discriminator_gauss(real_distribution) d_g_fake = discriminator_gauss(encoder_output_latent, reuse=True) with tf.variable_scope(tf.get_variable_scope()): d_c_real = discriminator_categorical(categorial_distribution) d_c_fake = discriminator_categorical(encoder_output_label, reuse=True) # Semi-Supervised Classification Phase with tf.variable_scope(tf.get_variable_scope()): encoder_output_label_, _ = encoder(x_input_l, reuse=True, supervised=True) # Generate output images with tf.variable_scope(tf.get_variable_scope()): decoder_image = decoder(manual_decoder_input, reuse=True) # Classification accuracy of encoder correct_pred = tf.equal(tf.argmax(encoder_output_label_, 1), tf.argmax(y_input, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Autoencoder loss autoencoder_loss = tf.reduce_mean(tf.square(x_target - decoder_output)) # Gaussian Discriminator Loss dc_g_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_g_real), logits=d_g_real)) dc_g_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(d_g_fake), logits=d_g_fake)) dc_g_loss = dc_g_loss_fake + dc_g_loss_real # Categorical Discrimminator Loss dc_c_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_c_real), logits=d_c_real)) dc_c_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(d_c_fake), logits=d_c_fake)) dc_c_loss = dc_c_loss_fake + dc_c_loss_real # Generator loss generator_g_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_g_fake), logits=d_g_fake)) generator_c_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(d_c_fake), logits=d_c_fake)) generator_loss = generator_c_loss + generator_g_loss # Supervised Encoder Loss supervised_encoder_loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=y_input, logits=encoder_output_label_)) all_variables = tf.trainable_variables() dc_g_var = [var for var in all_variables if 'dc_g_' in var.name] dc_c_var = [var for var in all_variables if 'dc_c_' in var.name] en_var = [var for var in all_variables if 'e_' in var.name] # Optimizers autoencoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(autoencoder_loss) discriminator_g_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(dc_g_loss, var_list=dc_g_var) discriminator_c_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(dc_c_loss, var_list=dc_c_var) generator_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(generator_loss, var_list=en_var) supervised_encoder_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(supervised_encoder_loss, var_list=en_var) init = tf.global_variables_initializer() # Reshape immages to display them input_images = tf.reshape(x_input, [-1, 28, 28, 1]) generated_images = tf.reshape(decoder_output, [-1, 28, 28, 1]) # Tensorboard visualization tf.summary.scalar(name='Autoencoder Loss', tensor=autoencoder_loss) tf.summary.scalar(name='Discriminator gauss Loss', tensor=dc_g_loss) tf.summary.scalar(name='Discriminator categorical Loss', tensor=dc_c_loss) tf.summary.scalar(name='Generator Loss', tensor=generator_loss) tf.summary.scalar(name='Supervised Encoder Loss', tensor=supervised_encoder_loss) tf.summary.histogram(name='Encoder Gauss Distribution', values=encoder_output_latent) tf.summary.histogram(name='Real Gauss Distribution', values=real_distribution) tf.summary.histogram(name='Encoder Categorical Distribution', values=encoder_output_label) tf.summary.histogram(name='Real Categorical Distribution', values=categorial_distribution) tf.summary.image(name='Input Images', tensor=input_images, max_outputs=10) tf.summary.image(name='Generated Images', tensor=generated_images, max_outputs=10) summary_op = tf.summary.merge_all() # Saving the model saver = tf.train.Saver() step = 0 with tf.Session() as sess: if train_model: tensorboard_path, saved_model_path, log_path = form_results() sess.run(init) writer = tf.summary.FileWriter(logdir=tensorboard_path, graph=sess.graph) x_l, y_l = mnist.test.next_batch(n_labeled) for i in range(n_epochs): n_batches = int(n_labeled / batch_size) print("------------------Epoch {}/{}------------------".format(i, n_epochs)) for b in range(1, n_batches + 1): z_real_dist = np.random.randn(batch_size, z_dim) * 5. real_cat_dist = np.random.randint(low=0, high=10, size=batch_size) real_cat_dist = np.eye(n_labels)[real_cat_dist] batch_x_ul, _ = mnist.train.next_batch(batch_size) batch_x_l, batch_y_l = next_batch(x_l, y_l, batch_size=batch_size) sess.run(autoencoder_optimizer, feed_dict={x_input: batch_x_ul, x_target: batch_x_ul}) sess.run(discriminator_g_optimizer, feed_dict={x_input: batch_x_ul, x_target: batch_x_ul, real_distribution: z_real_dist}) sess.run(discriminator_c_optimizer, feed_dict={x_input: batch_x_ul, x_target: batch_x_ul, categorial_distribution: real_cat_dist}) sess.run(generator_optimizer, feed_dict={x_input: batch_x_ul, x_target: batch_x_ul}) sess.run(supervised_encoder_optimizer, feed_dict={x_input_l: batch_x_l, y_input: batch_y_l}) if b % 5 == 0: a_loss, d_g_loss, d_c_loss, g_loss, s_loss, summary = sess.run( [autoencoder_loss, dc_g_loss, dc_c_loss, generator_loss, supervised_encoder_loss, summary_op], feed_dict={x_input: batch_x_ul, x_target: batch_x_ul, real_distribution: z_real_dist, y_input: batch_y_l, x_input_l: batch_x_l, categorial_distribution: real_cat_dist}) writer.add_summary(summary, global_step=step) print("Epoch: {}, iteration: {}".format(i, b)) print("Autoencoder Loss: {}".format(a_loss)) print("Discriminator Gauss Loss: {}".format(d_g_loss)) print("Discriminator Categorical Loss: {}".format(d_c_loss)) print("Generator Loss: {}".format(g_loss)) print("Supervised Loss: {}\n".format(s_loss)) with open(log_path + '/log.txt', 'a') as log: log.write("Epoch: {}, iteration: {}\n".format(i, b)) log.write("Autoencoder Loss: {}\n".format(a_loss)) log.write("Discriminator Gauss Loss: {}".format(d_g_loss)) log.write("Discriminator Categorical Loss: {}".format(d_c_loss)) log.write("Generator Loss: {}\n".format(g_loss)) log.write("Supervised Loss: {}".format(s_loss)) step += 1 acc = 0 num_batches = int(mnist.validation.num_examples/batch_size) for j in range(num_batches): # Classify unseen validation data instead of test data or train data batch_x_l, batch_y_l = mnist.validation.next_batch(batch_size=batch_size) encoder_acc = sess.run(accuracy, feed_dict={x_input_l: batch_x_l, y_input: batch_y_l}) acc += encoder_acc acc /= num_batches print("Encoder Classification Accuracy: {}".format(acc)) with open(log_path + '/log.txt', 'a') as log: log.write("Encoder Classification Accuracy: {}".format(acc)) saver.save(sess, save_path=saved_model_path, global_step=step) else: # Get the latest results folder all_results = os.listdir(results_path) all_results.sort() saver.restore(sess, save_path=tf.train.latest_checkpoint(results_path + '/' + all_results[-1] + '/Saved_models/')) generate_image_grid(sess, op=decoder_image) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Autoencoder Train Parameter") parser.add_argument('--train', '-t', type=bool, default=True, help='Set to True to train a new model, False to load weights and display image grid') args = parser.parse_args() train(train_model=args.train)
[ "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.concat", "tensorflow.cast", "numpy.concatenate", "numpy.random.randn", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "numpy.random.randint", "numpy.reshape", "numpy.arange", "tensorflow.summary.image", "numpy.eye", "matplotlib.pyplot.subplot", "matplotlib.gridspec.GridSpec", "tensorflow.name_scope", "tensorflow.square", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.Session", "tensorflow.random_normal_initializer", "tensorflow.matmul", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.zeros_like", "numpy.identity", "tensorflow.summary.merge_all", "matplotlib.pyplot.show", "tensorflow.summary.histogram", "tensorflow.nn.softmax", "tensorflow.summary.FileWriter", "tensorflow.train.latest_checkpoint", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.constant_initializer", "numpy.random.permutation", "tensorflow.variable_scope", "tensorflow.get_variable_scope" ]
semi_supervised_adversarial_autoencoder.py
[(11, 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""./Data"""'], {'one_hot': '(True)'}), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), (27, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, input_dim]', 'name': '"""Input"""'}), True, 'import tensorflow as tf\n'), (28, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, input_dim]', 'name': '"""Labeled_Input"""'}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, n_labels]', 'name': '"""Labels"""'}), True, 'import tensorflow as tf\n'), (30, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, input_dim]', 'name': '"""Target"""'}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, z_dim]', 'name': '"""Real_distribution"""'}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[batch_size, n_labels]', 'name': '"""Categorical_distribution"""'}), True, 'import tensorflow as tf\n'), (34, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '[1, z_dim + n_labels]', 'name': '"""Decoder_input"""'}), True, 'import tensorflow as tf\n'), (64, 'numpy.identity', 'np.identity', (['(10)'], {}), True, 'import numpy as np\n'), (65, 'matplotlib.pyplot.subplot', 'plt.subplot', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (66, 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['nx', 'ny'], {'hspace': '(0.05)', 'wspace': '(0.05)'}), False, 'from matplotlib import gridspec\n'), (80, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (182, 'numpy.arange', 'np.arange', (['n_labeled'], {}), True, 'import numpy as np\n'), (250, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.reshape', 'tf.reshape', (['x_input', '[-1, 28, 28, 1]'], {}), True, 'import tensorflow as tf\n'), (272, 'tensorflow.reshape', 'tf.reshape', (['decoder_output', '[-1, 28, 28, 1]'], {}), True, 'import tensorflow as tf\n'), (275, 'tensorflow.summary.scalar', 'tf.summary.scalar', ([], {'name': '"""Autoencoder Loss"""', 'tensor': 'autoencoder_loss'}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.summary.scalar', 'tf.summary.scalar', ([], {'name': '"""Discriminator gauss Loss"""', 'tensor': 'dc_g_loss'}), True, 'import tensorflow as tf\n'), (277, 'tensorflow.summary.scalar', 'tf.summary.scalar', ([], {'name': '"""Discriminator categorical Loss"""', 'tensor': 'dc_c_loss'}), True, 'import tensorflow as tf\n'), (278, 'tensorflow.summary.scalar', 'tf.summary.scalar', ([], {'name': '"""Generator Loss"""', 'tensor': 'generator_loss'}), True, 'import tensorflow as tf\n'), (279, 'tensorflow.summary.scalar', 'tf.summary.scalar', ([], {'name': '"""Supervised Encoder Loss"""', 'tensor': 'supervised_encoder_loss'}), True, 'import tensorflow as tf\n'), (280, 'tensorflow.summary.histogram', 'tf.summary.histogram', ([], {'name': '"""Encoder Gauss Distribution"""', 'values': 'encoder_output_latent'}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.summary.histogram', 'tf.summary.histogram', ([], {'name': '"""Real Gauss Distribution"""', 'values': 'real_distribution'}), True, 'import tensorflow as tf\n'), (282, 'tensorflow.summary.histogram', 'tf.summary.histogram', ([], {'name': '"""Encoder Categorical Distribution"""', 'values': 'encoder_output_label'}), True, 'import tensorflow as tf\n'), (283, 'tensorflow.summary.histogram', 'tf.summary.histogram', ([], {'name': '"""Real Categorical Distribution"""', 'values': 'categorial_distribution'}), True, 'import tensorflow as tf\n'), (284, 'tensorflow.summary.image', 'tf.summary.image', ([], {'name': '"""Input Images"""', 'tensor': 'input_images', 'max_outputs': '(10)'}), True, 'import tensorflow as tf\n'), (285, 'tensorflow.summary.image', 'tf.summary.image', ([], {'name': '"""Generated Images"""', 'tensor': 'generated_images', 'max_outputs': '(10)'}), True, 'import tensorflow as tf\n'), (286, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (358, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Autoencoder Train Parameter"""'}), False, 'import argparse\n'), (43, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n'), (47, 'os.path.exists', 'os.path.exists', (['(results_path + folder_name)'], {}), False, 'import os\n'), (48, 'os.mkdir', 'os.mkdir', (['(results_path + folder_name)'], {}), False, 'import os\n'), (49, 'os.mkdir', 'os.mkdir', (['tensorboard_path'], {}), False, 'import os\n'), (50, 'os.mkdir', 'os.mkdir', (['saved_model_path'], {}), False, 'import os\n'), (51, 'os.mkdir', 'os.mkdir', (['log_path'], {}), False, 'import os\n'), (63, 'numpy.random.randn', 'np.random.randn', (['(10)', 'z_dim'], {}), True, 'import numpy as np\n'), (92, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {'reuse': 'None'}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.name_scope', 'tf.name_scope', (['"""Encoder"""'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.name_scope', 'tf.name_scope', (['"""Decoder"""'], {}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.name_scope', 'tf.name_scope', (['"""Discriminator_Gauss"""'], {}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.name_scope', 'tf.name_scope', (['"""Discriminator_Categorial"""'], {}), True, 'import tensorflow as tf\n'), (183, 'numpy.random.permutation', 'np.random.permutation', (['index'], {}), True, 'import numpy as np\n'), (198, 'tensorflow.concat', 'tf.concat', (['[encoder_output_label, encoder_output_latent]', '(1)'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.argmax', 'tf.argmax', (['encoder_output_label_', '(1)'], {}), True, 'import tensorflow as tf\n'), (219, 'tensorflow.argmax', 'tf.argmax', (['y_input', '(1)'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.cast', 'tf.cast', (['correct_pred', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (223, 'tensorflow.square', 'tf.square', (['(x_target - decoder_output)'], {}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'labels': 'y_input', 'logits': 'encoder_output_label_'}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (71, 'numpy.concatenate', 'np.concatenate', (['(t, r)', '(1)'], {}), True, 'import numpy as np\n'), (73, 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[i]'], {}), True, 'import matplotlib.pyplot as plt\n'), (96, 'tensorflow.matmul', 'tf.matmul', (['x', 'weights'], {}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.nn.softmax', 'tf.nn.softmax', ([], {'logits': 'cat_op', 'name': '"""e_softmax_label"""'}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (215, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'beta1'}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'beta1'}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'beta1'}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'beta1'}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'beta1'}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', ([], {'logdir': 'tensorboard_path', 'graph': 'sess.graph'}), True, 'import tensorflow as tf\n'), (350, 'os.listdir', 'os.listdir', (['results_path'], {}), False, 'import os\n'), (70, 'numpy.reshape', 'np.reshape', (['r', '(1, z_dim)'], {}), True, 'import numpy as np\n'), (70, 'numpy.reshape', 'np.reshape', (['t', '(1, n_labels)'], {}), True, 'import numpy as np\n'), (94, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'mean': '(0.0)', 'stddev': '(0.01)'}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (149, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.ones_like', 'tf.ones_like', (['d_g_real'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.zeros_like', 'tf.zeros_like', (['d_g_fake'], {}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.ones_like', 'tf.ones_like', (['d_c_real'], {}), True, 'import tensorflow as tf\n'), (236, 'tensorflow.zeros_like', 'tf.zeros_like', (['d_c_fake'], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.ones_like', 'tf.ones_like', (['d_g_fake'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.ones_like', 'tf.ones_like', (['d_c_fake'], {}), True, 'import tensorflow as tf\n'), (302, 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(10)', 'size': 'batch_size'}), True, 'import numpy as np\n'), (352, 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["(results_path + '/' + all_results[-1] + '/Saved_models/')"], {}), True, 'import tensorflow as tf\n'), (301, 'numpy.random.randn', 'np.random.randn', (['batch_size', 'z_dim'], {}), True, 'import numpy as np\n'), (303, 'numpy.eye', 'np.eye', (['n_labels'], {}), True, 'import numpy as np\n')]
pcmoritz/analytics-zoo
4d9f1eb6ccbf58d49dd5dce41b491c0f76107c31
# # Copyright 2018 Analytics Zoo 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. # import numpy as np import sys from bigdl.dataset.dataset import DataSet from bigdl.transform.vision.image import FeatureTransformer from bigdl.util.common import get_node_and_core_number, callBigDlFunc from zoo.common import Sample, JTensor from zoo.common.nncontext import getOrCreateSparkContext from zoo.feature.image import ImagePreprocessing from zoo.util import nest if sys.version >= '3': long = int unicode = str def _to_tensor_structure(tensors): if isinstance(tensors, tuple): tensor_structure = TensorMeta(dtype=tensors[0], shape=tensors[1], name="input0") elif isinstance(tensors, list): tensor_structure = [TensorMeta(dtype=value[0], shape=value[1], name="list_input_" + str(idx)) for (idx, value) in enumerate(tensors)] elif isinstance(tensors, dict): tensor_structure = {} for key, value in tensors.items(): tensor_structure[key] = TensorMeta(dtype=value[0], shape=value[1], name=key) else: raise ValueError("In TFDataset.from_rdd, features and labels should be a tuple, " "a list of tuples or a dict of tuples") return tensor_structure def _tensors_to_rdd(tensors, sc, splits): import tensorflow as tf if isinstance(tensors, np.ndarray): tensors = (tensors,) if isinstance(tensors, list): for i in range(len(tensors)): if tensors[i].dtype == np.dtype("float64"): tensors[i] = np.float32(tensors[i]) data_list = _splits(tensors) rdd = sc.parallelize(data_list, splits) tensor_structure = [TensorMeta(tf.as_dtype(t.dtype), shape=t.shape[1:], name="input_%s" % i) for i, t in enumerate(tensors)] else: flattened = nest.flatten(tensors) for i in range(len(flattened)): if flattened[i].dtype == np.dtype("float64"): flattened[i] = np.float32(flattened[i]) data_list = _splits(flattened) rdd = sc.parallelize(data_list, splits) rdd = rdd.map(lambda x: nest.pack_sequence_as(tensors, x)) tensor_structure = nest.pack_sequence_as(tensors, [TensorMeta(tf.as_dtype(t.dtype), shape=t.shape[1:], name="input_%s" % i) for i, t in enumerate(flattened)]) return rdd, tensor_structure def _splits(tensors): data_list = [] data_size = tensors[0].shape[0] for i in range(data_size): sample = [] for j in range(len(tensors)): sample.append(tensors[j][i]) data_list.append(sample) return data_list class MergeFeatureLabelImagePreprocessing(ImagePreprocessing): def __init__(self, bigdl_type="float"): super(MergeFeatureLabelImagePreprocessing, self).__init__(bigdl_type) class MergeFeatureLabelFeatureTransformer(FeatureTransformer): def __init__(self, bigdl_type="float"): super(MergeFeatureLabelFeatureTransformer, self).__init__(bigdl_type) class TensorMeta(object): def __init__(self, dtype, name=None, shape=None): self.dtype = dtype self.name = name self.shape = shape class TFDataset(object): def __init__(self, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size=False): """ TFDataset represents a distributed collection of elements (backed by a RDD) to be feed into Tensorflow graph. :param tensor_structure: a nested structure of TensorMeta objects specifying the name, shape and data type of each element in this TFDataset :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. """ if batch_size > 0 and batch_per_thread > 0: raise ValueError("bath_size and batch_per_thread should not be set simultaneously") self.has_batch = True node_num, core_num = get_node_and_core_number() self.total_core_num = node_num * core_num if batch_size > 0: if batch_size % self.total_core_num != 0: raise ValueError("batch_size should be a multiple " + "of total core number, but got batch_size: " + "%s where total core number is %s" % (batch_size, self.total_core_num)) if batch_size <= 0 and batch_per_thread <= 0: batch_per_thread = 1 batch_size = self.total_core_num self.has_batch = False self.batch_size = batch_size self.batch_per_thread = batch_per_thread self.hard_code_batch_size = hard_code_batch_size self.tensor_structure = tensor_structure if not self.hard_code_batch_size: self.output_shapes = nest.pack_sequence_as( self.tensor_structure, [[None] + list(t.shape) if t is not None else None for t in nest.flatten(self.tensor_structure)]) else: if self.batch_per_thread > 0: self.output_shapes = nest.pack_sequence_as( self.tensor_structure, [[self.batch_per_thread] + t.shape if t is not None else None for t in nest.flatten(self.tensor_structure)]) else: self.output_shapes = nest.pack_sequence_as( self.tensor_structure, [[self.batch_size // self.total_core_num] + t.shape if t is not None else None for t in nest.flatten(self.tensor_structure)]) self.input_names = nest.pack_sequence_as( self.tensor_structure, [t.name if t is not None else None for t in nest.flatten(self.tensor_structure)]) self._tensors = None def _create_placeholders(self): import tensorflow as tf if not self.hard_code_batch_size: tensors = nest.pack_sequence_as( self.tensor_structure, [tf.placeholder(name=t.name, dtype=t.dtype, shape=[None] + list(t.shape)) for t in nest.flatten(self.tensor_structure)]) else: if self.batch_per_thread > 0: tensors = nest.pack_sequence_as( self.tensor_structure, [tf.placeholder(name=t.name, dtype=t.dtype, shape=[self.batch_per_thread] + list(t.shape)) for t in nest.flatten(self.tensor_structure)]) else: tensors = nest.pack_sequence_as( self.tensor_structure, [tf.placeholder(name=t.name, dtype=t.dtype, shape=[self.batch_size // self.total_core_num] + list(t.shape)) for t in nest.flatten(self.tensor_structure)]) for tensor in nest.flatten(tensors): tf.get_default_graph().clear_collection(tensor.name) tf.add_to_collection(tensor.name, self) self._original_tensors = tensors self._tensors = tensors if not self.has_batch: self._tensors = nest.pack_sequence_as(self.tensor_structure, [t[0] for t in nest.flatten(tensors)]) return tensors @property def tensors(self): """ a nested structure of TensorFlow tensor object in TensorFlow graph. The elements of this dataset will be fed into these tensors on each iteration. :return: the nested structure of TensorFlow tensor object """ if self._tensors is None: self._create_placeholders() return self._tensors @property def feature_tensors(self): if self._tensors is None: self._create_placeholders() if not isinstance(self._tensors, tuple): raise ValueError("To use feature_tensors, " + "the element in TFDataset must be a tuple of two components. " + "Please use TFDataset.from_rdd(rdd, features=..., labels=...). ") return self._tensors[0] @property def label_tensors(self): if self._tensors is None: self._create_placeholders() if not isinstance(self._tensors, tuple): raise ValueError("To use label_tensors, " + "the element in TFDataset must be a tuple of two components. " + "Please use TFDataset.from_rdd(rdd, features=..., labels=...). ") return self._tensors[1] @staticmethod def _to_tensor_structure(features, labels): feature_structure = _to_tensor_structure(features) if labels is not None: label_structure = _to_tensor_structure(labels) tensor_structure = (feature_structure, label_structure) else: tensor_structure = (feature_structure,) return tensor_structure def get_prediction_data(self): """ :return: an object that can be used for TFNet.predict e.g. an RDD of Sample or a ImageSet """ raise NotImplementedError def get_evaluation_data(self): """ :return: an object that can be used for TFNet.evaluate, e.g. an RDD of Sample or a ImageSet """ raise NotImplementedError def get_training_data(self): """ :return: an object that can be used to create a BigDL optimizer, e.g. an RDD of Sample or a DataSet """ raise NotImplementedError def get_validation_data(self): """ :return: an object that can be used to set validation in a BigDL optimizer, e.g. an RDD of Sample or a DataSet """ raise NotImplementedError def get_num_partitions(self): """ :return: the num of partitions of the underlying RDD """ raise NotImplementedError @staticmethod def from_rdd(*args, **kwargs): """ Create a TFDataset from a rdd. For training and evaluation, both `features` and `labels` arguments should be specified. The element of the rdd should be a tuple of two, (features, labels), each has the same structure of numpy.ndarrays of the argument `features`, `labels`. E.g. if `features` is [(tf.float32, [10]), (tf.float32, [20])], and `labels` is {"label1":(tf.float32, [10]), "label2": (tf.float32, [20])} then a valid element of the rdd could be ( [np.zeros(dtype=float, shape=(10,), np.zeros(dtype=float, shape=(10,)))], {"label1": np.zeros(dtype=float, shape=(10,)), "label2":np.zeros(dtype=float, shape=(10,))))} ) If `labels` is not specified, then the above element should be changed to [np.zeros(dtype=float, shape=(10,), np.zeros(dtype=float, shape=(10,)))] For inference, `labels` can be not specified. The element of the rdd should be some ndarrays of the same structure of the `features` argument. A note on the legacy api: if you are using `names`, `shapes`, `types` arguments, each element of the rdd should be a list of numpy.ndarray. :param rdd: a rdd containing the numpy.ndarrays to be used for training/evaluation/inference :param features: the structure of input features, should one the following: - a tuple (dtype, shape), e.g. (tf.float32, [28, 28, 1]) - a list of such tuple [(dtype1, shape1), (dtype2, shape2)], e.g. [(tf.float32, [10]), (tf.float32, [20])], - a dict of such tuple, mapping string names to tuple {"name": (dtype, shape}, e.g. {"input1":(tf.float32, [10]), "input2": (tf.float32, [20])} :param labels: the structure of input labels, format is the same as features :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param val_rdd: validation data with the same structure of rdd :return: a TFDataset """ return TFNdarrayDataset.from_rdd(*args, **kwargs) @staticmethod def from_ndarrays(*args, **kwargs): """ Create a TFDataset from a nested structure of numpy ndarrays. Each element in the resulting TFDataset has the same structure of the argument tensors and is created by indexing on the first dimension of each ndarray in the tensors argument. This method is equivalent to sc.parallize the tensors and call TFDataset.from_rdd :param tensors: the numpy ndarrays :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param val_tensors: the numpy ndarrays used for validation during training :return: """ return TFNdarrayDataset.from_ndarrays(*args, **kwargs) @staticmethod def from_image_set(image_set, image, label=None, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, validation_image_set=None): """ Create a TFDataset from a ImagetSet. Each ImageFeature in the ImageSet should already has the "sample" field, i.e. the result of ImageSetToSample transformer :param image_set: the ImageSet used to create this TFDataset :param image: a tuple of two, the first element is the type of image, the second element is the shape of this element, i.e. (tf.float32, [224, 224, 3])) :param label: a tuple of two, the first element is the type of label, the second element is the shape of this element, i.e. (tf.int32, [1])) :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param validation_image_set: the ImageSet used for validation during training :return: """ tensor_structure = TFDataset._to_tensor_structure(image, label) return TFImageDataset(image_set, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, validation_image_set) @staticmethod def from_text_set(text_set, text, label=None, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, validation_image_set=None): """ Create a TFDataset from a TextSet. The TextSet must be transformed to Sample, i.e. the result of TextFeatureToSample transformer. :param text_set: the TextSet used to create this TFDataset :param text: a tuple of two, the first element is the type of this input feature, the second element is the shape of this element, i.e. (tf.float32, [10, 100, 4])). text can also be nested structure of this tuple of two. :param label: a tuple of two, the first element is the type of label, the second element is the shape of this element, i.e. (tf.int32, [1])). label can also be nested structure of this tuple of two. :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param validation_image_set: The TextSet used for validation during training :return: """ tensor_structure = TFDataset._to_tensor_structure(text, label) return TFTextDataset(text_set, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, validation_image_set) @staticmethod def from_tfrecord(file_path, parse_fn, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, validation_file_path=None): """ Create a TFDataset from tfrecord files. :param file_path: comma seperated tfrecord file(s) path :param parse_fn: a TensorFlow function that takes a serialized example string to a nested structure of tensors. Follows the signature: * Args: * `example`: a string TensorFlow tensor representing a single record * Returns: a tuple or dictionary of output tensors and the output tensors must be of numeric type :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param validation_file_path: The tfrecord files used for validation :return: """ return TFRecordDataset(file_path, parse_fn, batch_size, batch_per_thread, hard_code_batch_size, validation_file_path) @staticmethod def from_feature_set(dataset, features, labels=None, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, validation_dataset=None): """ Create a TFDataset from a FeatureSet. Currently, the element in this Feature set must be a ImageFeature that has a sample field, i.e. the result of ImageSetToSample transformer :param dataset: the feature set used to create this TFDataset :param features: a tuple of two, the first element is the type of this input feature, the second element is the shape of this element, i.e. (tf.float32, [224, 224, 3])). text can also be nested structure of this tuple of two. :param labels: a tuple of two, the first element is the type of label, the second element is the shape of this element, i.e. (tf.int32, [1])). label can also be nested structure of this tuple of two. :param batch_size: the batch size, used for training, should be a multiple of total core num :param batch_per_thread: the batch size for each thread, used for inference or evaluation :param hard_code_batch_size: whether to hard code the batch_size into tensorflow graph, if True, the static size of the first dimension of the resulting tensors is batch_size/total_core_num (training) or batch_per_thread for inference; if False, it is None. :param validation_dataset: The FeatureSet used for validation during training :return: """ tensor_structure = TFDataset._to_tensor_structure(features, labels) return TFFeatureDataset(dataset, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, validation_dataset) class TFFeatureDataset(TFDataset): def __init__(self, dataset, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size=False, validation_dataset=None): super(TFFeatureDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.dataset = dataset self.validation_dataset = validation_dataset def get_prediction_data(self): raise Exception("TFFeatureDataset is only supported in training") def get_evaluation_data(self): raise Exception("TFFeatureDataset is only supported in training") def get_training_data(self): return self.dataset.transform(MergeFeatureLabelFeatureTransformer()).to_dataset() def get_validation_data(self): if self.validation_dataset is not None: return self.validation_dataset.transform( MergeFeatureLabelFeatureTransformer()).to_dataset() return None class TFRecordDataset(TFDataset): def get_num_partitions(self): self.train_rdd.getNumPartitions() def __init__(self, file_path, parse_fn, batch_size, batch_per_thread, hard_code_batch_size=False, validation_file_path=None): import tensorflow as tf g = tf.Graph() with g.as_default(): serialized_example = tf.placeholder(dtype=tf.string, shape=[]) results = parse_fn(serialized_example) flattened = nest.flatten(results) output_names = [tf.cast(t, dtype=tf.float32).name for t in flattened] serialized_graph = bytearray(g.as_graph_def().SerializeToString()) sc = getOrCreateSparkContext() train_rdd = callBigDlFunc("float", "createRDDFromTFRecords", file_path, sc, serialized_graph, serialized_example.name, output_names) validation_rdd = None if validation_file_path is not None: validation_rdd = callBigDlFunc("float", "createRDDFromTFRecords", validation_file_path, sc, serialized_graph, serialized_example.name, output_names) tensor_structure = nest.pack_sequence_as(results, [TensorMeta(tf.as_dtype(t.dtype), shape=t.shape, name="data_%s" % i) for i, t in enumerate(nest.flatten(results))]) super(TFRecordDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.train_rdd = train_rdd self.validation_rdd = validation_rdd def get_prediction_data(self): return self.train_rdd def get_evaluation_data(self): return self.train_rdd def get_training_data(self): return self.train_rdd def get_validation_data(self): return self.validation_rdd class TFTextDataset(TFDataset): def __init__(self, text_set, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size=False, validation_text_set=None): super(TFTextDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.text_set = text_set self.validation_text_set = validation_text_set def get_prediction_data(self): return self.text_set.get_samples().map( lambda sample: Sample.from_jtensor(features=sample.features, labels=JTensor.from_ndarray(np.array([0.0])))) def get_evaluation_data(self): return self.text_set.get_samples() def get_training_data(self): return self.text_set.get_samples().map( lambda sample: Sample.from_jtensor(features=sample.features + sample.labels, labels=JTensor.from_ndarray(np.array([0.0])))) def get_validation_data(self): if self.validation_text_set is not None: return self.validation_text_set.get_samples().map( lambda sample: Sample.from_jtensor(features=sample.features + sample.labels, labels=JTensor.from_ndarray(np.array([0.0])))) return None def get_num_partitions(self): return self.text_set.get_samples().getNumPartitions() class TFImageDataset(TFDataset): def __init__(self, image_set, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size=False, validation_image_set=None): super(TFImageDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.image_set = image_set self.validation_image_set = validation_image_set def get_prediction_data(self): return self.image_set def get_evaluation_data(self): return self.image_set.to_image_frame() def get_training_data(self): return DataSet.image_frame(self.image_set .transform(MergeFeatureLabelImagePreprocessing()) .to_image_frame()) def get_validation_data(self): if self.validation_image_set is not None: return DataSet.image_frame(self.validation_image_set. transform(MergeFeatureLabelImagePreprocessing()) .to_image_frame()) return None def get_num_partitions(self): return self.image_set.get_image().getNumPartitions() class TFNdarrayDataset(TFDataset): def __init__(self, rdd, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size=False, val_rdd=None): super(TFNdarrayDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.val_rdd = val_rdd self.rdd = rdd def get_prediction_data(self): data = self.rdd.map(lambda t: Sample.from_ndarray( nest.flatten(t[0] if isinstance(t, tuple) else t), np.array([0.0]))) return data def get_evaluation_data(self): if isinstance(self.tensor_structure, tuple): return self.rdd.map( lambda t: Sample.from_ndarray(nest.flatten(t[0]), nest.flatten(t[1]))) return self.rdd.map(lambda t: Sample.from_ndarray(nest.flatten(t), np.array([0.0]))) def get_training_data(self): return self.rdd.map(lambda t: Sample.from_ndarray(nest.flatten(t), np.array([0.0]))) def get_validation_data(self): if self.val_rdd is not None: return self.val_rdd.map(lambda t: Sample.from_ndarray(nest.flatten(t), np.array([0.0]))) return None def get_num_partitions(self): return self.rdd.getNumPartitions() @staticmethod def from_rdd(rdd, names=None, shapes=None, types=None, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, val_rdd=None, features=None, labels=None): import tensorflow as tf if features is not None: feature_structure = _to_tensor_structure(features) if labels is not None: label_structure = _to_tensor_structure(labels) tensor_structure = (feature_structure, label_structure) else: tensor_structure = (feature_structure,) return TFNdarrayDataset(rdd, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, val_rdd) if names is not None or shapes is not None or types is not None: if not names: names = ["features", "labels"] if not shapes: shapes = [None] * len(names) if not types: types = [tf.float32] * len(names) tensor_structure = [] for i in range(len(names)): tensor_structure.append(TensorMeta(types[i], name=names[i], shape=shapes[i])) else: tensor_structure = [TensorMeta(dtype=tf.float32), TensorMeta(dtype=tf.float32)] return TFNdarrayDataset(rdd, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, val_rdd) @staticmethod def from_ndarrays(tensors, batch_size=-1, batch_per_thread=-1, hard_code_batch_size=False, val_tensors=None): sc = getOrCreateSparkContext() node_num, core_num = get_node_and_core_number() total_core_num = node_num * core_num rdd, tensor_structure = _tensors_to_rdd(tensors, sc, total_core_num) val_rdd = None if val_tensors is not None: val_rdd, _ = _tensors_to_rdd(val_tensors, sc, total_core_num) return TFNdarrayDataset(rdd, tensor_structure, batch_size, batch_per_thread, hard_code_batch_size, val_rdd)
[ "tensorflow.Graph", "tensorflow.as_dtype", "tensorflow.cast", "tensorflow.placeholder", "numpy.dtype", "numpy.float32", "tensorflow.get_default_graph", "numpy.array", "tensorflow.add_to_collection" ]
pyzoo/zoo/pipeline/api/net/tf_dataset.py
[(67, 'zoo.util.nest.flatten', 'nest.flatten', (['tensors'], {}), False, 'from zoo.util import nest\n'), (133, 'bigdl.util.common.get_node_and_core_number', 'get_node_and_core_number', ([], {}), False, 'from bigdl.util.common import get_node_and_core_number, callBigDlFunc\n'), (199, 'zoo.util.nest.flatten', 'nest.flatten', (['tensors'], {}), False, 'from zoo.util import nest\n'), (517, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (527, 'zoo.common.nncontext.getOrCreateSparkContext', 'getOrCreateSparkContext', ([], {}), False, 'from zoo.common.nncontext import getOrCreateSparkContext\n'), (528, 'bigdl.util.common.callBigDlFunc', 'callBigDlFunc', (['"""float"""', '"""createRDDFromTFRecords"""', 'file_path', 'sc', 'serialized_graph', 'serialized_example.name', 'output_names'], {}), False, 'from bigdl.util.common import get_node_and_core_number, callBigDlFunc\n'), (701, 'zoo.common.nncontext.getOrCreateSparkContext', 'getOrCreateSparkContext', ([], {}), False, 'from zoo.common.nncontext import getOrCreateSparkContext\n'), (702, 'bigdl.util.common.get_node_and_core_number', 'get_node_and_core_number', ([], {}), False, 'from bigdl.util.common import get_node_and_core_number, callBigDlFunc\n'), (201, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tensor.name', 'self'], {}), True, 'import tensorflow as tf\n'), (519, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.string', 'shape': '[]'}), True, 'import tensorflow as tf\n'), (522, 'zoo.util.nest.flatten', 'nest.flatten', (['results'], {}), False, 'from zoo.util import nest\n'), (533, 'bigdl.util.common.callBigDlFunc', 'callBigDlFunc', (['"""float"""', '"""createRDDFromTFRecords"""', 'validation_file_path', 'sc', 'serialized_graph', 'serialized_example.name', 'output_names'], {}), False, 'from bigdl.util.common import get_node_and_core_number, callBigDlFunc\n'), (57, 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), True, 'import numpy as np\n'), (58, 'numpy.float32', 'np.float32', (['tensors[i]'], {}), True, 'import numpy as np\n'), (62, 'tensorflow.as_dtype', 'tf.as_dtype', (['t.dtype'], {}), True, 'import tensorflow as tf\n'), (69, 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), True, 'import numpy as np\n'), (70, 'numpy.float32', 'np.float32', (['flattened[i]'], {}), True, 'import numpy as np\n'), (73, 'zoo.util.nest.pack_sequence_as', 'nest.pack_sequence_as', (['tensors', 'x'], {}), False, 'from zoo.util import nest\n'), (75, 'tensorflow.as_dtype', 'tf.as_dtype', (['t.dtype'], {}), True, 'import tensorflow as tf\n'), (171, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (200, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (523, 'tensorflow.cast', 'tf.cast', (['t'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (538, 'tensorflow.as_dtype', 'tf.as_dtype', (['t.dtype'], {}), True, 'import tensorflow as tf\n'), (638, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (645, 'zoo.util.nest.flatten', 'nest.flatten', (['t'], {}), False, 'from zoo.util import nest\n'), (645, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (648, 'zoo.util.nest.flatten', 'nest.flatten', (['t'], {}), False, 'from zoo.util import nest\n'), (648, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (155, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (182, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (208, 'zoo.util.nest.flatten', 'nest.flatten', (['tensors'], {}), False, 'from zoo.util import nest\n'), (541, 'zoo.util.nest.flatten', 'nest.flatten', (['results'], {}), False, 'from zoo.util import nest\n'), (644, 'zoo.util.nest.flatten', 'nest.flatten', (['t[0]'], {}), False, 'from zoo.util import nest\n'), (644, 'zoo.util.nest.flatten', 'nest.flatten', (['t[1]'], {}), False, 'from zoo.util import nest\n'), (652, 'zoo.util.nest.flatten', 'nest.flatten', (['t'], {}), False, 'from zoo.util import nest\n'), (653, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (161, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (166, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (190, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (197, 'zoo.util.nest.flatten', 'nest.flatten', (['self.tensor_structure'], {}), False, 'from zoo.util import nest\n'), (574, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (582, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n'), (588, 'numpy.array', 'np.array', (['[0.0]'], {}), True, 'import numpy as np\n')]
mabounassif/t3f
28acf14812481f6a47ea6dbedeb55048e2e6203b
import numpy as np import tensorflow as tf from t3f.tensor_train import TensorTrain from t3f.tensor_train_batch import TensorTrainBatch from t3f.tensor_train_base import TensorTrainBase from t3f import shapes def _validate_input_parameters(is_tensor, shape, **params): """Internal function for validating input parameters Args: is_tensor: bool, determines whether we attempt to construct a TT-tensor or a TT-matrix (needed for the correct shape checks). shape: array, the desired shape of the generated TT object params: optional, possible values: batch_size: int, for constructing batches tt_rank: array or int, desired TT-ranks """ if is_tensor: if len(shape.shape) != 1: raise ValueError('shape should be 1d array, got %a' % shape) if np.any(shape < 1): raise ValueError('all elements in `shape` should be positive, got %a' % shape) if not all(isinstance(sh, np.integer) for sh in shape): raise ValueError('all elements in `shape` should be integers, got %a' % shape) else: if len(shape.shape) != 2: raise ValueError('shape should be 2d array, got %a' % shape) if shape[0].size != shape[1].size: raise ValueError('shape[0] should have the same length as shape[1], but' 'got %d and %d' % (shape[0].size, shape[1].size)) if np.any(shape.flatten() < 1): raise ValueError('all elements in `shape` should be positive, got %a' % shape) if not all(isinstance(sh, np.integer) for sh in shape.flatten()): raise ValueError('all elements in `shape` should be integers, got %a' % shape) if 'batch_size' in params: batch_size = params['batch_size'] if not isinstance(batch_size, (int, np.integer)): raise ValueError('`batch_size` should be integer, got %f' % batch_size) if batch_size < 1: raise ValueError('Batch size should be positive, got %d' % batch_size) if 'tt_rank' in params: tt_rank = params['tt_rank'] if tt_rank.size == 1: if not isinstance(tt_rank[()], np.integer): raise ValueError('`tt_rank` should be integer, got %f' % tt_rank[()]) if tt_rank.size > 1: if not all(isinstance(tt_r, np.integer) for tt_r in tt_rank): raise ValueError('all elements in `tt_rank` should be integers, got' ' %a' % tt_rank) if np.any(tt_rank < 1): raise ValueError('`tt_rank` should be positive, got %a' % tt_rank) if is_tensor: if tt_rank.size != 1 and tt_rank.size != (shape.size + 1): raise ValueError('`tt_rank` array has inappropriate size, expected' '1 or %d, got %d' % (shape.size + 1, tt_rank.size)) else: if tt_rank.size != 1 and tt_rank.size != (shape[0].size + 1): raise ValueError('`tt_rank` array has inappropriate size, expected' '1 or %d, got %d' % (shape[0].size + 1, tt_rank.size)) def tensor_ones(shape, dtype=tf.float32, name='t3f_tensor_ones'): """Generate TT-tensor of the given shape with all entries equal to 1. Args: shape: array representing the shape of the future tensor dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrain object containing a TT-tensor """ shape = np.array(shape) _validate_input_parameters(is_tensor=True, shape=shape) num_dims = shape.size tt_rank = np.ones(num_dims + 1) with tf.name_scope(name): tt_cores = num_dims * [None] for i in range(num_dims): curr_core_shape = (1, shape[i], 1) tt_cores[i] = tf.ones(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def tensor_zeros(shape, dtype=tf.float32, name='t3f_tensor_zeros'): """Generate TT-tensor of the given shape with all entries equal to 0. Args: shape: array representing the shape of the future tensor dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrain object containing a TT-tensor """ shape = np.array(shape) _validate_input_parameters(is_tensor=True, shape=shape) num_dims = shape.size tt_rank = np.ones(num_dims + 1) tt_cores = num_dims * [None] with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (1, shape[i], 1) tt_cores[i] = tf.zeros(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def eye(shape, dtype=tf.float32, name='t3f_eye'): """Creates an identity TT-matrix. Args: shape: array which defines the shape of the matrix row and column indices. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing an identity TT-matrix of size np.prod(shape) x np.prod(shape) """ shape = np.array(shape) # In this special case shape is in the same format as in the TT-tensor case _validate_input_parameters(is_tensor=True, shape=shape) num_dims = shape.size tt_ranks = np.ones(num_dims + 1) with tf.name_scope(name): tt_cores = num_dims * [None] for i in range(num_dims): curr_core_shape = (1, shape[i], shape[i], 1) tt_cores[i] = tf.reshape(tf.eye(shape[i], dtype=dtype), curr_core_shape) true_shape = np.vstack([shape, shape]) return TensorTrain(tt_cores, true_shape, tt_ranks) def matrix_ones(shape, dtype=tf.float32, name='t3f_matrix_ones'): """Generate a TT-matrix of the given shape with each entry equal to 1. Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. matrix_ones([[2, 2, 2], None]) and matrix_ones([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) with each entry equal to 1 """ shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) _validate_input_parameters(is_tensor=False, shape=shape) num_dims = shape[0].size tt_rank = np.ones(shape[0].size + 1) with tf.name_scope(name): tt_cores = [None] * num_dims for i in range(num_dims): curr_core_shape = (1, shape[0][i], shape[1][i], 1) tt_cores[i] = tf.ones(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def matrix_zeros(shape, dtype=tf.float32, name='t3f_matrix_zeros'): """Generate a TT-matrix of the given shape with each entry equal to 0. Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. matrix_zeros([[2, 2, 2], None]) and matrix_zeros([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) with each entry equal to 0 """ shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) _validate_input_parameters(is_tensor=False, shape=shape) num_dims = shape[0].size tt_rank = np.ones(shape[0].size + 1) with tf.name_scope(name): tt_cores = [None] * num_dims for i in range(num_dims): curr_core_shape = (1, shape[0][i], shape[1][i], 1) tt_cores[i] = tf.zeros(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def tensor_with_random_cores(shape, tt_rank=2, mean=0., stddev=1., dtype=tf.float32, name='t3f_tensor_with_random_cores'): """Generate a TT-tensor of the given shape with N(mean, stddev^2) cores. Args: shape: array representing the shape of the future tensor. tt_rank: a number or a (d+1)-element array with the desired ranks. mean: a number, the mean of the normal distribution used for initializing TT-cores. stddev: a number, the standard deviation of the normal distribution used for initializing TT-cores. dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrain containing a TT-tensor """ # TODO: good distribution to init training. # TODO: support shape and tt_ranks as TensorShape?. # TODO: support None as a dimension. shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=True, shape=shape, tt_rank=tt_rank) num_dims = shape.size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.insert(tt_rank, 0, 1) tt_rank = np.append(tt_rank, 1) tt_rank = tt_rank.astype(int) tt_cores = [None] * num_dims with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (tt_rank[i], shape[i], tt_rank[i + 1]) tt_cores[i] = tf.random_normal(curr_core_shape, mean=mean, stddev=stddev, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def tensor_batch_with_random_cores(shape, tt_rank=2, batch_size=1, mean=0., stddev=1., dtype=tf.float32, name='t3f_tensor_batch_with_random_cores'): """Generate a batch of TT-tensors of given shape with N(mean, stddev^2) cores. Args: shape: array representing the shape of the future tensor. tt_rank: a number or a (d+1)-element array with ranks. batch_size: an integer. mean: a number, the mean of the normal distribution used for initializing TT-cores. stddev: a number, the standard deviation of the normal distribution used for initializing TT-cores. dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrainBatch containing TT-tensors """ # TODO: support shape and tt_ranks as TensorShape?. # TODO: support None as a dimension. shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=True, shape=shape, tt_rank=tt_rank, batch_size=batch_size) num_dims = shape.size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.insert(tt_rank, 0, 1) tt_rank = np.append(tt_rank, 1) tt_rank = tt_rank.astype(int) tt_cores = [None] * num_dims with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (batch_size, tt_rank[i], shape[i], tt_rank[i + 1]) tt_cores[i] = tf.random_normal(curr_core_shape, mean=mean, stddev=stddev, dtype=dtype) return TensorTrainBatch(tt_cores, shape, tt_rank, batch_size) def matrix_with_random_cores(shape, tt_rank=2, mean=0., stddev=1., dtype=tf.float32, name='t3f_matrix_with_random_cores'): """Generate a TT-matrix of given shape with N(mean, stddev^2) cores. Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. matrix_with_random_cores([[2, 2, 2], None]) and matrix_with_random_cores([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. tt_rank: a number or a (d+1)-element array with ranks. mean: a number, the mean of the normal distribution used for initializing TT-cores. stddev: a number, the standard deviation of the normal distribution used for initializing TT-cores. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) """ # TODO: good distribution to init training. # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank) num_dims = shape[0].size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.concatenate([[1], tt_rank, [1]]) tt_rank = tt_rank.astype(int) tt_cores = [None] * num_dims with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (tt_rank[i], shape[0][i], shape[1][i], tt_rank[i + 1]) tt_cores[i] = tf.random_normal(curr_core_shape, mean=mean, stddev=stddev, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def matrix_batch_with_random_cores(shape, tt_rank=2, batch_size=1, mean=0., stddev=1., dtype=tf.float32, name='t3f_matrix_batch_with_random_cores'): """Generate a batch of TT-matrices of given shape with N(mean, stddev^2) cores. Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. matrix_batch_with_random_cores([[2, 2, 2], None]) and matrix_batch_with_random_cores([None, [2, 2, 2]]) will create a batch of one 8-element column and row vector correspondingly. tt_rank: a number or a (d+1)-element array with ranks. batch_size: an integer. mean: a number, the mean of the normal distribution used for initializing TT-cores. stddev: a number, the standard deviation of the normal distribution used for initializing TT-cores. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrainBatch containing a batch of TT-matrices of size np.prod(shape[0]) x np.prod(shape[1]) """ # TODO: good distribution to init training. # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank, batch_size=batch_size) num_dims = shape[0].size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.concatenate([[1], tt_rank, [1]]) shape = shape.astype(int) tt_rank = tt_rank.astype(int) tt_cores = [None] * num_dims with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (batch_size, tt_rank[i], shape[0][i], shape[1][i], tt_rank[i + 1]) tt_cores[i] = tf.random_normal(curr_core_shape, mean=mean, stddev=stddev, dtype=dtype) return TensorTrainBatch(tt_cores, shape, tt_rank, batch_size) def ones_like(tt, name='t3f_ones_like'): """Constructs t3f.ones with the shape of `tt`. In the case when `tt` is TensorTrainBatch constructs t3f.ones with the shape of a TensorTrain in `tt`. Args: tt: TensorTrain object name: string, name of the Op. Returns: TensorTrain object of the same shape as `tt` but with all entries equal to 1. """ if not isinstance(tt, TensorTrainBase): raise ValueError("`tt` has to be a Tensor Train object") else: shape = shapes.lazy_raw_shape(tt) # I guess variables=tt.tt_cores is not needed here since the output of # the function doesn't depend on the values of the TT-cores, only on their # shapes etc. But I'm not 100% sure. with tf.name_scope(name): if tt.is_tt_matrix(): return matrix_ones(shape, dtype=tt.dtype) else: return tensor_ones(shape[0, :], dtype=tt.dtype) def zeros_like(tt, name='t3f_zeros_like'): """Constructs t3f.zeros with the shape of `tt`. In the case when `tt` is a TensorTrainBatch constructs t3f.zeros with the shape of a TensorTrain in `tt`. Args: tt: TensorTrain object name: string, name of the Op. Returns: TensorTrain object of the same shape as `tt` but with all entries equal to 0. """ if not isinstance(tt, TensorTrainBase): raise ValueError("`tt` has to be a Tensor Train object") else: shape = shapes.lazy_raw_shape(tt) # I guess variables=tt.tt_cores is not needed here since the output of # the function doesn't depend on the values of the TT-cores, only on their # shapes etc. But I'm not 100% sure. with tf.name_scope(name): if tt.is_tt_matrix(): return matrix_zeros(shape, dtype=tt.dtype) else: return tensor_zeros(shape[0, :], dtype=tt.dtype) def random_tensor(shape, tt_rank=2, mean=0., stddev=1., dtype=tf.float32, name='t3f_random_tensor'): """Generate a random TT-tensor of the given shape with given mean and stddev. Entries of the generated tensor (in the full format) will be iid and satisfy E[x_{i1i2..id}] = mean, Var[x_{i1i2..id}] = stddev^2, but the distribution is in fact not Gaussian (but is close for large tensors). In the current implementation only mean 0 is supported. To get a random_tensor with specified mean but tt_rank greater by 1 you can call x = t3f.random_tensor(shape, tt_rank, stddev=stddev) x = mean * t3f.ones_like(x) + x Args: shape: array representing the shape of the future tensor. tt_rank: a number or a (d+1)-element array with the desired ranks. mean: a number, the desired mean for the distribution of entries. stddev: a number, the desired standard deviation for the distribution of entries. dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrain containing a TT-tensor """ shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=True, shape=shape, tt_rank=tt_rank) num_dims = shape.size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.insert(tt_rank, 0, 1) tt_rank = np.append(tt_rank, 1) tt_rank = tt_rank.astype(int) # Empirically entries of a TT tensor with cores initialized from N(0, 1) # will have variances np.prod(tt_rank) and mean 0. # We scale each TT-core to obtain the desired stddev cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) core_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = tensor_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet') def random_tensor_batch(shape, tt_rank=2, batch_size=1, mean=0., stddev=1., dtype=tf.float32, name='t3f_random_tensor_batch'): """Generate a batch of TT-tensors with given shape, mean and stddev. Entries of the generated tensors (in the full format) will be iid and satisfy E[x_{i1i2..id}] = mean, Var[x_{i1i2..id}] = stddev^2, but the distribution is in fact not Gaussian (but is close for large tensors). In the current implementation only mean 0 is supported. To get a random_tensor_batch with specified mean but tt_rank greater by 1 you can call x = t3f.random_tensor_batch(shape, tt_rank, batch_size=bs, stddev=stddev) x = mean * t3f.ones_like(x) + x Args: shape: array representing the shape of the future tensor. tt_rank: a number or a (d+1)-element array with ranks. batch_size: an integer. mean: a number, the desired mean for the distribution of entries. stddev: a number, the desired standard deviation for the distribution of entries. dtype: [tf.float32] dtype of the resulting tensor. name: string, name of the Op. Returns: TensorTrainBatch containing TT-tensors. """ # TODO: support shape and tt_ranks as TensorShape?. # TODO: support None as a dimension. shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=True, shape=shape, tt_rank=tt_rank, batch_size=batch_size) num_dims = shape.size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.insert(tt_rank, 0, 1) tt_rank = np.append(tt_rank, 1) tt_rank = tt_rank.astype(int) cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) cr_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = tensor_batch_with_random_cores(shape, tt_rank=tt_rank, stddev=cr_stddev, batch_size=batch_size, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet') def random_matrix(shape, tt_rank=2, mean=0., stddev=1., dtype=tf.float32, name='t3f_random_matrix'): """Generate a random TT-matrix of the given shape with given mean and stddev. Entries of the generated matrix (in the full format) will be iid and satisfy E[x_{i1i2..id}] = mean, Var[x_{i1i2..id}] = stddev^2, but the distribution is in fact not Gaussian. In the current implementation only mean 0 is supported. To get a random_matrix with specified mean but tt_rank greater by 1 you can call x = t3f.random_matrix(shape, tt_rank, stddev=stddev) x = mean * t3f.ones_like(x) + x Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. random_matrix([[2, 2, 2], None]) and random_matrix([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. tt_rank: a number or a (d+1)-element array with ranks. mean: a number, the desired mean for the distribution of entries. stddev: a number, the desired standard deviation for the distribution of entries. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) """ # TODO: good distribution to init training. # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank) num_dims = shape[0].size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.concatenate([[1], tt_rank, [1]]) tt_rank = tt_rank.astype(int) var = np.prod(tt_rank) # Empirically entries of a TT tensor with cores initialized from N(0, 1) # will have variances np.prod(tt_rank) and mean 0. # We scale each TT-core to obtain the desired stddev cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) core_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = matrix_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet') def random_matrix_batch(shape, tt_rank=2, batch_size=1, mean=0., stddev=1., dtype=tf.float32, name='t3f_random_matrix_batch'): """Generate a batch of TT-matrices with given shape, mean and stddev. Entries of the generated matrices (in the full format) will be iid and satisfy E[x_{i1i2..id}] = mean, Var[x_{i1i2..id}] = stddev^2, but the distribution is in fact not Gaussian. In the current implementation only mean 0 is supported. To get a random_matrix_batch with specified mean but tt_rank greater by 1 you can call x = t3f.random_matrix_batch(shape, tt_rank, batch_size=bs, stddev=stddev) x = mean * t3f.ones_like(x) + x Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. random_matrix_batch([[2, 2, 2], None]) and random_matrix_batch([None, [2, 2, 2]]) will create a batch of one 8-element column and row vector correspondingly. tt_rank: a number or a (d+1)-element array with ranks. batch_size: an integer. mean: a number, the desired mean for the distribution of entries. stddev: a number, the desired standard deviation for the distribution of entries. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrainBatch containing a batch of TT-matrices of size np.prod(shape[0]) x np.prod(shape[1]) """ # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank, batch_size=batch_size) num_dims = shape[0].size if tt_rank.size == 1: tt_rank = tt_rank * np.ones(num_dims - 1) tt_rank = np.concatenate([[1], tt_rank, [1]]) shape = shape.astype(int) tt_rank = tt_rank.astype(int) cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) core_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = matrix_batch_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev, batch_size=batch_size, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet') def glorot_initializer(shape, tt_rank=2, dtype=tf.float32, name='t3f_glorot_initializer'): """Constructs a random TT matrix with entrywise variance 2.0 / (n_in + n_out) Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. glorot_initializer([[2, 2, 2], None]) and glorot_initializer([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. tt_rank: a number or a (d+1)-element array with ranks. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) """ # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank) n_in = np.prod(shape[0]) n_out = np.prod(shape[1]) lamb = 2.0 / (n_in + n_out) with tf.name_scope(name): return random_matrix(shape, tt_rank=tt_rank, stddev=np.sqrt(lamb), dtype=dtype) def he_initializer(shape, tt_rank=2, dtype=tf.float32, name='t3f_he_initializer'): """Constructs a random TT matrix with entrywise variance 2.0 / n_in Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. he_initializer([[2, 2, 2], None]) and he_initializer([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. tt_rank: a number or a (d+1)-element array with ranks. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) """ # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank) n_in = np.prod(shape[0]) lamb = 2.0 / n_in with tf.name_scope(name): return random_matrix(shape, tt_rank=tt_rank, stddev=np.sqrt(lamb), dtype=dtype) def lecun_initializer(shape, tt_rank=2, dtype=tf.float32, name='t3f_lecun_initializer'): """Constructs a random TT matrix with entrywise variance 1.0 / n_in Args: shape: 2d array, shape[0] is the shape of the matrix row-index, shape[1] is the shape of the column index. shape[0] and shape[1] should have the same number of elements (d) Also supports omitting one of the dimensions for vectors, e.g. lecun_initializer([[2, 2, 2], None]) and lecun_initializer([None, [2, 2, 2]]) will create an 8-element column and row vectors correspondingly. tt_rank: a number or a (d+1)-element array with ranks. dtype: [tf.float32] dtype of the resulting matrix. name: string, name of the Op. Returns: TensorTrain containing a TT-matrix of size np.prod(shape[0]) x np.prod(shape[1]) """ # In case the shape is immutable. shape = list(shape) # In case shape represents a vector, e.g. [None, [2, 2, 2]] if shape[0] is None: shape[0] = np.ones(len(shape[1]), dtype=int) # In case shape represents a vector, e.g. [[2, 2, 2], None] if shape[1] is None: shape[1] = np.ones(len(shape[0]), dtype=int) shape = np.array(shape) tt_rank = np.array(tt_rank) _validate_input_parameters(is_tensor=False, shape=shape, tt_rank=tt_rank) n_in = np.prod(shape[0]) lamb = 1.0 / n_in with tf.name_scope(name): return random_matrix(shape, tt_rank=tt_rank, stddev=np.sqrt(lamb), dtype=dtype)
[ "numpy.abs", "numpy.sqrt", "tensorflow.zeros", "tensorflow.ones", "tensorflow.eye", "numpy.ones", "numpy.concatenate", "numpy.append", "tensorflow.name_scope", "numpy.any", "numpy.prod", "numpy.insert", "numpy.array", "numpy.vstack", "tensorflow.random_normal" ]
t3f/initializers.py
[(84, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (87, 'numpy.ones', 'np.ones', (['(num_dims + 1)'], {}), True, 'import numpy as np\n'), (110, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (113, 'numpy.ones', 'np.ones', (['(num_dims + 1)'], {}), True, 'import numpy as np\n'), (136, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (141, 'numpy.ones', 'np.ones', (['(num_dims + 1)'], {}), True, 'import numpy as np\n'), (180, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (185, 'numpy.ones', 'np.ones', (['(shape[0].size + 1)'], {}), True, 'import numpy as np\n'), (223, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (227, 'numpy.ones', 'np.ones', (['(shape[0].size + 1)'], {}), True, 'import numpy as np\n'), (259, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (260, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (301, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (302, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (356, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (357, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (414, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (415, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (519, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (520, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (536, 'numpy.prod', 'np.prod', (['(tt_rank ** cr_exponent)'], {}), True, 'import numpy as np\n'), (577, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (578, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (589, 'numpy.prod', 'np.prod', (['(tt_rank ** cr_exponent)'], {}), True, 'import numpy as np\n'), (643, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (644, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (654, 'numpy.prod', 'np.prod', (['tt_rank'], {}), True, 'import numpy as np\n'), (661, 'numpy.prod', 'np.prod', (['(tt_rank ** cr_exponent)'], {}), True, 'import numpy as np\n'), (715, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (716, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (728, 'numpy.prod', 'np.prod', (['(tt_rank ** cr_exponent)'], {}), True, 'import numpy as np\n'), (772, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (773, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (775, 'numpy.prod', 'np.prod', (['shape[0]'], {}), True, 'import numpy as np\n'), (776, 'numpy.prod', 'np.prod', (['shape[1]'], {}), True, 'import numpy as np\n'), (814, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (815, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (817, 'numpy.prod', 'np.prod', (['shape[0]'], {}), True, 'import numpy as np\n'), (855, 'numpy.array', 'np.array', (['shape'], {}), True, 'import numpy as np\n'), (856, 'numpy.array', 'np.array', (['tt_rank'], {}), True, 'import numpy as np\n'), (858, 'numpy.prod', 'np.prod', (['shape[0]'], {}), True, 'import numpy as np\n'), (25, 'numpy.any', 'np.any', (['(shape < 1)'], {}), True, 'import numpy as np\n'), (59, 'numpy.any', 'np.any', (['(tt_rank < 1)'], {}), True, 'import numpy as np\n'), (89, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (95, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (115, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (120, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (143, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (149, 'numpy.vstack', 'np.vstack', (['[shape, shape]'], {}), True, 'import numpy as np\n'), (150, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'true_shape', 'tt_ranks'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (187, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (193, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (229, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (235, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (265, 'numpy.insert', 'np.insert', (['tt_rank', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (266, 'numpy.append', 'np.append', (['tt_rank', '(1)'], {}), True, 'import numpy as np\n'), (270, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (276, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (308, 'numpy.insert', 'np.insert', (['tt_rank', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (309, 'numpy.append', 'np.append', (['tt_rank', '(1)'], {}), True, 'import numpy as np\n'), (312, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (318, 't3f.tensor_train_batch.TensorTrainBatch', 'TensorTrainBatch', (['tt_cores', 'shape', 'tt_rank', 'batch_size'], {}), False, 'from t3f.tensor_train_batch import TensorTrainBatch\n'), (363, 'numpy.concatenate', 'np.concatenate', (['[[1], tt_rank, [1]]'], {}), True, 'import numpy as np\n'), (367, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (374, 't3f.tensor_train.TensorTrain', 'TensorTrain', (['tt_cores', 'shape', 'tt_rank'], {}), False, 'from t3f.tensor_train import TensorTrain\n'), (421, 'numpy.concatenate', 'np.concatenate', (['[[1], tt_rank, [1]]'], {}), True, 'import numpy as np\n'), (425, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (432, 't3f.tensor_train_batch.TensorTrainBatch', 'TensorTrainBatch', (['tt_cores', 'shape', 'tt_rank', 'batch_size'], {}), False, 'from t3f.tensor_train_batch import TensorTrainBatch\n'), (453, 't3f.shapes.lazy_raw_shape', 'shapes.lazy_raw_shape', (['tt'], {}), False, 'from t3f import shapes\n'), (482, 't3f.shapes.lazy_raw_shape', 'shapes.lazy_raw_shape', (['tt'], {}), False, 'from t3f import shapes\n'), (526, 'numpy.insert', 'np.insert', (['tt_rank', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (527, 'numpy.append', 'np.append', (['tt_rank', '(1)'], {}), True, 'import numpy as np\n'), (538, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (542, 'numpy.abs', 'np.abs', (['mean'], {}), True, 'import numpy as np\n'), (584, 'numpy.insert', 'np.insert', (['tt_rank', '(0)', '(1)'], {}), True, 'import numpy as np\n'), (585, 'numpy.append', 'np.append', (['tt_rank', '(1)'], {}), True, 'import numpy as np\n'), (591, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (595, 'numpy.abs', 'np.abs', (['mean'], {}), True, 'import numpy as np\n'), (651, 'numpy.concatenate', 'np.concatenate', (['[[1], tt_rank, [1]]'], {}), True, 'import numpy as np\n'), (663, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (667, 'numpy.abs', 'np.abs', (['mean'], {}), True, 'import numpy as np\n'), (722, 'numpy.concatenate', 'np.concatenate', (['[[1], tt_rank, [1]]'], {}), True, 'import numpy as np\n'), (730, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (736, 'numpy.abs', 'np.abs', (['mean'], {}), True, 'import numpy as np\n'), (779, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (820, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (860, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.ones', 'tf.ones', (['curr_core_shape'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (118, 'tensorflow.zeros', 'tf.zeros', (['curr_core_shape'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.ones', 'tf.ones', (['curr_core_shape'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.zeros', 'tf.zeros', (['curr_core_shape'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (264, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (273, 'tensorflow.random_normal', 'tf.random_normal', (['curr_core_shape'], {'mean': 'mean', 'stddev': 'stddev', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (307, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (315, 'tensorflow.random_normal', 'tf.random_normal', (['curr_core_shape'], {'mean': 'mean', 'stddev': 'stddev', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (362, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (371, 'tensorflow.random_normal', 'tf.random_normal', (['curr_core_shape'], {'mean': 'mean', 'stddev': 'stddev', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (420, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (429, 'tensorflow.random_normal', 'tf.random_normal', (['curr_core_shape'], {'mean': 'mean', 'stddev': 'stddev', 'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (457, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (486, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (525, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (583, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (650, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (721, 'numpy.ones', 'np.ones', (['(num_dims - 1)'], {}), True, 'import numpy as np\n'), (147, 'tensorflow.eye', 'tf.eye', (['shape[i]'], {'dtype': 'dtype'}), True, 'import tensorflow as tf\n'), (780, 'numpy.sqrt', 'np.sqrt', (['lamb'], {}), True, 'import numpy as np\n'), (821, 'numpy.sqrt', 'np.sqrt', (['lamb'], {}), True, 'import numpy as np\n'), (861, 'numpy.sqrt', 'np.sqrt', (['lamb'], {}), True, 'import numpy as np\n')]
mabounassif/t3f
28acf14812481f6a47ea6dbedeb55048e2e6203b
import tensorflow as tf from t3f.tensor_train_base import TensorTrainBase from t3f import shapes class TensorTrain(TensorTrainBase): """Represents a Tensor Train object (a TT-tensor or TT-matrix). t3f represents a Tensor Train object as a tuple of TT-cores. """ def __init__(self, tt_cores, shape=None, tt_ranks=None, convert_to_tensors=True, name="TensorTrain"): """Creates a `TensorTrain`. Args: tt_cores: A tuple of 3d or 4d tensor-like objects of shape `[r_k-1, n_k, r_k]`. Tensor-like can be numpy array, tf.Tensor, of tf.Variable shape: Shape of the underlying tensor. If None, tries to infer from the cores (not always possible even if it should be, e.g. if ranks are unknown, than the whole shape of a core can be unknown). tt_ranks: a TensorShape of length d+1 (d is the dimensionality of the underlying tensor). The first and the last ranks are assumed to equal to 1. If None, tries to infer the ranks from the cores. convert_to_tensors: bool, if True than convert each element of the tt_cores tuple into a tf.Tensor (e.g. to initialize from np.array) name: The name of ops. Returns: A `TensorTrain`. Raises: ValueError if the provided TT-cores are not valid or inconsistent with the provided shape. """ tt_cores = list(tt_cores) if convert_to_tensors: with tf.name_scope(name): for i in range(len(tt_cores)): name = "core%d" % i tt_cores[i] = tf.convert_to_tensor(tt_cores[i], name=name) if not _are_tt_cores_valid(tt_cores, shape, tt_ranks): raise ValueError('The tt_cores provided to TensorTrain constructor are ' 'not valid, have different dtypes, or are inconsistent ' 'with the provided shape or TT-ranks.') self._tt_cores = tuple(tt_cores) self._raw_shape = shapes.clean_raw_shape(shape) if self._raw_shape is None: self._raw_shape = _infer_raw_shape(self._tt_cores) self._tt_ranks = None if tt_ranks is None else tf.TensorShape(tt_ranks) if self._tt_ranks is None: self._tt_ranks = _infer_tt_ranks(self._tt_cores) @property def tt_cores(self): """A tuple of TT-cores. Returns: A tuple of 3d or 4d tensors shape `[r_k-1, n_k, r_k]` or `[r_k-1, n_k, m_k, r_k]` """ return self._tt_cores @property def left_tt_rank_dim(self): """The dimension of the left TT-rank in each TT-core.""" return 0 @property def right_tt_rank_dim(self): """The dimension of the right TT-rank in each TT-core.""" if self.is_tt_matrix(): # The dimensions of each TT-core are # [left_rank, n, m, right_rank] return 3 else: # The dimensions of each TT-core are # [left_rank, n, right_rank] return 2 def __str__(self): """A string describing the TensorTrain object, its TT-rank, and shape.""" shape = self.get_shape() tt_ranks = self.get_tt_ranks() variable_str = ' variable' if self.is_variable() else '' if self.is_tt_matrix(): raw_shape = self.get_raw_shape() return "A TT-Matrix%s of size %d x %d, underlying tensor " \ "shape: %s x %s, TT-ranks: %s" % (variable_str, shape[0], shape[1], raw_shape[0], raw_shape[1], tt_ranks) else: return "A Tensor Train%s of shape %s, TT-ranks: %s" % (variable_str, shape, tt_ranks) def __getitem__(self, slice_spec): """Basic indexing, returns a `TensorTrain` containing the specified region. Examples: >>> a = t3f.random_tensor((2, 3, 4)) >>> a[1, :, :] is a 2D TensorTrain 3 x 4. >>> a[1:2, :, :] is a 3D TensorTrain 1 x 3 x 4 """ if len(slice_spec) != self.ndims(): raise ValueError('Expected %d indices, got %d' % (self.ndims(), len(slice_spec))) new_tt_cores = [] remainder = None for i in range(self.ndims()): curr_core = self.tt_cores[i] if self.is_tt_matrix(): raise NotImplementedError else: sliced_core = curr_core[:, slice_spec[i], :] if len(curr_core.get_shape()) != len(sliced_core.get_shape()): # This index is specified exactly and we want to collapse this axis. if remainder is None: remainder = sliced_core else: remainder = tf.matmul(remainder, sliced_core) else: if remainder is not None: # Add reminder from the previous collapsed cores to the current # core. sliced_core = tf.einsum('ab,bid->aid', remainder, sliced_core) remainder = None new_tt_cores.append(sliced_core) if remainder is not None: # The reminder obtained from collapsing the last cores. new_tt_cores[-1] = tf.einsum('aib,bd->aid', new_tt_cores[-1], remainder) remainder = None # TODO: infer the output ranks and shape. return TensorTrain(new_tt_cores) def _are_tt_cores_valid(tt_cores, shape, tt_ranks): """Check if dimensions of the TT-cores are consistent and the dtypes coincide. Args: tt_cores: a tuple of `Tensor` objects shape: An np.array, a tf.TensorShape (for tensors), a tuple of tf.TensorShapes (for TT-matrices or tensors), or None tt_ranks: An np.array or a tf.TensorShape of length len(tt_cores)+1. Returns: boolean, True if the dimensions and dtypes are consistent. """ shape = shapes.clean_raw_shape(shape) num_dims = len(tt_cores) for core_idx in range(1, num_dims): if tt_cores[core_idx].dtype != tt_cores[0].dtype: return False try: for core_idx in range(num_dims): curr_core_shape = tt_cores[core_idx].get_shape() if len(curr_core_shape) != len(tt_cores[0].get_shape()): # Shapes are inconsistent. return False if shape is not None: for i in range(len(shape)): if curr_core_shape[i + 1] != shape[i][core_idx]: # The TT-cores are not aligned with the given shape. return False if core_idx >= 1: prev_core_shape = tt_cores[core_idx - 1].get_shape() if curr_core_shape[0] != prev_core_shape[-1]: # TT-ranks are inconsistent. return False if tt_ranks is not None: if curr_core_shape[0] != tt_ranks[core_idx]: # The TT-ranks are not aligned with the TT-cores shape. return False if curr_core_shape[-1] != tt_ranks[core_idx + 1]: # The TT-ranks are not aligned with the TT-cores shape. return False if tt_cores[0].get_shape()[0] != 1 or tt_cores[-1].get_shape()[-1] != 1: # The first or the last rank is not 1. return False except ValueError: # The shape of the TT-cores is undetermined, can not validate it. pass return True def _infer_raw_shape(tt_cores): """Tries to infer the (static) raw shape from the TT-cores.""" num_dims = len(tt_cores) num_tensor_shapes = len(tt_cores[0].get_shape().as_list()) - 2 raw_shape = [[] for _ in range(num_tensor_shapes)] for dim in range(num_dims): curr_core_shape = tt_cores[dim].get_shape() for i in range(num_tensor_shapes): raw_shape[i].append(curr_core_shape[i + 1]) for i in range(num_tensor_shapes): raw_shape[i] = tf.TensorShape(raw_shape[i]) return tuple(raw_shape) def _infer_tt_ranks(tt_cores): """Tries to infer the (static) raw shape from the TT-cores.""" tt_ranks = [] for i in range(len(tt_cores)): tt_ranks.append(tt_cores[i].get_shape()[0]) tt_ranks.append(tt_cores[-1].get_shape()[-1]) return tf.TensorShape(tt_ranks)
[ "tensorflow.convert_to_tensor", "tensorflow.TensorShape", "tensorflow.matmul", "tensorflow.einsum", "tensorflow.name_scope" ]
t3f/tensor_train.py
[(157, 't3f.shapes.clean_raw_shape', 'shapes.clean_raw_shape', (['shape'], {}), False, 'from t3f import shapes\n'), (215, 'tensorflow.TensorShape', 'tf.TensorShape', (['tt_ranks'], {}), True, 'import tensorflow as tf\n'), (51, 't3f.shapes.clean_raw_shape', 'shapes.clean_raw_shape', (['shape'], {}), False, 'from t3f import shapes\n'), (205, 'tensorflow.TensorShape', 'tf.TensorShape', (['raw_shape[i]'], {}), True, 'import tensorflow as tf\n'), (54, 'tensorflow.TensorShape', 'tf.TensorShape', (['tt_ranks'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.einsum', 'tf.einsum', (['"""aib,bd->aid"""', 'new_tt_cores[-1]', 'remainder'], {}), True, 'import tensorflow as tf\n'), (40, 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (43, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['tt_cores[i]'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.matmul', 'tf.matmul', (['remainder', 'sliced_core'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.einsum', 'tf.einsum', (['"""ab,bid->aid"""', 'remainder', 'sliced_core'], {}), True, 'import tensorflow as tf\n')]
leopauly/Observation-Learning-Simulations
462c04a87c45aae51537b8ea5b44646afa31d3a5
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import gfile import imageio import pickle import scipy.misc import sys from IPython.display import HTML import imageio import argparse def transform(image, resize_height=36, resize_width=64): cropped_image = scipy.misc.imresize(image, [resize_height, resize_width]) return np.array(cropped_image)/127.5 - 1. def inverse_transform(images): return (images+1.)/2. def lrelu(x, leak=0.2, name="lrelu"): return tf.maximum(x, leak*x) def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name="conv2d"): with tf.variable_scope(name): w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev)) # print("c", w.get_shape()) conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME') biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0)) conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape()) return conv class batch_norm(object): def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"): with tf.variable_scope(name): self.epsilon = epsilon self.momentum = momentum self.name = name def __call__(self, x): return tf.contrib.layers.batch_norm(x, decay=self.momentum, updates_collections=None, epsilon=self.epsilon, scale=True, is_training=tftrain, scope=self.name) def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False): shape = input_.get_shape().as_list() with tf.variable_scope(scope or "Linear"): matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev)) bias = tf.get_variable("bias", [output_size], initializer=tf.constant_initializer(bias_start)) if with_w: return tf.matmul(input_, matrix) + bias, matrix, bias else: return tf.matmul(input_, matrix) + bias def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name="deconv2d", with_w=False): with tf.variable_scope(name): # filter : [height, width, output_channels, in_channels] w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) # print("w", w.get_shape()) try: deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape, strides=[1, d_h, d_w, 1]) # Support for verisons of TensorFlow before 0.7.0 except AttributeError: deconv = tf.nn.deconv2d(input_, w, output_shape=output_shape, strides=[1, d_h, d_w, 1]) biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) if with_w: return deconv, w, biases else: return deconv class ContextAEPushReal: def __init__(self, gf_dim=64, df_dim=64, gfc_dim=1024, dfc_dim=1024, c_dim=3): self.gf_dim = gf_dim self.df_dim = df_dim self.c_dim = c_dim self.gfc_dim = gfc_dim self.dfc_dim = dfc_dim def build(self, image, ablation_type): imgshape = image.get_shape().as_list() print(imgshape) self.output_height, self.output_width = imgshape[-3:-1] self.batch_size = imgshape[1] featsize = 100 srcimg = image[0] tgtimg = image[2] tgtctx = image[1] nf0 = 32 nf1 = 16 nf2 = 16 nf3 = 8 ns0 = 1 ns1 = 2 ns2 = 1 ns3 = 2 # with tf.variable_scope("conv_context") as scope: def encode(img): img_h0 = lrelu(conv2d(img, nf0, d_h=ns0, d_w=ns0, name='h0_conv')) img_h1 = lrelu(conv2d(img_h0, nf1, d_h=ns1, d_w=ns1, name='h1_conv')) img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv')) img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv')) print(img_h3.get_shape()) img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin')) img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin')) return img_h0, img_h1, img_h2, img_h3, img_h4, img_z with tf.variable_scope("conv") as scope: srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg) scope.reuse_variables() tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg) tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0')) trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z') self.translated_z = trans_z s_h, s_w = self.output_height, self.output_width s_h0, s_h1, s_h2, s_h3 = \ int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3) s_w0, s_w1, s_w2, s_w3 = \ int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3) def decode(z, skip_h3, skip_h2, skip_h1, skip_h0): z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin')) h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob) h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3), [self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3)) h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3), [self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2)) h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3), [self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1)) print(h3.get_shape()) h4 = deconv2d(tf.concat([h3, skip_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0) return h4 with tf.variable_scope("deconv") as scope: output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) scope.reuse_variables() truthoutput_h4 = decode(tgtimg_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 print(tgtimg_z.get_shape()) self.out = output_h4 self.out2 = truthoutput_h4 print(self.out.get_shape()) self.recon1 = tf.nn.l2_loss(tgtimg - self.out) self.recon2 = tf.nn.l2_loss(tgtimg - self.out2) if ablation_type == "None": self.loss = self.recon1 + self.recon2 + self.simloss elif ablation_type == "L2": self.loss = self.recon1 + self.recon2 elif ablation_type == "L2L3": self.loss = self.recon1 elif ablation_type == "L1": self.loss = self.recon2 + self.simloss class ContextAEPush: def __init__(self, gf_dim=64, df_dim=64, gfc_dim=1024, dfc_dim=1024, c_dim=3): self.gf_dim = gf_dim self.df_dim = df_dim self.c_dim = c_dim self.gfc_dim = gfc_dim self.dfc_dim = dfc_dim def build(self, image, ablation_type): imgshape = image.get_shape().as_list() print(imgshape) self.output_height, self.output_width = imgshape[-3:-1] self.batch_size = imgshape[1] featsize = 1024 srcimg = image[0] tgtimg = image[2] tgtctx = image[1] with tf.variable_scope("conv_context") as scope: tgtctx_h0 = lrelu(conv2d(tgtctx, self.df_dim, name='h0_conv')) tgtctx_h1 = lrelu(conv2d(tgtctx_h0, self.df_dim*2, name='h1_conv')) tgtctx_h2 = lrelu(conv2d(tgtctx_h1, self.df_dim*4, name='h2_conv')) tgtctx_h3 = lrelu(conv2d(tgtctx_h2, self.df_dim*8, name='h3_conv')) tgtctx_h4 = lrelu(linear(tf.reshape(tgtctx_h3, [self.batch_size, -1]), featsize, 'h4_lin')) tgtctx_z = linear(tgtctx_h4, featsize, 'hz_lin') with tf.variable_scope("conv") as scope: srcimg_h0 = lrelu(conv2d(srcimg, self.df_dim, name='h0_conv')) srcimg_h1 = lrelu(conv2d(srcimg_h0, self.df_dim*2, name='h1_conv')) srcimg_h2 = lrelu(conv2d(srcimg_h1, self.df_dim*4, name='h2_conv')) srcimg_h3 = lrelu(conv2d(srcimg_h2, self.df_dim*8, name='h3_conv')) print(srcimg_h3.get_shape()) srcimg_h4 = lrelu(linear(tf.reshape(srcimg_h3, [self.batch_size, -1]), featsize, 'h4_lin')) srcimg_z = lrelu(linear(srcimg_h4, featsize, 'hz_lin')) scope.reuse_variables() tgtimg_h0 = lrelu(conv2d(tgtimg, self.df_dim, name='h0_conv')) tgtimg_h1 = lrelu(conv2d(tgtimg_h0, self.df_dim*2, name='h1_conv')) tgtimg_h2 = lrelu(conv2d(tgtimg_h1, self.df_dim*4, name='h2_conv')) tgtimg_h3 = lrelu(conv2d(tgtimg_h2, self.df_dim*8, name='h3_conv')) tgtimg_h4 = lrelu(linear(tf.reshape(tgtimg_h3, [self.batch_size, -1]), featsize, 'h4_lin')) tgtimg_z = lrelu(linear(tgtimg_h4, featsize, 'hz_lin')) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.concat([srcimg_z, tgtctx_z], 1), featsize, 'trans_h0')) trans_z = linear(trans_h0, featsize, 'trans_z') self.translated_z = trans_z with tf.variable_scope("deconv") as scope: s_h, s_w = self.output_height, self.output_width s_h2, s_h4, s_h8, s_h16 = \ int(s_h/2), int(s_h/4), int(s_h/8), int(s_h/16) s_w2, s_w4, s_w8, s_w16 = \ int(s_w/2), int(s_w/4), int(s_w/8), int(s_w/16) output_z_ = lrelu(linear(trans_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin')) output_h0 = tf.reshape(output_z_, [-1, s_h16, s_w16, self.gf_dim * 8]) output_h1 = lrelu(deconv2d(tf.concat([output_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) output_h2 = lrelu(deconv2d(tf.concat([output_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) output_h3 = lrelu(deconv2d(tf.concat([output_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) output_h4 = deconv2d(tf.concat([output_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') scope.reuse_variables() truthoutput_z_ = lrelu(linear(tgtimg_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin')) truthoutput_h0 = tf.reshape(truthoutput_z_, [-1, s_h16, s_w16, self.gf_dim * 8]) truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 mean, var = tf.nn.moments(tgtimg_z, axes=[0]) print(var.get_shape()) # self.simloss /= tf.reduce_mean(var) print(tgtimg_z.get_shape()) self.out = output_h4# + contextimg#tf.nn.tanh(h4) self.out2 = truthoutput_h4 self.recon1 = tf.nn.l2_loss(tgtimg - self.out) self.recon2 = tf.nn.l2_loss(tgtimg - self.out2) self.loss = self.recon1 + self.recon2 + self.simloss if ablation_type == "None": self.loss = self.recon1 + self.recon2 + self.simloss elif ablation_type == "L2": self.loss = self.recon1 + self.recon2 elif ablation_type == "L2L3": self.loss = self.recon1 elif ablation_type == "L1": self.loss = self.recon2 + self.simloss class ContextAEReach: def __init__(self, gf_dim=64, df_dim=64, gfc_dim=1024, dfc_dim=1024, c_dim=3): self.gf_dim = gf_dim self.df_dim = df_dim self.c_dim = c_dim self.gfc_dim = gfc_dim self.dfc_dim = dfc_dim def build(self, image, ablation_type): imgshape = image.get_shape().as_list() print(imgshape) self.output_height, self.output_width = imgshape[-3:-1] self.batch_size = imgshape[1] featsize = 1024 srcimg = image[0] tgtimg = image[2] tgtctx = image[1] with tf.variable_scope("conv_context") as scope: tgtctx_h0 = lrelu(conv2d(tgtctx, self.df_dim, name='h0_conv')) tgtctx_h1 = lrelu(conv2d(tgtctx_h0, self.df_dim*2, name='h1_conv')) tgtctx_h2 = lrelu(conv2d(tgtctx_h1, self.df_dim*4, name='h2_conv')) tgtctx_h3 = lrelu(conv2d(tgtctx_h2, self.df_dim*8, name='h3_conv')) tgtctx_h4 = lrelu(linear(tf.reshape(tgtctx_h3, [self.batch_size, -1]), featsize, 'h4_lin')) tgtctx_z = linear(tgtctx_h4, featsize, 'hz_lin') with tf.variable_scope("conv") as scope: srcimg_h0 = lrelu(conv2d(srcimg, self.df_dim, name='h0_conv')) srcimg_h1 = lrelu(conv2d(srcimg_h0, self.df_dim*2, name='h1_conv')) srcimg_h2 = lrelu(conv2d(srcimg_h1, self.df_dim*4, name='h2_conv')) srcimg_h3 = lrelu(conv2d(srcimg_h2, self.df_dim*8, name='h3_conv')) print(srcimg_h3.get_shape()) srcimg_h4 = lrelu(linear(tf.reshape(srcimg_h3, [self.batch_size, -1]), featsize, 'h4_lin')) srcimg_z = lrelu(linear(srcimg_h4, featsize, 'hz_lin')) scope.reuse_variables() tgtimg_h0 = lrelu(conv2d(tgtimg, self.df_dim, name='h0_conv')) tgtimg_h1 = lrelu(conv2d(tgtimg_h0, self.df_dim*2, name='h1_conv')) tgtimg_h2 = lrelu(conv2d(tgtimg_h1, self.df_dim*4, name='h2_conv')) tgtimg_h3 = lrelu(conv2d(tgtimg_h2, self.df_dim*8, name='h3_conv')) tgtimg_h4 = lrelu(linear(tf.reshape(tgtimg_h3, [self.batch_size, -1]), featsize, 'h4_lin')) tgtimg_z = lrelu(linear(tgtimg_h4, featsize, 'hz_lin')) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.concat([srcimg_z, tgtctx_z], 1), featsize, 'trans_h0')) trans_z = linear(trans_h0, featsize, 'trans_z') self.translated_z = trans_z with tf.variable_scope("deconv") as scope: s_h, s_w = self.output_height, self.output_width s_h2, s_h4, s_h8, s_h16 = \ int(s_h/2), int(s_h/4), int(s_h/8), int(s_h/16) s_w2, s_w4, s_w8, s_w16 = \ int(s_w/2), int(s_w/4), int(s_w/8), int(s_w/16) output_z_ = lrelu(linear(trans_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin')) output_h0 = tf.reshape(output_z_, [-1, s_h16, s_w16, self.gf_dim * 8]) output_h1 = lrelu(deconv2d(tf.concat([output_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) output_h2 = lrelu(deconv2d(tf.concat([output_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) output_h3 = lrelu(deconv2d(tf.concat([output_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) output_h4 = deconv2d(tf.concat([output_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') scope.reuse_variables() truthoutput_z_ = lrelu(linear(tgtimg_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin')) truthoutput_h0 = tf.reshape(truthoutput_z_, [-1, s_h16, s_w16, self.gf_dim * 8]) truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 mean, var = tf.nn.moments(tgtimg_z, axes=[0]) print(var.get_shape()) # self.simloss /= tf.reduce_mean(var) print(tgtimg_z.get_shape()) self.out = output_h4# + contextimg#tf.nn.tanh(h4) self.out2 = truthoutput_h4 self.recon1 = tf.nn.l2_loss(tgtimg - self.out) self.recon2 = tf.nn.l2_loss(tgtimg - self.out2) # self.loss = self.recon1 + self.recon2 + self.simloss if ablation_type == "None": self.loss = self.recon1 + self.recon2 + self.simloss elif ablation_type == "L2": self.loss = self.recon1 + self.recon2 elif ablation_type == "L2L3": self.loss = self.recon1 elif ablation_type == "L1": self.loss = self.recon2 + self.simloss class ContextAESweep: def __init__(self, gf_dim=64, df_dim=64, gfc_dim=1024, dfc_dim=1024, c_dim=3): self.gf_dim = gf_dim self.df_dim = df_dim self.c_dim = c_dim self.gfc_dim = gfc_dim self.dfc_dim = dfc_dim def build(self, image, ablation_type): imgshape = image.get_shape().as_list() print(imgshape) self.output_height, self.output_width = imgshape[-3:-1] self.batch_size = imgshape[1] featsize = 100 srcimg = image[0] tgtimg = image[2] tgtctx = image[1] nf0 = 32 nf1 = 16 nf2 = 16 nf3 = 8 ns0 = 1 ns1 = 2 ns2 = 1 ns3 = 2 # with tf.variable_scope("conv_context") as scope: def encode(img): img_h0 = lrelu(conv2d(img, nf0, d_h=ns0, d_w=ns0, name='h0_conv')) img_h1 = lrelu(conv2d(img_h0, nf1, d_h=ns1, d_w=ns1, name='h1_conv')) img_h2 = lrelu(conv2d(img_h1, nf2, d_h=ns2, d_w=ns2, name='h2_conv')) img_h3 = lrelu(conv2d(img_h2, nf3, d_h=ns3, d_w=ns3, name='h3_conv')) print(img_h3.get_shape()) img_h4 = lrelu(linear(tf.nn.dropout(tf.reshape(img_h3, [self.batch_size, -1]), keep_prob), featsize, 'h4_lin')) img_z = lrelu(linear(tf.nn.dropout(img_h4, keep_prob), featsize, 'hz_lin')) return img_h0, img_h1, img_h2, img_h3, img_h4, img_z with tf.variable_scope("conv") as scope: srcimg_h0, srcimg_h1, srcimg_h2, srcimg_h3, srcimg_h4, srcimg_z = encode(srcimg) scope.reuse_variables() tgtimg_h0, tgtimg_h1, tgtimg_h2, tgtimg_h3, tgtimg_h4, tgtimg_z = encode(tgtimg) tgtctx_h0, tgtctx_h1, tgtctx_h2, tgtctx_h3, tgtctx_h4, tgtctx_z = encode(tgtctx) with tf.variable_scope("translate") as scope: trans_h0 = lrelu(linear(tf.nn.dropout(tf.concat([srcimg_z, tgtctx_z], 1), keep_prob), featsize, 'trans_h0')) trans_z = linear(tf.nn.dropout(trans_h0, keep_prob), featsize, 'trans_z') self.translated_z = trans_z s_h, s_w = self.output_height, self.output_width s_h0, s_h1, s_h2, s_h3 = \ int(s_h/ns0), int(s_h/ns0/ns1), int(s_h/ns0/ns1/ns2), int(s_h/ns0/ns1/ns2/ns3) s_w0, s_w1, s_w2, s_w3 = \ int(s_w/ns0), int(s_w/ns0/ns1), int(s_w/ns0/ns1/ns2), int(s_w/ns0/ns1/ns2/ns3) def decode(z, skip_h3, skip_h2, skip_h1, skip_h0): z_ = lrelu(linear(tf.nn.dropout(z, keep_prob), nf3*s_h3*s_w3, 'd_h0_lin')) h0 = tf.nn.dropout(tf.reshape(z_, [-1, s_h3, s_w3, nf3]), keep_prob) import IPython IPython.embed() h1 = lrelu(deconv2d(tf.concat([h0, skip_h3], 3), [self.batch_size, s_h2, s_w2, nf2], name='d_h1', d_h=ns3, d_w=ns3)) h2 = lrelu(deconv2d(tf.concat([h1, skip_h2], 3), [self.batch_size, s_h1, s_w1, nf1], name='d_h2', d_h=ns2, d_w=ns2)) h3 = lrelu(deconv2d(tf.concat([h2, skip_h1], 3), [self.batch_size, s_h0, s_w0, nf0], name='d_h3', d_h=ns1, d_w=ns1)) print(h3.get_shape()) h4 = deconv2d(tf.concat([h3, skip_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4', d_h=ns0, d_w=ns0) return h4 with tf.variable_scope("deconv") as scope: output_h4 = decode(trans_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) scope.reuse_variables() truthoutput_h4 = decode(tgtimg_z, tgtctx_h3, tgtctx_h2, tgtctx_h1, tgtctx_h0) self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 print(tgtimg_z.get_shape()) self.out = output_h4 self.out2 = truthoutput_h4 print(self.out.get_shape()) self.recon1 = tf.nn.l2_loss(tgtimg - self.out) self.recon2 = tf.nn.l2_loss(tgtimg - self.out2) self.loss = self.recon1 + self.recon2 + self.simloss if ablation_type == "None": self.loss = self.recon1 + self.recon2 + self.simloss elif ablation_type == "L2": self.loss = self.recon1 + self.recon2 elif ablation_type == "L2L3": self.loss = self.recon1 elif ablation_type == "L1": self.loss = self.recon2 + self.simloss if __name__ == "__main__": #TODO: add in an argparse parser = argparse.ArgumentParser(description='Run ablations on models') parser.add_argument('experiment_type', type=str, help='type of ablation') parser.add_argument('ablation_type', type=str, help='type of ablation') parser.add_argument('data_location', type=str, help='data_location') args = parser.parse_args() vdata = np.load(args.data_location) tf.reset_default_graph() idim = (36, 64) keep_prob = tf.placeholder(tf.float32, name='keep_prob') tftrain = tf.placeholder(tf.bool, name='tftrain') batch_size=100 if (args.experiment_type == "reach") or (args.experiment_type == "push"): idim = (48, 48) tfinput = tf.placeholder(tf.float32, (3, batch_size) + idim + (3, ), name='x') if args.experiment_type == "reach": test = ContextAEReach() elif args.experiment_type == "push": test = ContextAEPush() elif args.experiment_type == "pushreal": test = ContextAEPushReal() elif args.experiment_type == "sweep": test = ContextAESweep() test.build(tfinput, args.ablation_type) config = tf.ConfigProto() config.gpu_options.allow_growth=True sess = tf.Session(config=config) learning_rate = tf.placeholder(tf.float32, shape=[]) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(test.loss) sess.run(tf.global_variables_initializer()) allloss = [] validloss = [] itr = 0 saver = tf.train.Saver() n = vdata.shape[1] nlen = vdata.shape[0] ntrain = int(0.8*n) nvalid = n - ntrain validdata = vdata[:, ntrain:] traindata = vdata[:, :ntrain] while True: choicesrc = np.random.choice(ntrain, batch_size) choicetgt = np.random.choice(ntrain, batch_size) srcdata = traindata[np.arange(0, batch_size) % nlen, choicesrc] tgtdata = traindata[np.arange(0, batch_size) % nlen, choicetgt] tgtctx = traindata[0, choicetgt] batch = [srcdata, tgtctx, tgtdata] _, loss, sim, r1, r2 = sess.run( [optimizer, test.loss, test.simloss, test.recon1, test.recon2], {tfinput: batch, learning_rate:1e-4, tftrain:False, keep_prob:0.5}) if itr % 4 == 0: print(loss, sim, r1, r2) allloss.append(loss) if itr % 40 == 0: choicesrc = np.random.choice(nvalid, batch_size) choicetgt = np.random.choice(nvalid, batch_size) srcdata = validdata[np.arange(0, batch_size) % nlen, choicesrc] tgtdata = validdata[np.arange(0, batch_size) % nlen, choicetgt] tgtctx = validdata[0, choicetgt] batch = [srcdata, tgtctx, tgtdata] loss, sim, r1, r2 = sess.run([test.loss, test.simloss, test.recon1, test.recon2], {tfinput: batch, tftrain:False, keep_prob:1.0}) print(loss, sim, r1, r2,'E') validloss.append(loss) saver.save(sess, 'ablation_' + str(args.experiment_type) + '_' + str(args.ablation_type) + "_" + str(itr)) if itr == 30000 or (itr>30000 and itr%10000 == 0): import IPython IPython.embed() itr += 1
[ "tensorflow.concat", "tensorflow.nn.conv2d_transpose", "tensorflow.nn.l2_loss", "tensorflow.train.AdamOptimizer", "tensorflow.nn.conv2d", "numpy.arange", "tensorflow.nn.moments", "tensorflow.nn.deconv2d", "tensorflow.truncated_normal_initializer", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.Session", "tensorflow.train.Saver", "numpy.load", "tensorflow.random_normal_initializer", "tensorflow.nn.dropout", "tensorflow.matmul", "numpy.random.choice", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.contrib.layers.batch_norm", "numpy.array", "tensorflow.nn.bias_add", "tensorflow.reduce_mean", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.constant_initializer", "tensorflow.variable_scope" ]
ablations_code/ablations.py
[(20, 'tensorflow.maximum', 'tf.maximum', (['x', '(leak * x)'], {}), True, 'import tensorflow as tf\n'), (488, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run ablations on models"""'}), False, 'import argparse\n'), (497, 'numpy.load', 'np.load', (['args.data_location'], {}), True, 'import numpy as np\n'), (499, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (501, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""keep_prob"""'}), True, 'import tensorflow as tf\n'), (502, 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {'name': '"""tftrain"""'}), True, 'import tensorflow as tf\n'), (506, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '((3, batch_size) + idim + (3,))'], {'name': '"""x"""'}), True, 'import tensorflow as tf\n'), (519, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), True, 'import tensorflow as tf\n'), (521, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (522, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[]'}), True, 'import tensorflow as tf\n'), (528, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['input_', 'w'], {'strides': '[1, d_h, d_w, 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (44, 'tensorflow.contrib.layers.batch_norm', 'tf.contrib.layers.batch_norm', (['x'], {'decay': 'self.momentum', 'updates_collections': 'None', 'epsilon': 'self.epsilon', 'scale': '(True)', 'is_training': 'tftrain', 'scope': 'self.name'}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.variable_scope', 'tf.variable_scope', (["(scope or 'Linear')"], {}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out)'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out2)'], {}), True, 'import tensorflow as tf\n'), (269, 'tensorflow.nn.moments', 'tf.nn.moments', (['tgtimg_z'], {'axes': '[0]'}), True, 'import tensorflow as tf\n'), (275, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out)'], {}), True, 'import tensorflow as tf\n'), (276, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out2)'], {}), True, 'import tensorflow as tf\n'), (372, 'tensorflow.nn.moments', 'tf.nn.moments', (['tgtimg_z'], {'axes': '[0]'}), True, 'import tensorflow as tf\n'), (378, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out)'], {}), True, 'import tensorflow as tf\n'), (379, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out2)'], {}), True, 'import tensorflow as tf\n'), (474, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out)'], {}), True, 'import tensorflow as tf\n'), (475, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['(tgtimg - self.out2)'], {}), True, 'import tensorflow as tf\n'), (524, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (537, 'numpy.random.choice', 'np.random.choice', (['ntrain', 'batch_size'], {}), True, 'import numpy as np\n'), (538, 'numpy.random.choice', 'np.random.choice', (['ntrain', 'batch_size'], {}), True, 'import numpy as np\n'), (15, 'numpy.array', 'np.array', (['cropped_image'], {}), True, 'import numpy as np\n'), (32, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['conv', 'biases'], {}), True, 'import tensorflow as tf\n'), (38, 'tensorflow.variable_scope', 'tf.variable_scope', (['name'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'stddev'}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.matmul', 'tf.matmul', (['input_', 'matrix'], {}), True, 'import tensorflow as tf\n'), (75, 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (['input_', 'w'], {'output_shape': 'output_shape', 'strides': '[1, d_h, d_w, 1]'}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['deconv', 'biases'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv"""'], {}), True, 'import tensorflow as tf\n'), (139, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""translate"""'], {}), True, 'import tensorflow as tf\n'), (163, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""deconv"""'], {}), True, 'import tensorflow as tf\n'), (168, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((trans_z - tgtimg_z) ** 2)'], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_context"""'], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv"""'], {}), True, 'import tensorflow as tf\n'), (232, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""translate"""'], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""deconv"""'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.reshape', 'tf.reshape', (['output_z_', '[-1, s_h16, s_w16, self.gf_dim * 8]'], {}), True, 'import tensorflow as tf\n'), (258, 'tensorflow.reshape', 'tf.reshape', (['truthoutput_z_', '[-1, s_h16, s_w16, self.gf_dim * 8]'], {}), True, 'import tensorflow as tf\n'), (268, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((trans_z - tgtimg_z) ** 2)'], {}), True, 'import tensorflow as tf\n'), (309, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_context"""'], {}), True, 'import tensorflow as tf\n'), (317, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv"""'], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""translate"""'], {}), True, 'import tensorflow as tf\n'), (340, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""deconv"""'], {}), True, 'import tensorflow as tf\n'), (348, 'tensorflow.reshape', 'tf.reshape', (['output_z_', '[-1, s_h16, s_w16, self.gf_dim * 8]'], {}), True, 'import tensorflow as tf\n'), (361, 'tensorflow.reshape', 'tf.reshape', (['truthoutput_z_', '[-1, s_h16, s_w16, self.gf_dim * 8]'], {}), True, 'import tensorflow as tf\n'), (371, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((trans_z - tgtimg_z) ** 2)'], {}), True, 'import tensorflow as tf\n'), (432, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv"""'], {}), True, 'import tensorflow as tf\n'), (438, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""translate"""'], {}), True, 'import tensorflow as tf\n'), (453, 'IPython.embed', 'IPython.embed', ([], {}), False, 'import IPython\n'), (464, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""deconv"""'], {}), True, 'import tensorflow as tf\n'), (469, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((trans_z - tgtimg_z) ** 2)'], {}), True, 'import tensorflow as tf\n'), (523, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), True, 'import tensorflow as tf\n'), (550, 'numpy.random.choice', 'np.random.choice', (['nvalid', 'batch_size'], {}), True, 'import numpy as np\n'), (551, 'numpy.random.choice', 'np.random.choice', (['nvalid', 'batch_size'], {}), True, 'import numpy as np\n'), (563, 'IPython.embed', 'IPython.embed', ([], {}), False, 'import IPython\n'), (27, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': 'stddev'}), True, 'import tensorflow as tf\n'), (31, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['bias_start'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.matmul', 'tf.matmul', (['input_', 'matrix'], {}), True, 'import tensorflow as tf\n'), (72, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'stddev'}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.nn.deconv2d', 'tf.nn.deconv2d', (['input_', 'w'], {'output_shape': 'output_shape', 'strides': '[1, d_h, d_w, 1]'}), True, 'import tensorflow as tf\n'), (83, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['trans_h0', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (152, 'tensorflow.reshape', 'tf.reshape', (['z_', '[-1, s_h3, s_w3, nf3]'], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.concat', 'tf.concat', (['[h3, skip_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (252, 'tensorflow.concat', 'tf.concat', (['[output_h3, tgtctx_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h3, tgtctx_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (355, 'tensorflow.concat', 'tf.concat', (['[output_h3, tgtctx_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (368, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h3, tgtctx_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (440, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['trans_h0', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (451, 'tensorflow.reshape', 'tf.reshape', (['z_', '[-1, s_h3, s_w3, nf3]'], {}), True, 'import tensorflow as tf\n'), (461, 'tensorflow.concat', 'tf.concat', (['[h3, skip_h0]', '(3)'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['img_h4', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['z', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.concat', 'tf.concat', (['[h0, skip_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.concat', 'tf.concat', (['[h1, skip_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.concat', 'tf.concat', (['[h2, skip_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.reshape', 'tf.reshape', (['tgtctx_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.reshape', 'tf.reshape', (['srcimg_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.reshape', 'tf.reshape', (['tgtimg_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.concat', 'tf.concat', (['[srcimg_z, tgtctx_z]', '(1)'], {}), True, 'import tensorflow as tf\n'), (246, 'tensorflow.concat', 'tf.concat', (['[output_h0, tgtctx_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.concat', 'tf.concat', (['[output_h1, tgtctx_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.concat', 'tf.concat', (['[output_h2, tgtctx_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (259, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h0, tgtctx_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h1, tgtctx_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h2, tgtctx_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (314, 'tensorflow.reshape', 'tf.reshape', (['tgtctx_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (323, 'tensorflow.reshape', 'tf.reshape', (['srcimg_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (332, 'tensorflow.reshape', 'tf.reshape', (['tgtimg_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (336, 'tensorflow.concat', 'tf.concat', (['[srcimg_z, tgtctx_z]', '(1)'], {}), True, 'import tensorflow as tf\n'), (349, 'tensorflow.concat', 'tf.concat', (['[output_h0, tgtctx_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (351, 'tensorflow.concat', 'tf.concat', (['[output_h1, tgtctx_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (353, 'tensorflow.concat', 'tf.concat', (['[output_h2, tgtctx_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (362, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h0, tgtctx_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (364, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h1, tgtctx_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (366, 'tensorflow.concat', 'tf.concat', (['[truthoutput_h2, tgtctx_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (429, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['img_h4', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (450, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['z', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (454, 'tensorflow.concat', 'tf.concat', (['[h0, skip_h3]', '(3)'], {}), True, 'import tensorflow as tf\n'), (456, 'tensorflow.concat', 'tf.concat', (['[h1, skip_h2]', '(3)'], {}), True, 'import tensorflow as tf\n'), (458, 'tensorflow.concat', 'tf.concat', (['[h2, skip_h1]', '(3)'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.reshape', 'tf.reshape', (['img_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.concat', 'tf.concat', (['[srcimg_z, tgtctx_z]', '(1)'], {}), True, 'import tensorflow as tf\n'), (428, 'tensorflow.reshape', 'tf.reshape', (['img_h3', '[self.batch_size, -1]'], {}), True, 'import tensorflow as tf\n'), (439, 'tensorflow.concat', 'tf.concat', (['[srcimg_z, tgtctx_z]', '(1)'], {}), True, 'import tensorflow as tf\n'), (539, 'numpy.arange', 'np.arange', (['(0)', 'batch_size'], {}), True, 'import numpy as np\n'), (540, 'numpy.arange', 'np.arange', (['(0)', 'batch_size'], {}), True, 'import numpy as np\n'), (552, 'numpy.arange', 'np.arange', (['(0)', 'batch_size'], {}), True, 'import numpy as np\n'), (553, 'numpy.arange', 'np.arange', (['(0)', 'batch_size'], {}), True, 'import numpy as np\n')]
jaesik817/svpg_tensorflow
ef8323af45bcb4f7c06588b4ee4ac8ec478b6027
import gym import itertools import matplotlib import numpy as np import sys import tensorflow as tf import collections import sklearn.pipeline import sklearn.preprocessing from sklearn.kernel_approximation import RBFSampler from svpg import SVPG ################### # parameters ################### ENV_NAME="MountainCarContinuous-v0"; #ENV_NAME="Pendulum-v0"; #ENV_NAME="Reacher-v1"; if(ENV_NAME=="Pendulum-v0"): NUM_EPISODES=2000; ENTROPY_BETA=0.01; POLICY_LR=0.0001; VALUE_LR=0.001; NUM_VARS=6; UPDATE_ITER=10; MAX_EPI_STEP=200; DISCOUNT_FACTOR=0.9; if(ENV_NAME=="MountainCarContinuous-v0"): NUM_EPISODES=100; ENTROPY_BETA=0.1; POLICY_LR=0.001; VALUE_LR=0.1; NUM_VARS=4; UPDATE_ITER=20; MAX_EPI_STEP=1000; DISCOUNT_FACTOR=0.95; # for SVPG n_particles=1; independent_flag_svpg=1; ################### # gym env env=np.zeros(n_particles,dtype=object); for i in range(n_particles): env[i] = gym.envs.make(ENV_NAME) num_state=env[0].observation_space.shape[0] num_action=env[0].action_space.shape[0] action_bound=[env[0].action_space.low, env[0].action_space.high] # MAX EPI STEP is setted in gym MAX_EPI_STEP=env[0].spec.timestep_limit; """ For MountainCarContinuous-v0 """ # Feature Preprocessing: Normalize to zero mean and unit variance # We use a few samples from the observation space to do this obsp_high=env[0].observation_space.high; obsp_low=env[0].observation_space.low; for i in range(len(obsp_high)): if(obsp_high[i]==float('Inf')): obsp_high[i]=1e+10; for i in range(len(obsp_low)): if(obsp_low[i]==-float('Inf')): obsp_low[i]=-1e+10; observation_examples = np.array([np.random.uniform(low=obsp_low, high=obsp_high,size=env[0].observation_space.low.shape) for x in range(10000)]) scaler = sklearn.preprocessing.StandardScaler() scaler.fit(observation_examples) # Used to convert a state to a featurizes represenation. # We use RBF kernels with different variances to cover different parts of the space featurizer = sklearn.pipeline.FeatureUnion([ ("rbf1", RBFSampler(gamma=5.0, n_components=100)), ("rbf2", RBFSampler(gamma=2.0, n_components=100)), ("rbf3", RBFSampler(gamma=1.0, n_components=100)), ("rbf4", RBFSampler(gamma=0.5, n_components=100)) ]) featurizer.fit(scaler.transform(observation_examples)) def featurize_state(state): scaled = scaler.transform([state]) featurized = featurizer.transform(scaled) return featurized[0] def build_policy_net_MountainCarContinuous(input_tf): mu = tf.layers.dense(input_tf, num_action, tf.nn.tanh, kernel_initializer=w_init, name='mu') # estimated action value sigma = tf.layers.dense(input_tf, num_action, tf.nn.softplus, kernel_initializer=w_init, name='sigma') # estimated variance return mu,sigma; class PolicyEstimator_MountainCarContinuous(): def __init__(self, entropy_beta=0.1, learning_rate=0.001, par_idx=0,scope="policy_estimator"): w_init = tf.random_normal_initializer(0.,.1); with tf.variable_scope(scope+"_"+str(par_idx)): # state, target and action self.state = tf.placeholder(tf.float32, [None,400], name="state") self.target = tf.placeholder(tf.float32,[None,1], name="target") self.a_his = tf.placeholder(tf.float32, [None, num_action], name="action_hist") # layers # wrap output self.mu = self.mu * action_bound[1]; self.sigma = self.sigma + 1e-5 self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma) self.action = tf.squeeze(self.normal_dist.sample(1),axis=0); self.action = tf.clip_by_value(self.action, action_bound[0], action_bound[1]) # Loss and train op self.loss = -self.normal_dist.log_prob(self.a_his) * self.target # Add cross entropy cost to encourage exploration self.loss -= entropy_beta * self.normal_dist.entropy() self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.grads_and_vars = self.optimizer.compute_gradients(self.loss) self.grads=[]; self.vars=[]; for i in range(len(self.grads_and_vars)): self.grads.append(self.grads_and_vars[i][0]); self.vars.append(self.grads_and_vars[i][1]); self.grads=self.grads[-1*NUM_VARS:]; self.vars=self.vars[-1*NUM_VARS:]; self.train_op = self.optimizer.apply_gradients( self.grads_and_vars, global_step=tf.contrib.framework.get_global_step()) def predict(self, state, sess=None): sess = sess or tf.get_default_session() state=featurize_state(state); return sess.run(self.action, { self.state: [state] })[0] def update(self, state, target, action, sess=None): sess = sess or tf.get_default_session() for st_idx in range(len(state)): state[st_idx]=featurize_state(state[st_idx]); feed_dict = { self.state: state, self.target: target, self.a_his: action } _, loss = sess.run([self.train_op, self.loss], feed_dict) return loss class ValueEstimator_MountainCarContinuous(): def __init__(self, learning_rate=0.1, par_idx=0,scope="value_estimator"): w_init = tf.random_normal_initializer(0.,.1); with tf.variable_scope(scope+"_"+str(par_idx)): # state and target self.state = tf.placeholder(tf.float32, [None,400], "state") self.target = tf.placeholder(tf.float32, [None,1], name="target") # layers self.value_estimate = tf.layers.dense(self.state, 1, kernel_initializer=w_init, name='v') # estimated value for state # loss and optimizer self.loss = tf.squared_difference(self.value_estimate, self.target) self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.train_op = self.optimizer.minimize( self.loss, global_step=tf.contrib.framework.get_global_step()) def predict(self, state, sess=None): sess = sess or tf.get_default_session() state=featurize_state(state); return sess.run(self.value_estimate, { self.state: [state] })[0][0] def update(self, state, target, sess=None): sess = sess or tf.get_default_session() for st_idx in range(len(state)): state[st_idx]=featurize_state(state[st_idx]); feed_dict = { self.state: state, self.target: target } _, loss = sess.run([self.train_op, self.loss], feed_dict) return loss """ For Pendulum-v0 """ class PolicyEstimator_Pendulum(): def __init__(self, entropy_beta=0.01, learning_rate=0.01, par_idx=0,scope="policy_estimator"): w_init = tf.random_normal_initializer(0.,.1); with tf.variable_scope(scope+"_"+str(par_idx)): # state, target and action self.state = tf.placeholder(tf.float32, [None,num_state], name="state") self.target = tf.placeholder(tf.float32,[None,1], name="target") self.a_his = tf.placeholder(tf.float32, [None, num_action], name="action_hist") # layers l_a = tf.layers.dense(self.state, 200, tf.nn.relu6, kernel_initializer=w_init, name='la') self.mu = tf.layers.dense(l_a, num_action, tf.nn.tanh, kernel_initializer=w_init, name='mu') # estimated action value self.sigma = tf.layers.dense(l_a, num_action, tf.nn.softplus, kernel_initializer=w_init, name='sigma') # estimated variance # wrap output self.mu = self.mu * action_bound[1]; self.sigma = self.sigma + 1e-4 # get action from distribution self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma) self.action = tf.squeeze(self.normal_dist.sample(1),axis=0); self.action = tf.clip_by_value(self.action, action_bound[0], action_bound[1]) # Loss and train op self.loss = -self.normal_dist.log_prob(self.a_his) * self.target # Add cross entropy cost to encourage exploration self.loss -= entropy_beta * self.normal_dist.entropy() self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.grads_and_vars = self.optimizer.compute_gradients(self.loss) self.grads=[]; self.vars=[]; for i in range(len(self.grads_and_vars)): self.grads.append(self.grads_and_vars[i][0]); self.vars.append(self.grads_and_vars[i][1]); self.grads=self.grads[-1*NUM_VARS:]; self.vars=self.vars[-1*NUM_VARS:]; self.train_op = self.optimizer.apply_gradients( self.grads_and_vars, global_step=tf.contrib.framework.get_global_step()) def predict(self, state, sess=None): sess = sess or tf.get_default_session() return sess.run(self.action, { self.state: [state] })[0] def update(self, state, target, a_his, sess=None): sess = sess or tf.get_default_session() feed_dict = { self.state: state, self.target: target, self.a_his: a_his } _, loss = sess.run([self.train_op, self.loss], feed_dict) return loss class ValueEstimator_Pendulum(): def __init__(self, learning_rate=0.1, par_idx=0,scope="value_estimator"): w_init = tf.random_normal_initializer(0.,.1); with tf.variable_scope(scope+"_"+str(par_idx)): # state and target self.state = tf.placeholder(tf.float32, [None,num_state], "state") self.target = tf.placeholder(tf.float32, [None,1], name="target") # layers l_c = tf.layers.dense(self.state, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc') self.value_estimate = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # estimated value for state # loss and optimizer self.loss = tf.reduce_mean(tf.square(tf.subtract(self.value_estimate, self.target))) self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.train_op = self.optimizer.minimize( self.loss, global_step=tf.contrib.framework.get_global_step()) def predict(self, state, sess=None): sess = sess or tf.get_default_session() return sess.run(self.value_estimate, { self.state: [state] })[0][0] def update(self, state, target, sess=None): sess = sess or tf.get_default_session() feed_dict = { self.state: state, self.target: target } _, loss = sess.run([self.train_op, self.loss], feed_dict) return loss def advantage_actor_critic(env, estimator_policy, estimator_value, svpg, num_episodes,max_epi_step, discount_factor=1.0): # Keeps track of useful statistics stats = {}; stats["episode_lengths"]=np.zeros((n_particles,num_episodes)); stats["episode_rewards"]=np.zeros((n_particles,num_episodes)); Transition = collections.namedtuple("Transition", ["state", "action", "reward", "next_state", "done"]) # state list state=np.zeros(n_particles,dtype=object); action=np.zeros(n_particles,dtype=object); next_state=np.zeros(n_particles,dtype=object); episode=np.zeros(n_particles,dtype=object); reward=np.zeros(n_particles,dtype=object); done=np.zeros(n_particles,dtype=object); policy_grads=np.zeros(n_particles,dtype=object); # total step total_step=1; # trasition backup initialization for i in range(n_particles): episode[i]=[]; for i_episode in range(num_episodes): # Reset the environment for i in range(n_particles): state[i] = env[i].reset() # run for t in range(MAX_EPI_STEP): for i in range(n_particles): # Take a step action[i] = estimator_policy[i].predict(state[i]) next_state[i], reward[i], done[i], _ = env[i].step(action[i]) # Pendulum case maximum running is just done (there are no reward threshold) if(ENV_NAME=="Pendulum-v0"): done[i] = True if t == max_epi_step -1 else False # Keep track of the transition episode[i].append(Transition( state=state[i], action=action[i], reward=reward[i], next_state=next_state[i], done=done[i])) # Update statistics stats["episode_rewards"][i][i_episode] += reward[i] stats["episode_lengths"][i][i_episode] = t state[i] = next_state[i] # checking one of them is done Done=False; for i in range(n_particles): if done[i]: Done=True; if((total_step%UPDATE_ITER==0)or(Done)): feed_dict={}; # Buffer for each particle buffer_s=np.zeros(n_particles,dtype=object); buffer_a=np.zeros(n_particles,dtype=object); buffer_v=np.zeros(n_particles,dtype=object); buffer_td_target=np.zeros(n_particles,dtype=object); buffer_td_error=np.zeros(n_particles,dtype=object); for i in range(n_particles): buffer_s[i]=[]; buffer_a[i]=[]; buffer_v[i]=[]; buffer_td_target[i]=[]; buffer_td_error[i]=[]; for t in range(len(episode[i])): transition=episode[i][t]; buffer_s[i].append(transition.state); buffer_a[i].append(transition.action); # normalize reward for Pendulum case if(ENV_NAME=="Pendulum-v0"): buffer_v[i].append((transition.reward+8)/8) else: buffer_v[i].append(transition.reward) if done[i]: v_s_=0; else: v_s_=estimator_value[i].predict(episode[i][-1].next_state); buffer_v[i].reverse(); for r in buffer_v[i]: v_s_=r+discount_factor*v_s_ buffer_td_target[i].append(v_s_); buffer_td_target[i].reverse(); for t in range(len(buffer_s[i])): buffer_td_error[i].append(buffer_td_target[i][t]-estimator_value[i].predict(buffer_s[i][t])); estimator_value[i].update(buffer_s[i],np.reshape(buffer_td_target[i],[-1,1])); feed_dict.update({estimator_policy[i].state:buffer_s[i]}); feed_dict.update({estimator_policy[i].target:np.reshape(buffer_td_error[i],[-1,1])}); feed_dict.update({estimator_policy[i].a_his:np.reshape(buffer_a[i],[-1,num_action])}); svpg.run(feed_dict); # trasition backup re-set for i in range(n_particles): episode[i]=[]; total_step+=1; if Done: break # Print out which step we're on, useful for debugging. (average recent 10 episode scores) if(i_episode>=10): print("Episode {}/{} ({})".format(i_episode + 1, num_episodes, np.max(np.mean(stats["episode_rewards"][:,i_episode-10:i_episode - 1],axis=1)))) return stats tf.reset_default_graph() global_step = tf.Variable(0, name="global_step", trainable=False) policy_estimator = np.zeros(n_particles,dtype=object); value_estimator = np.zeros(n_particles,dtype=object); # call proper policy and value estimators for each envs for i in range(n_particles): if(ENV_NAME=="Pendulum-v0"): policy_estimator[i] = PolicyEstimator_Pendulum(entropy_beta=ENTROPY_BETA,learning_rate=POLICY_LR,par_idx=i) value_estimator[i] = ValueEstimator_Pendulum(learning_rate=VALUE_LR,par_idx=i) if(ENV_NAME=="MountainCarContinuous-v0"): policy_estimator[i] = PolicyEstimator_MountainCarContinuous(entropy_beta=ENTROPY_BETA,learning_rate=POLICY_LR,par_idx=i) value_estimator[i] = ValueEstimator_MountainCarContinuous(learning_rate=VALUE_LR,par_idx=i) svpg=SVPG(policy_estimator,independent_flag_svpg,learning_rate=POLICY_LR); with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Note, due to randomness in the policy the number of episodes you need varies # TODO: Sometimes the algorithm gets stuck, I'm not sure what exactly is happening there. stats = advantage_actor_critic(env, policy_estimator, value_estimator, svpg, NUM_EPISODES, MAX_EPI_STEP,discount_factor=DISCOUNT_FACTOR)
[ "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.Variable", "numpy.reshape", "tensorflow.layers.dense", "tensorflow.subtract", "tensorflow.reset_default_graph", "tensorflow.contrib.distributions.Normal", "tensorflow.Session", "tensorflow.random_normal_initializer", "numpy.zeros", "sklearn.kernel_approximation.RBFSampler", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.clip_by_value", "tensorflow.get_default_session", "tensorflow.contrib.framework.get_global_step", "numpy.random.uniform", "tensorflow.squared_difference" ]
svpg_cont_action/tmp.py
[(47, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (358, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (360, 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), True, 'import tensorflow as tf\n'), (361, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (362, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (373, 'svpg.SVPG', 'SVPG', (['policy_estimator', 'independent_flag_svpg'], {'learning_rate': 'POLICY_LR'}), False, 'from svpg import SVPG\n'), (49, 'gym.envs.make', 'gym.envs.make', (['ENV_NAME'], {}), False, 'import gym\n'), (90, 'tensorflow.layers.dense', 'tf.layers.dense', (['input_tf', 'num_action', 'tf.nn.tanh'], {'kernel_initializer': 'w_init', 'name': '"""mu"""'}), True, 'import tensorflow as tf\n'), (91, 'tensorflow.layers.dense', 'tf.layers.dense', (['input_tf', 'num_action', 'tf.nn.softplus'], {'kernel_initializer': 'w_init', 'name': '"""sigma"""'}), True, 'import tensorflow as tf\n'), (256, 'numpy.zeros', 'np.zeros', (['(n_particles, num_episodes)'], {}), True, 'import numpy as np\n'), (257, 'numpy.zeros', 'np.zeros', (['(n_particles, num_episodes)'], {}), True, 'import numpy as np\n'), (259, 'collections.namedtuple', 'collections.namedtuple', (['"""Transition"""', "['state', 'action', 'reward', 'next_state', 'done']"], {}), False, 'import collections\n'), (262, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (263, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (264, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (265, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (266, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (267, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (268, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (375, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (69, 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'obsp_low', 'high': 'obsp_high', 'size': 'env[0].observation_space.low.shape'}), True, 'import numpy as np\n'), (96, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), True, 'import tensorflow as tf\n'), (144, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0.0)', '(0.1)'], {}), True, 'import tensorflow as tf\n'), (376, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (77, 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(5.0)', 'n_components': '(100)'}), False, 'from sklearn.kernel_approximation import RBFSampler\n'), (78, 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(2.0)', 'n_components': '(100)'}), False, 'from sklearn.kernel_approximation import RBFSampler\n'), (79, 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(1.0)', 'n_components': '(100)'}), False, 'from sklearn.kernel_approximation import RBFSampler\n'), (80, 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(0.5)', 'n_components': '(100)'}), False, 'from sklearn.kernel_approximation import RBFSampler\n'), (100, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 400]'], {'name': '"""state"""'}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""target"""'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_action]'], {'name': '"""action_hist"""'}), True, 'import tensorflow as tf\n'), (109, 'tensorflow.contrib.distributions.Normal', 'tf.contrib.distributions.Normal', (['self.mu', 'self.sigma'], {}), True, 'import tensorflow as tf\n'), (111, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self.action', 'action_bound[0]', 'action_bound[1]'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 400]', '"""state"""'], {}), True, 'import tensorflow as tf\n'), (148, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""target"""'}), True, 'import tensorflow as tf\n'), (151, 'tensorflow.layers.dense', 'tf.layers.dense', (['self.state', '(1)'], {'kernel_initializer': 'w_init', 'name': '"""v"""'}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.squared_difference', 'tf.squared_difference', (['self.value_estimate', 'self.target'], {}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_state]'], {'name': '"""state"""'}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""target"""'}), True, 'import tensorflow as tf\n'), (183, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_action]'], {'name': '"""action_hist"""'}), True, 'import tensorflow as tf\n'), (186, 'tensorflow.layers.dense', 'tf.layers.dense', (['self.state', '(200)', 'tf.nn.relu6'], {'kernel_initializer': 'w_init', 'name': '"""la"""'}), True, 'import tensorflow as tf\n'), (187, 'tensorflow.layers.dense', 'tf.layers.dense', (['l_a', 'num_action', 'tf.nn.tanh'], {'kernel_initializer': 'w_init', 'name': '"""mu"""'}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.layers.dense', 'tf.layers.dense', (['l_a', 'num_action', 'tf.nn.softplus'], {'kernel_initializer': 'w_init', 'name': '"""sigma"""'}), True, 'import tensorflow as tf\n'), (195, 'tensorflow.contrib.distributions.Normal', 'tf.contrib.distributions.Normal', (['self.mu', 'self.sigma'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self.action', 'action_bound[0]', 'action_bound[1]'], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_state]', '"""state"""'], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, 1]'], {'name': '"""target"""'}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.layers.dense', 'tf.layers.dense', (['self.state', '(100)', 'tf.nn.relu6'], {'kernel_initializer': 'w_init', 'name': '"""lc"""'}), True, 'import tensorflow as tf\n'), (235, 'tensorflow.layers.dense', 'tf.layers.dense', (['l_c', '(1)'], {'kernel_initializer': 'w_init', 'name': '"""v"""'}), True, 'import tensorflow as tf\n'), (239, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (248, 'tensorflow.get_default_session', 'tf.get_default_session', ([], {}), True, 'import tensorflow as tf\n'), (309, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (310, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (311, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (312, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (313, 'numpy.zeros', 'np.zeros', (['n_particles'], {'dtype': 'object'}), True, 'import numpy as np\n'), (127, 'tensorflow.contrib.framework.get_global_step', 'tf.contrib.framework.get_global_step', ([], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.contrib.framework.get_global_step', 'tf.contrib.framework.get_global_step', ([], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.contrib.framework.get_global_step', 'tf.contrib.framework.get_global_step', ([], {}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.subtract', 'tf.subtract', (['self.value_estimate', 'self.target'], {}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.contrib.framework.get_global_step', 'tf.contrib.framework.get_global_step', ([], {}), True, 'import tensorflow as tf\n'), (340, 'numpy.reshape', 'np.reshape', (['buffer_td_target[i]', '[-1, 1]'], {}), True, 'import numpy as np\n'), (354, 'numpy.mean', 'np.mean', (["stats['episode_rewards'][:, i_episode - 10:i_episode - 1]"], {'axis': '(1)'}), True, 'import numpy as np\n'), (342, 'numpy.reshape', 'np.reshape', (['buffer_td_error[i]', '[-1, 1]'], {}), True, 'import numpy as np\n'), (343, 'numpy.reshape', 'np.reshape', (['buffer_a[i]', '[-1, num_action]'], {}), True, 'import numpy as np\n')]
TheSeriousProgrammer/Keras_QuickNet_SSD
30c3c7ac8a2c05cc60fb4635a3f954c45e46108a
from typing import List import itertools import collections import tensorflow as tf import numpy as np from utils.misc import * SSDBoxSizes = collections.namedtuple('SSDBoxSizes', ['min', 'max']) SSDSpec = collections.namedtuple('SSDSpec', ['feature_map_size', 'shrinkage', 'box_sizes', 'aspect_ratios']) def generate_ssd_priors(specs: List[SSDSpec], image_size, clamp=True): """Generate SSD Prior Boxes. It returns the center, height and width of the priors. The values are relative to the image size Args: specs: SSDSpecs about the shapes of sizes of prior boxes. i.e. specs = [ SSDSpec(38, 8, SSDBoxSizes(30, 60), [2]), SSDSpec(19, 16, SSDBoxSizes(60, 111), [2, 3]), SSDSpec(10, 32, SSDBoxSizes(111, 162), [2, 3]), SSDSpec(5, 64, SSDBoxSizes(162, 213), [2, 3]), SSDSpec(3, 100, SSDBoxSizes(213, 264), [2]), SSDSpec(1, 300, SSDBoxSizes(264, 315), [2]) ] image_size: image size. clamp: if true, clamp the values to make fall between [0.0, 1.0] Returns: priors (num_priors, 4): The prior boxes represented as [[center_x, center_y, w, h]]. All the values are relative to the image size. """ priors = [] for spec in specs: scale = image_size / spec.shrinkage for j, i in itertools.product(range(spec.feature_map_size), repeat=2): x_center = (i + 0.5) / scale y_center = (j + 0.5) / scale # small sized square box size = spec.box_sizes.min h = w = size / image_size priors.append([ x_center, y_center, w, h ]) # big sized square box size = np.sqrt(spec.box_sizes.max * spec.box_sizes.min) h = w = size / image_size priors.append([ x_center, y_center, w, h ]) # change h/w ratio of the small sized box size = spec.box_sizes.min h = w = size / image_size for ratio in spec.aspect_ratios: ratio = np.sqrt(ratio) priors.append([ x_center, y_center, w * ratio, h / ratio ]) priors.append([ x_center, y_center, w / ratio, h * ratio ]) priors = np.array(priors, dtype=np.float32) if clamp: np.clip(priors, 0.0, 1.0, out=priors) return tf.convert_to_tensor(priors) @tf.function def assign_priors(gt_boxes, gt_labels, corner_form_priors, iou_threshold=0.45): """Assign ground truth boxes and targets to priors. Args: gt_boxes (num_targets, 4): ground truth boxes. gt_labels (num_targets): labels of targets. priors (num_priors, 4): corner form priors Returns: boxes (num_priors, 4): real values for priors. labels (num_priors): labels for priors. """ # size: num_priors x num_targets ious = iou_of(tf.expand_dims(gt_boxes, axis=0), tf.expand_dims(corner_form_priors, axis=1)) # size: num_priors best_target_per_prior = tf.math.reduce_max(ious, axis=1) best_target_per_prior_index = tf.math.argmax(ious, axis=1) # size: num_targets best_prior_per_target = tf.math.reduce_max(ious, axis=0) best_prior_per_target_index = tf.math.argmax(ious, axis=0) targets = tf.range(tf.shape(best_prior_per_target_index)[0], dtype='int64') best_target_per_prior_index = tf.tensor_scatter_nd_update(best_target_per_prior_index, tf.expand_dims(best_prior_per_target_index, 1), targets) # 2.0 is used to make sure every target has a prior assigned best_target_per_prior = tf.tensor_scatter_nd_update(best_target_per_prior, tf.expand_dims(best_prior_per_target_index, 1), tf.ones_like(best_prior_per_target_index, dtype=tf.float32)*2.0) # size: num_priors labels = tf.gather(gt_labels, best_target_per_prior_index) labels = tf.where(tf.less(best_target_per_prior, iou_threshold), tf.constant(0, dtype='int64'), labels) # labels[best_target_per_prior < iou_threshold] = 0 # the backgournd id boxes = tf.gather(gt_boxes, best_target_per_prior_index) return boxes, labels class MatchPrior(object): def __init__(self, center_form_priors, center_variance, size_variance, iou_threshold): self.center_form_priors = center_form_priors self.corner_form_priors = center_form_to_corner_form(center_form_priors) self.center_variance = center_variance self.size_variance = size_variance self.iou_threshold = iou_threshold def __call__(self, gt_boxes, gt_labels): if type(gt_boxes) is np.ndarray: gt_boxes = tf.convert_to_tensor(gt_boxes) if type(gt_labels) is np.ndarray: gt_labels = tf.convert_to_tensor(gt_labels) boxes, labels = assign_priors(gt_boxes, gt_labels, self.corner_form_priors, self.iou_threshold) boxes = corner_form_to_center_form(boxes) locations = convert_boxes_to_locations(boxes, self.center_form_priors, self.center_variance, self.size_variance) return locations, labels
[ "tensorflow.convert_to_tensor", "tensorflow.math.argmax", "tensorflow.constant", "numpy.sqrt", "numpy.clip", "tensorflow.math.reduce_max", "tensorflow.less", "tensorflow.shape", "tensorflow.ones_like", "tensorflow.expand_dims", "tensorflow.gather", "numpy.array" ]
utils/priors.py
[(8, 'collections.namedtuple', 'collections.namedtuple', (['"""SSDBoxSizes"""', "['min', 'max']"], {}), False, 'import collections\n'), (10, 'collections.namedtuple', 'collections.namedtuple', (['"""SSDSpec"""', "['feature_map_size', 'shrinkage', 'box_sizes', 'aspect_ratios']"], {}), False, 'import collections\n'), (77, 'numpy.array', 'np.array', (['priors'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (80, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['priors'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.math.reduce_max', 'tf.math.reduce_max', (['ious'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.math.argmax', 'tf.math.argmax', (['ious'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (101, 'tensorflow.math.reduce_max', 'tf.math.reduce_max', (['ious'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.math.argmax', 'tf.math.argmax', (['ious'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.gather', 'tf.gather', (['gt_labels', 'best_target_per_prior_index'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.gather', 'tf.gather', (['gt_boxes', 'best_target_per_prior_index'], {}), True, 'import tensorflow as tf\n'), (79, 'numpy.clip', 'np.clip', (['priors', '(0.0)', '(1.0)'], {'out': 'priors'}), True, 'import numpy as np\n'), (95, 'tensorflow.expand_dims', 'tf.expand_dims', (['gt_boxes'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.expand_dims', 'tf.expand_dims', (['corner_form_priors'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.expand_dims', 'tf.expand_dims', (['best_prior_per_target_index', '(1)'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.expand_dims', 'tf.expand_dims', (['best_prior_per_target_index', '(1)'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.less', 'tf.less', (['best_target_per_prior', 'iou_threshold'], {}), True, 'import tensorflow as tf\n'), (112, 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': '"""int64"""'}), True, 'import tensorflow as tf\n'), (50, 'numpy.sqrt', 'np.sqrt', (['(spec.box_sizes.max * spec.box_sizes.min)'], {}), True, 'import numpy as np\n'), (104, 'tensorflow.shape', 'tf.shape', (['best_prior_per_target_index'], {}), True, 'import tensorflow as tf\n'), (108, 'tensorflow.ones_like', 'tf.ones_like', (['best_prior_per_target_index'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['gt_boxes'], {}), True, 'import tensorflow as tf\n'), (130, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['gt_labels'], {}), True, 'import tensorflow as tf\n'), (63, 'numpy.sqrt', 'np.sqrt', (['ratio'], {}), True, 'import numpy as np\n')]
lshengjian/rlstudy
263bf68c94867551002ff0b02441c67b02ebe8ef
import numpy as np import tensorflow as tf #from gym import Discrete from rlstudy.common.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch from rlstudy.common.distributions import make_pdtype #from rlstudy.common.input import observation_input from gym.spaces import Discrete, Box def nature_cnn(unscaled_images, **conv_kwargs): """ CNN from Nature paper. """ scaled_images = tf.cast(unscaled_images, tf.float32) / 255. activ = tf.nn.relu h = activ(conv(scaled_images, 'c1', nf=32, rf=8, stride=4, init_scale=np.sqrt(2), **conv_kwargs)) h2 = activ(conv(h, 'c2', nf=64, rf=4, stride=2, init_scale=np.sqrt(2), **conv_kwargs)) h3 = activ(conv(h2, 'c3', nf=64, rf=3, stride=1, init_scale=np.sqrt(2), **conv_kwargs)) h3 = conv_to_fc(h3) return activ(fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2))) class CnnPolicy(object): def __init__(self, sess, ob_space, ac_space, nbatch, nsteps, reuse=False, **conv_kwargs): #pylint: disable=W0613 self.pdtype = make_pdtype(ac_space) X, processed_x = observation_input(ob_space, nbatch) # X:0~255 processed_x:0~1.0 with tf.variable_scope("model", reuse=reuse): h = nature_cnn(processed_x, **conv_kwargs) vf = fc(h, 'v', 1)[:,0] self.pd, self.pi = self.pdtype.pdfromlatent(h, init_scale=0.01) a0 = self.pd.sample() neglogp0 = self.pd.neglogp(a0) self.initial_state = None def step(ob, *_args, **_kwargs): a, v, neglogp = sess.run([a0, vf, neglogp0], {X:ob}) return a, v, self.initial_state, neglogp def value(ob, *_args, **_kwargs): return sess.run(vf, {X:ob}) self.X = X self.vf = vf self.step = step self.value = value def observation_input(ob_space, batch_size=None, name='Ob'): ''' Build observation input with encoding depending on the observation space type Params: ob_space: observation space (should be one of gym.spaces) batch_size: batch size for input (default is None, so that resulting input placeholder can take tensors with any batch size) name: tensorflow variable name for input placeholder returns: tuple (input_placeholder, processed_input_tensor) ''' if isinstance(ob_space, Discrete): input_x = tf.placeholder(shape=(batch_size,), dtype=tf.int32, name=name) processed_x = tf.to_float(tf.one_hot(input_x, ob_space.n)) return input_x, processed_x elif isinstance(ob_space, Box): input_shape = (batch_size,) + ob_space.shape input_x = tf.placeholder(shape=input_shape, dtype=ob_space.dtype, name=name) processed_x = tf.to_float(input_x) return input_x, processed_x else: raise NotImplementedError
[ "numpy.sqrt", "tensorflow.cast", "tensorflow.placeholder", "tensorflow.one_hot", "tensorflow.to_float", "tensorflow.variable_scope" ]
rlstudy/a2c/policies.py
[(19, 'rlstudy.common.utils.conv_to_fc', 'conv_to_fc', (['h3'], {}), False, 'from rlstudy.common.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch\n'), (13, 'tensorflow.cast', 'tf.cast', (['unscaled_images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (24, 'rlstudy.common.distributions.make_pdtype', 'make_pdtype', (['ac_space'], {}), False, 'from rlstudy.common.distributions import make_pdtype\n'), (62, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': '(batch_size,)', 'dtype': 'tf.int32', 'name': 'name'}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.one_hot', 'tf.one_hot', (['input_x', 'ob_space.n'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.placeholder', 'tf.placeholder', ([], {'shape': 'input_shape', 'dtype': 'ob_space.dtype', 'name': 'name'}), True, 'import tensorflow as tf\n'), (69, 'tensorflow.to_float', 'tf.to_float', (['input_x'], {}), True, 'import tensorflow as tf\n'), (15, 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), True, 'import numpy as np\n'), (17, 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), True, 'import numpy as np\n'), (18, 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), True, 'import numpy as np\n'), (20, 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), True, 'import numpy as np\n'), (29, 'rlstudy.common.utils.fc', 'fc', (['h', '"""v"""', '(1)'], {}), False, 'from rlstudy.common.utils import conv, fc, conv_to_fc, batch_to_seq, seq_to_batch\n')]
derdav3/tf-sparql
6d3fe6e3b6824a4cd5468a243829b71f5b0952f2
# Copyright 2016 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. # ============================================================================== """Batch normalization module for nn. This contains the module BatchNorm, which performs batch normalization on its inputs. It has an optional post-normalization scale and offset, and it maintains moving averages of the statistics for use at test time. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import xrange import tensorflow as tf from tensorflow.contrib.layers.python.layers import utils from tensorflow.python.training import moving_averages from nn import base from nn import util class BatchNorm(base.AbstractModule): """Batch normalization module, including optional affine transformation. This module maintains exponential moving averages of the mean and variance, used for calculating more accurate shifted statistics at training time and optionally used to normalize at test time. In order to update the moving averages, the user must run the ops in the tf.GraphKeys.UPDATE_OPS TensorFlow collection. For example: bn = BatchNorm() train_net = bn(train_inputs, is_training=True) test_net = bn(test_inputs, is_training=False, test_local_stats=False) ... update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = tf.group(train_op) Then, whenever `train_op` is run so also are the moving average update ops. At training time, batch statistics (mean, variance) are not shared between separate connections. The moving averages are shared between separate connections. At both training and test time, the optional affine transformations are shared between separate connections. Local batch statistics are used by default at test time, but the moving averages can be used by specifying a flag when connecting. One often wants to use local batch statistics at test time to track the progress while the model is trained as it would ensure that moving average updates do not affect the training curves. Once the training is finished, it's often advantageous to use moving average statistics, since it would make evaluation agnostic to the batch size, and might even lead to small improvements over the local batch statistics. """ GAMMA = "gamma" BETA = "beta" POSSIBLE_INITIALIZER_KEYS = {GAMMA, BETA} def __init__(self, reduction_indices=None, offset=True, scale=False, decay_rate=0.999, eps=1e-3, initializers=None, use_legacy_moving_second_moment=False, name="batch_norm"): """Constructs a BatchNorm module. By default reduces over all input tensor dimensions apart from the final dimension. This has the effect of treating pixels in 1D/2D/3D images as additional elements of the minibatch. If this is not the desired behaviour, the user can specify the tensor indices to reduce over with `reduction_indices`. Args: reduction_indices: Optional indices of dimensions to reduce over. offset: Optional boolean to specify whether or not to apply a trained component-wise bias after the batch normalization and scaling. scale: Optional boolean to specify whether or not to apply a trained component-wise scale after the batch normalization. decay_rate: Decay rate of the exponential moving averages of the mean and variance. eps: Small number to avoid dividing by zero when diving by the standard deviation. initializers: Optional dict containing ops to initialize the weights of the affine transform (`gamma` and `beta`). use_legacy_moving_second_moment: Keep a moving second moment, rather than the moving variance. This is deprecated, but is kept for backwards compatability with old checkpoints. By default `False`. name: Name of the module. Raises: base.Error: If initializers contains any keys other than `gamma` or `beta`. ValueError: If `use_legacy_moving_second_moment` is not `True`. """ super(BatchNorm, self).__init__(name) self._reduction_indices = reduction_indices self._offset = offset self._scale = scale self._decay_rate = decay_rate self._eps = eps self._use_legacy_moving_second_moment = use_legacy_moving_second_moment self._initializers = util.check_initializers( initializers, self.POSSIBLE_INITIALIZER_KEYS) def _set_default_initializer(self, var_name): """Sets up a default initializer for a variable if one doesn't exist. For the offset (beta), a zeros initializer is used by default. For the scale (gamma), a ones initializer is used by default. Args: var_name: name of variable as a string. """ if var_name not in self._initializers: if var_name == self.GAMMA: self._initializers[self.GAMMA] = tf.ones_initializer() elif var_name == self.BETA: self._initializers[self.BETA] = tf.zeros_initializer() def _build_statistics_variance(self, input_batch, reduction_indices, use_batch_stats): """Builds the statistics part of the graph when using moving variance. Args: input_batch: Input batch Tensor. reduction_indices: Indices of `input_batch` to reduce over. use_batch_stats: Boolean to indicate if batch statistics should be calculated, otherwise moving averages are returned. Returns: Tuple of (mean, variance). """ # Set up our moving statistics. When connecting in parallel, this is shared. self._moving_mean = tf.get_variable( "moving_mean", shape=self._mean_shape, collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES], initializer=tf.zeros_initializer(), trainable=False) self._moving_variance = tf.get_variable( "moving_variance", shape=self._mean_shape, collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES], initializer=tf.ones_initializer(), trainable=False) def build_batch_stats(): """Builds the batch statistics calculation ops.""" # We use the moving mean as an estimate of the mean in order to perform # a more numerically stable calculation of the batch mean. # Copy for better stability. shift = tf.add(self._moving_mean, 0) counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics( input_batch, reduction_indices, keep_dims=True, shift=shift, name="batch_norm_ss") mean, variance = tf.nn.normalize_moments(counts, shifted_sum_x, shifted_sum_x2, shift, name="normalize_moments") return mean, variance def build_moving_stats(): return ( tf.identity(self._moving_mean), tf.identity(self._moving_variance), ) mean, variance = utils.smart_cond( use_batch_stats, build_batch_stats, build_moving_stats, ) return mean, variance def _build_statistics_second_moment(self, input_batch, reduction_indices, use_batch_stats): """Builds the statistics part of the graph when using moving second moment. Args: input_batch: Input batch Tensor. reduction_indices: Indices of `input_batch` to reduce over. use_batch_stats: Boolean to indicate if batch statistics should be calculated, otherwise moving averages are returned. Returns: Tuple of (mean, variance, second_moment). """ # Set up our moving statistics. When connecting in parallel, this is shared. self._moving_mean = tf.get_variable( "moving_mean", shape=self._mean_shape, collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES], initializer=tf.zeros_initializer(), trainable=False) self._moving_second_moment = tf.get_variable( "moving_second_moment", shape=self._mean_shape, collections=[tf.GraphKeys.MOVING_AVERAGE_VARIABLES, tf.GraphKeys.GLOBAL_VARIABLES], initializer=tf.ones_initializer(), trainable=False) self._moving_variance = tf.subtract(self._moving_second_moment, tf.square(self._moving_mean), name="moving_variance") def build_batch_stats(): """Builds the batch statistics calculation ops.""" # Copy for better stability. # We use the moving mean as an estimate of the mean in order to perform # a more numerically stable calculation of the batch mean. shift = tf.add(self._moving_mean, 0) counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics( input_batch, reduction_indices, keep_dims=True, shift=shift, name="batch_norm_ss") mean, variance = tf.nn.normalize_moments(counts, shifted_sum_x, shifted_sum_x2, shift, name="normalize_moments") second_moment = variance + tf.square(mean) return mean, variance, second_moment def build_moving_stats(): return ( tf.identity(self._moving_mean), tf.identity(self._moving_variance), tf.identity(self._moving_second_moment), ) mean, variance, second_moment = utils.smart_cond( use_batch_stats, build_batch_stats, build_moving_stats, ) return mean, variance, second_moment def _build_update_ops_variance(self, mean, variance, is_training): """Builds the moving average update ops when using moving variance. Args: mean: The mean value to update with. variance: The variance value to update with. is_training: Boolean Tensor to indicate if we're currently in training mode. """ def build_update_ops(): """Builds the exponential moving average update ops.""" update_mean_op = moving_averages.assign_moving_average( variable=self._moving_mean, value=mean, decay=self._decay_rate, name="update_moving_mean").op update_variance_op = moving_averages.assign_moving_average( variable=self._moving_variance, value=variance, decay=self._decay_rate, name="update_moving_variance").op return update_mean_op, update_variance_op def build_no_ops(): return (tf.no_op(), tf.no_op()) # Only make the ops if we know that `is_training=True`, or the value of # `is_training` is unknown. is_training_const = utils.constant_value(is_training) if is_training_const is None or is_training_const: update_mean_op, update_variance_op = utils.smart_cond( is_training, build_update_ops, build_no_ops, ) # Every new connection creates a new op which adds its contribution # to the running average when ran. tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_variance_op) def _build_update_ops_second_moment(self, mean, second_moment, is_training): """Builds the moving average update ops when using the moving second moment. Args: mean: The mean value to update with. second_moment: The second_moment value to update with. is_training: Boolean Tensor to indicate if we're currently in training mode. """ def build_update_ops(): """Builds the exponential moving average update ops.""" update_mean_op = moving_averages.assign_moving_average( variable=self._moving_mean, value=mean, decay=self._decay_rate, name="update_moving_mean").op update_second_moment_op = moving_averages.assign_moving_average( variable=self._moving_second_moment, value=second_moment, decay=self._decay_rate, name="update_moving_second_moment").op return update_mean_op, update_second_moment_op def build_no_ops(): return (tf.no_op(), tf.no_op()) # Only make the ops if we know that `is_training=True`, or the value of # `is_training` is unknown. is_training_const = utils.constant_value(is_training) if is_training_const is None or is_training_const: update_mean_op, update_second_moment_op = utils.smart_cond( is_training, build_update_ops, build_no_ops, ) # Every new connection creates a new op which adds its contribution # to the running average when ran. tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_mean_op) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_second_moment_op) def _build(self, input_batch, is_training=True, test_local_stats=True): """Connects the BatchNorm module into the graph. Args: input_batch: A Tensor of arbitrary dimension. By default, the final dimension is not reduced over when computing the minibatch statistics. is_training: A boolean to indicate if the module should be connected in training mode, meaning the moving averages are updated. By default `True`. Can be a Tensor. test_local_stats: A boolean to indicate if local batch statistics should be used when `is_training=False`. If not, moving averages are used. By default `True`. Can be a Tensor. Returns: A tensor with the same shape as `input_batch`. Raises: base.IncompatibleShapeError: If `reduction_indices` is not valid for the input shape or has negative entries. base.NotSupportedError: If `input_batch` has data type of `tf.float16`. """ input_shape = input_batch.get_shape() if self._reduction_indices is not None: if len(self._reduction_indices) > len(input_shape): raise base.IncompatibleShapeError( "Too many reduction indices specified.") if max(self._reduction_indices) >= len(input_shape): raise base.IncompatibleShapeError( "Reduction index too large for input shape.") if min(self._reduction_indices) < 0: raise base.IncompatibleShapeError( "Reduction indeces must be non-negative.") reduction_indices = self._reduction_indices else: # Reduce over all dimensions except the last. reduction_indices = range(len(input_shape))[:-1] if input_batch.dtype == tf.float16: raise base.NotSupportedError( "BatchNorm does not support `tf.float16`, insufficient " "precision for calculating sufficient statistics.") self._mean_shape = input_batch.get_shape().as_list() for index in reduction_indices: self._mean_shape[index] = 1 use_batch_stats = is_training | test_local_stats # Use the legacy moving second moment if the flag is set. if self._use_legacy_moving_second_moment: tf.logging.warning( "nn.BatchNorm `use_legacy_second_moment=True` is deprecated.") mean, variance, second_moment = self._build_statistics_second_moment( input_batch, reduction_indices, use_batch_stats) self._build_update_ops_second_moment(mean, second_moment, is_training) else: mean, variance = self._build_statistics_variance( input_batch, reduction_indices, use_batch_stats) self._build_update_ops_variance(mean, variance, is_training) # Set up optional scale and offset factors. if self._offset: self._set_default_initializer(self.BETA) self._beta = tf.get_variable( self.BETA, shape=self._mean_shape, initializer=self._initializers[self.BETA]) else: self._beta = None if self._scale: self._set_default_initializer(self.GAMMA) self._gamma = tf.get_variable( self.GAMMA, shape=self._mean_shape, initializer=self._initializers[self.GAMMA]) else: self._gamma = None out = tf.nn.batch_normalization( input_batch, mean, variance, self._beta, self._gamma, self._eps, name="batch_norm") return out @property def moving_mean(self): self._ensure_is_connected() return self._moving_mean @property def moving_second_moment(self): self._ensure_is_connected() return self._moving_second_moment @property def moving_variance(self): self._ensure_is_connected() return self._moving_variance @property def beta(self): self._ensure_is_connected() if self._beta is None: raise base.Error( "Batch normalization doesn't have an offset, so no beta") else: return self._beta @property def gamma(self): self._ensure_is_connected() if self._gamma is None: raise base.Error( "Batch normalization doesn't have a scale, so no gamma") else: return self._gamma
[ "tensorflow.contrib.layers.python.layers.utils.constant_value", "tensorflow.logging.warning", "tensorflow.nn.batch_normalization", "tensorflow.get_variable", "tensorflow.python.training.moving_averages.assign_moving_average", "tensorflow.zeros_initializer", "tensorflow.nn.normalize_moments", "tensorflow.identity", "tensorflow.nn.sufficient_statistics", "tensorflow.contrib.layers.python.layers.utils.smart_cond", "tensorflow.add", "tensorflow.no_op", "tensorflow.square", "tensorflow.ones_initializer", "tensorflow.add_to_collection" ]
ml_models/nn/batch_norm.py
[(119, 'nn.util.check_initializers', 'util.check_initializers', (['initializers', 'self.POSSIBLE_INITIALIZER_KEYS'], {}), False, 'from nn import util\n'), (195, 'tensorflow.contrib.layers.python.layers.utils.smart_cond', 'utils.smart_cond', (['use_batch_stats', 'build_batch_stats', 'build_moving_stats'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (267, 'tensorflow.contrib.layers.python.layers.utils.smart_cond', 'utils.smart_cond', (['use_batch_stats', 'build_batch_stats', 'build_moving_stats'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (307, 'tensorflow.contrib.layers.python.layers.utils.constant_value', 'utils.constant_value', (['is_training'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (352, 'tensorflow.contrib.layers.python.layers.utils.constant_value', 'utils.constant_value', (['is_training'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (455, 'tensorflow.nn.batch_normalization', 'tf.nn.batch_normalization', (['input_batch', 'mean', 'variance', 'self._beta', 'self._gamma', 'self._eps'], {'name': '"""batch_norm"""'}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.add', 'tf.add', (['self._moving_mean', '(0)'], {}), True, 'import tensorflow as tf\n'), (174, 'tensorflow.nn.sufficient_statistics', 'tf.nn.sufficient_statistics', (['input_batch', 'reduction_indices'], {'keep_dims': '(True)', 'shift': 'shift', 'name': '"""batch_norm_ss"""'}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.nn.normalize_moments', 'tf.nn.normalize_moments', (['counts', 'shifted_sum_x', 'shifted_sum_x2', 'shift'], {'name': '"""normalize_moments"""'}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.square', 'tf.square', (['self._moving_mean'], {}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.add', 'tf.add', (['self._moving_mean', '(0)'], {}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.nn.sufficient_statistics', 'tf.nn.sufficient_statistics', (['input_batch', 'reduction_indices'], {'keep_dims': '(True)', 'shift': 'shift', 'name': '"""batch_norm_ss"""'}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.nn.normalize_moments', 'tf.nn.normalize_moments', (['counts', 'shifted_sum_x', 'shifted_sum_x2', 'shift'], {'name': '"""normalize_moments"""'}), True, 'import tensorflow as tf\n'), (309, 'tensorflow.contrib.layers.python.layers.utils.smart_cond', 'utils.smart_cond', (['is_training', 'build_update_ops', 'build_no_ops'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (317, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_mean_op'], {}), True, 'import tensorflow as tf\n'), (318, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_variance_op'], {}), True, 'import tensorflow as tf\n'), (354, 'tensorflow.contrib.layers.python.layers.utils.smart_cond', 'utils.smart_cond', (['is_training', 'build_update_ops', 'build_no_ops'], {}), False, 'from tensorflow.contrib.layers.python.layers import utils\n'), (362, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_mean_op'], {}), True, 'import tensorflow as tf\n'), (363, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.UPDATE_OPS', 'update_second_moment_op'], {}), True, 'import tensorflow as tf\n'), (407, 'nn.base.NotSupportedError', 'base.NotSupportedError', (['"""BatchNorm does not support `tf.float16`, insufficient precision for calculating sufficient statistics."""'], {}), False, 'from nn import base\n'), (419, 'tensorflow.logging.warning', 'tf.logging.warning', (['"""nn.BatchNorm `use_legacy_second_moment=True` is deprecated."""'], {}), True, 'import tensorflow as tf\n'), (439, 'tensorflow.get_variable', 'tf.get_variable', (['self.BETA'], {'shape': 'self._mean_shape', 'initializer': 'self._initializers[self.BETA]'}), True, 'import tensorflow as tf\n'), (448, 'tensorflow.get_variable', 'tf.get_variable', (['self.GAMMA'], {'shape': 'self._mean_shape', 'initializer': 'self._initializers[self.GAMMA]'}), True, 'import tensorflow as tf\n'), (486, 'nn.base.Error', 'base.Error', (['"""Batch normalization doesn\'t have an offset, so no beta"""'], {}), False, 'from nn import base\n'), (496, 'nn.base.Error', 'base.Error', (['"""Batch normalization doesn\'t have a scale, so no gamma"""'], {}), False, 'from nn import base\n'), (133, 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.identity', 'tf.identity', (['self._moving_mean'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.identity', 'tf.identity', (['self._moving_variance'], {}), True, 'import tensorflow as tf\n'), (222, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.ones_initializer', 'tf.ones_initializer', ([], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.square', 'tf.square', (['mean'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.identity', 'tf.identity', (['self._moving_mean'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.identity', 'tf.identity', (['self._moving_variance'], {}), True, 'import tensorflow as tf\n'), (264, 'tensorflow.identity', 'tf.identity', (['self._moving_second_moment'], {}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', ([], {'variable': 'self._moving_mean', 'value': 'mean', 'decay': 'self._decay_rate', 'name': '"""update_moving_mean"""'}), False, 'from tensorflow.python.training import moving_averages\n'), (294, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', ([], {'variable': 'self._moving_variance', 'value': 'variance', 'decay': 'self._decay_rate', 'name': '"""update_moving_variance"""'}), False, 'from tensorflow.python.training import moving_averages\n'), (303, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (303, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', ([], {'variable': 'self._moving_mean', 'value': 'mean', 'decay': 'self._decay_rate', 'name': '"""update_moving_mean"""'}), False, 'from tensorflow.python.training import moving_averages\n'), (339, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', ([], {'variable': 'self._moving_second_moment', 'value': 'second_moment', 'decay': 'self._decay_rate', 'name': '"""update_moving_second_moment"""'}), False, 'from tensorflow.python.training import moving_averages\n'), (348, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (348, 'tensorflow.no_op', 'tf.no_op', ([], {}), True, 'import tensorflow as tf\n'), (390, 'nn.base.IncompatibleShapeError', 'base.IncompatibleShapeError', (['"""Too many reduction indices specified."""'], {}), False, 'from nn import base\n'), (394, 'nn.base.IncompatibleShapeError', 'base.IncompatibleShapeError', (['"""Reduction index too large for input shape."""'], {}), False, 'from nn import base\n'), (398, 'nn.base.IncompatibleShapeError', 'base.IncompatibleShapeError', (['"""Reduction indeces must be non-negative."""'], {}), False, 'from nn import base\n'), (135, 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), True, 'import tensorflow as tf\n')]
1212Prajwol-Pdl/SmartProcessAnalytics
b25b6e922e19cc61cfb9eb96395ad177af1daf71
# -*- coding: utf-8 -*- """ Created on Tue Jul 23 17:52:31 2019 @author: Weike (Vicky) Sun [email protected]/[email protected] (c) 2020 Weike Sun, all rights reserved """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 4 09:15:46 2018 @author: weiksun @comment: this file contains the RNN formulation for regression purpose w/ feedback connection """ """ Import package """ import numpy as np import tensorflow as tf """ Generate batch data """ def gen_batch(raw_x, raw_y,raw_yp, batch_size, num_steps, epoch_overlap): data_length = len(raw_x) dx = np.shape(raw_x)[1] dy = np.shape(raw_y)[1] dyp = np.shape(raw_yp)[1] batch_partition_length = data_length // batch_size data_x = np.zeros([batch_size, batch_partition_length,dx], dtype= np.float32) data_y = np.zeros([batch_size, batch_partition_length,dy], dtype= np.float32) data_yp = np.zeros([batch_size, batch_partition_length,dyp], dtype= np.float32) for i in range(batch_size): data_x[i] = raw_x[batch_partition_length * i : batch_partition_length * (i+1)] data_y[i] = raw_y[batch_partition_length * i : batch_partition_length * (i+1)] data_yp[i] = raw_yp[batch_partition_length * i : batch_partition_length * (i+1)] if epoch_overlap == None: epoch_size = batch_partition_length // num_steps for i in range(epoch_size): x = data_x[:, i * num_steps:(i + 1) * num_steps] y = data_y[:, i * num_steps:(i + 1) * num_steps] yp = data_yp[:, i * num_steps:(i + 1) * num_steps] yield (x, y, yp) else: epoch_size = (batch_partition_length - num_steps + 1)//(epoch_overlap+1) for i in range(epoch_size): x = data_x[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] y = data_y[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yp = data_yp[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yield (x, y, yp) """ Generate batch data for multiple series """ def gen_batch_multi(raw_x, raw_y, timeindex, batch_size, num_steps, epoch_overlap): cum = 0 num_series = len(timeindex) for s in range(num_series): num = np.shape(timeindex[s+1])[0] x = raw_x[cum:cum+num] y = raw_y[cum:cum+num] yp = np.insert(y,0,0,axis=0)[:-1] data_length = len(x) dx = np.shape(x)[1] dy = np.shape(y)[1] dyp = np.shape(yp)[1] batch_partition_length = data_length // batch_size data_x = np.zeros([batch_size, batch_partition_length,dx], dtype= np.float32) data_y = np.zeros([batch_size, batch_partition_length,dy], dtype= np.float32) data_yp = np.zeros([batch_size, batch_partition_length,dyp], dtype= np.float32) for i in range(batch_size): data_x[i] = x[batch_partition_length * i : batch_partition_length * (i+1)] data_y[i] = y[batch_partition_length * i : batch_partition_length * (i+1)] data_yp[i] = yp[batch_partition_length * i : batch_partition_length * (i+1)] if epoch_overlap == None: epoch_size = batch_partition_length // num_steps for i in range(epoch_size): x = data_x[:, i * num_steps:(i + 1) * num_steps] y = data_y[:, i * num_steps:(i + 1) * num_steps] yp = data_yp[:, i * num_steps:(i + 1) * num_steps] yield (x, y, yp,s) else: epoch_size = (batch_partition_length - num_steps + 1)//(epoch_overlap+1) for i in range(epoch_size): x = data_x[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] y = data_y[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yp = data_yp[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yield (x, y, yp,s) cum += num """ Generate batch data for kstep prediction """ def gen_batch_kstep(raw_x, raw_y,raw_yp, rnn_state, batch_size, num_steps, epoch_overlap): data_length = len(raw_x) dx = np.shape(raw_x)[1] dy = np.shape(raw_y)[1] dyp = np.shape(raw_yp)[1] ds = np.shape(rnn_state)[1] batch_partition_length = data_length // batch_size data_x = np.zeros([batch_size, batch_partition_length,dx], dtype= np.float32) data_y = np.zeros([batch_size, batch_partition_length,dy], dtype= np.float32) data_yp = np.zeros([batch_size, batch_partition_length,dyp], dtype= np.float32) data_s = np.zeros([batch_size, batch_partition_length,ds], dtype= np.float32) for i in range(batch_size): data_x[i] = raw_x[batch_partition_length * i : batch_partition_length * (i+1)] data_y[i] = raw_y[batch_partition_length * i : batch_partition_length * (i+1)] data_yp[i] = raw_yp[batch_partition_length * i : batch_partition_length * (i+1)] data_s[i] = rnn_state[batch_partition_length * i : batch_partition_length * (i+1)] if epoch_overlap == None: epoch_size = batch_partition_length // num_steps for i in range(epoch_size): x = data_x[:, i * num_steps:(i + 1) * num_steps] y = data_y[:, i * num_steps:(i + 1) * num_steps] yp = data_yp[:, i * num_steps:(i + 1) * num_steps] s = data_s[:, i * num_steps:(i + 1) * num_steps] yield (x, y, yp, s) else: epoch_size = (batch_partition_length - num_steps + 1)//(epoch_overlap+1) for i in range(epoch_size): x = data_x[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] y = data_y[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yp = data_yp[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] s = data_s[:, i*(epoch_overlap+1):i*(epoch_overlap+1)+num_steps] yield (x, y, yp, s) """ Generate batch data for kstep prediction """ def gen_batch_kstep_layer(raw_x, raw_y,raw_yp, rnn_state): data_length = len(raw_x) dx = np.shape(raw_x)[1] dy = np.shape(raw_y)[1] dyp = np.shape(raw_yp)[1] num_layers = len(rnn_state) batch_size = data_length batch_partition_length = 1 data_x = np.zeros([batch_size, batch_partition_length,dx], dtype= np.float32) data_y = np.zeros([batch_size, batch_partition_length,dy], dtype= np.float32) data_yp = np.zeros([batch_size, batch_partition_length,dyp], dtype= np.float32) final_data_s = () for i in range(batch_size): data_x[i] = raw_x[batch_partition_length * i : batch_partition_length * (i+1)] data_y[i] = raw_y[batch_partition_length * i : batch_partition_length * (i+1)] data_yp[i] = raw_yp[batch_partition_length * i : batch_partition_length * (i+1)] for l in range(num_layers): final_data_s += (rnn_state[l][:-1],) yield (data_x, data_y, data_yp, final_data_s) def gen_epochs(raw_data_x,raw_data_y,raw_data_yp, num_epochs, num_steps, batch_size,epoch_overlap): for i in range(int(num_epochs)): yield gen_batch(raw_data_x,raw_data_y, raw_data_yp, batch_size, num_steps, epoch_overlap) def gen_epochs_multi(raw_data_x,raw_data_y, timeindex, num_epochs, num_steps, batch_size,epoch_overlap): for i in range(int(num_epochs)): yield gen_batch_multi(raw_data_x,raw_data_y, timeindex, batch_size, num_steps, epoch_overlap) def reset_graph(): if 'sess' in globals() and sess: sess.close() tf.reset_default_graph() """ Define RNN graph """ def build_multilayer_rnn_graph_with_dynamic_rnn(cell_type, activation,state_size, num_steps, num_layers, input_size_x, input_size_y , learning_rate, lambda_l2_reg,random_seed=0): reset_graph() tf.set_random_seed(random_seed) #make reproducible results input_size_x += input_size_y """Define the graph inputs""" batch_size = tf.placeholder(tf.int32, [], name='batch_size') x = tf.placeholder(tf.float32, [None, num_steps, input_size_x], name='x') y = tf.placeholder(tf.float32, [None, num_steps, input_size_y], name='y') input_prob = tf.placeholder(tf.float32, name='input_prob') state_prob = tf.placeholder(tf.float32,name='state_prob') output_prob = tf.placeholder(tf.float32,name='output_prob') rnn_inputs = x """Define a single cell with variational dropout""" def get_a_cell(state_size,input_prob,state_prob,num_input): if cell_type == 'LSTM': if activation == 'linear': lstm=tf.nn.rnn_cell.LSTMCell(num_units=state_size, activation = tf.identity, state_is_tuple=True) cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': lstm=tf.nn.rnn_cell.LSTMCell(num_units=state_size, activation = tf.nn.relu, state_is_tuple=True) cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: #tanh by default lstm=tf.nn.rnn_cell.LSTMCell(num_units=state_size, state_is_tuple=True) cell_drop=tf.contrib.rnn.DropoutWrapper(lstm,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif cell_type == 'GRU': if activation == 'linear': gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.identity) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': gru=tf.nn.rnn_cell.GRUCell(state_size, activation = tf.nn.relu) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: gru=tf.nn.rnn_cell.GRUCell(state_size) cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: if activation == 'linear': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size,activation=tf.identity) cell_drop=tf.contrib.rnn.DropoutWrapper(cell_basic,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size, activation=tf.nn.relu) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob, state_keep_prob=state_prob) else: #tanh by default cell_basic = tf.contrib.rnn.BasicRNNCell(state_size) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob, state_keep_prob=state_prob) return cell_drop """Wrap the cell in multilayer""" cell=tf.nn.rnn_cell.MultiRNNCell([get_a_cell(state_size,input_prob,state_prob,input_size_x if layer==0 else state_size) for layer in range(num_layers)],state_is_tuple=True) cell=tf.nn.rnn_cell.DropoutWrapper(cell,variational_recurrent=True,dtype=tf.float32,input_size=input_size_x,output_keep_prob=output_prob) init_state = cell.zero_state(batch_size, dtype=tf.float32) """Build dynamic graph""" rnn_outputs, final_state = tf.nn.dynamic_rnn(cell=cell, inputs=rnn_inputs,initial_state=init_state) """Add prediction layer""" with tf.variable_scope('softmax'): W = tf.get_variable('W', [state_size, input_size_y]) b = tf.get_variable('b', [input_size_y], initializer=tf.constant_initializer(0.0)) rnn_outputs = tf.reshape(rnn_outputs, [-1, state_size]) predictions = tf.matmul(rnn_outputs, W) + b yy = tf.reshape(y, [-1, input_size_y]) #batch_size*num_steps when yo udefine a placeholder in Tensorflow, the shape of the input during the session should be the same as the shape of the plcae holder "Mean squared error loss" loss=tf.reduce_mean(tf.square(tf.reshape(predictions,[-1])-tf.reshape(yy,[-1]))) "Adding regularization" if lambda_l2_reg > 0 : cell_l2 = tf.reduce_sum([tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables() if not ("noreg" in tf_var.name or "Bias" in tf_var.name)]) Predict_l2 = tf.nn.l2_loss(W) #+ tf.nn.l2_loss(b) total_loss = tf.reduce_sum(loss + lambda_l2_reg* tf.reduce_sum(cell_l2+Predict_l2) ) else: total_loss = loss "Define the train_step" train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss) return dict(x=x, y=y, batch_size=batch_size, input_prob=input_prob, state_prob=state_prob, output_prob=output_prob, init_state=init_state, final_state=final_state, rnn_outputs = rnn_outputs, total_loss= total_loss, loss = loss, train_step=train_step, preds = predictions, saver= tf.train.Saver()) """ Train RNN graph """ def train_rnn(raw_data_x, raw_data_y, val_data_x, val_data_y,g, num_epochs, num_steps, batch_size, input_prob, output_prob, state_prob, epoch_before_val = 50, max_checks_without_progress=50,epoch_overlap=None, verbose=True, save=False): with tf.Session() as sess: "initialize the variables" sess.run(tf.global_variables_initializer()) raw_data_yp = np.insert(raw_data_y,0,0,axis=0)[:-1] val_data_yp = np.insert(val_data_y,0,0,axis=0)[:-1] "see the trainable variables" # print("The trainable variables are:") variable_names = [v.name for v in tf.trainable_variables()] variable_shapes = [v.get_shape() for v in tf.trainable_variables()] parameter_num = 0 for name, shape in zip(variable_names, variable_shapes): # print('{}\nShape: {}'.format(name, shape)) parameter_num += shape[0]*shape[1] if np.size(shape)>1 else shape[0] "train the graph" training_losses = [] val_losses = [] #set early_stopping cretirion checks_without_progress = 0 best_loss = np.infty for idx, epoch in enumerate(gen_epochs(raw_data_x,raw_data_y,raw_data_yp,num_epochs, num_steps, batch_size,epoch_overlap)): training_loss = 0 steps = 0 training_state = None for steps,(X, Y, YP) in enumerate(epoch): feed_dict = {g['x']: np.dstack((X,YP)), g['y']: Y, g['batch_size']:batch_size, g['input_prob']: input_prob ,g['output_prob']: output_prob,g['state_prob']:state_prob} # feed_dict = {g['x']: X, g['y']: Y, g['batch_size']:batch_size, g['input_prob']: 1 ,g['output_prob']: 1,g['state_prob']:1} #continue to feed in if in the same class if training_state is not None: feed_dict[g['init_state']] = training_state training_loss_, training_state, _ = sess.run([g['loss'], g['final_state'], g['train_step']], feed_dict=feed_dict) training_loss += training_loss_ if np.isnan(training_loss_): print('Explode!!!!!!!!!') return (None, None, None) if verbose and idx%100==0: print("Average training total loss for Epoch", idx, ":", training_loss/(steps+1)) training_losses.append(training_loss / (steps+1)) '''Test on validation set''' if idx > epoch_before_val: # print('Using validation for early stopping') '''see performance on validation set and do early stopping''' val_loss = 0 steps_val = 0 val_state = None for steps_val,(X_val, Y_val, YP_val) in enumerate(gen_batch(val_data_x, val_data_y, val_data_yp, batch_size, num_steps,epoch_overlap)): feed_dict_val = {g['x']: np.dstack((X_val,YP_val)), g['y']: Y_val, g['batch_size']:batch_size, g['input_prob']: 1 ,g['output_prob']: 1,g['state_prob']:1} #continue to feed in if in the same class if val_state is not None: feed_dict_val[g['init_state']] = val_state val_loss_,val_state = sess.run([g['loss'], g['final_state']],feed_dict=feed_dict_val) val_loss += val_loss_ val_loss = val_loss/(steps_val+1) val_losses.append(val_loss) if val_loss < best_loss: best_loss = val_loss checks_without_progress = 0 g['saver'].save(sess, save) else: checks_without_progress += 1 if checks_without_progress > max_checks_without_progress: print("Early stopping!") return (training_losses, val_losses, int(parameter_num)) if isinstance(save, str): g['saver'].save(sess, save) print("Max number train epoch reached") training_losses = np.array(training_losses) val_losses = np.array(val_losses) return (training_losses,val_losses, int(parameter_num)) """ Train RNN graph for multiple series """ def train_rnn_multi(raw_data_x, raw_data_y, val_data_x, val_data_y, timeindex_train, timeindex_val, g, num_epochs, num_steps, batch_size, input_prob, output_prob, state_prob, epoch_before_val = 50, max_checks_without_progress=50,epoch_overlap=None, verbose=True, save=False): with tf.Session() as sess: "initialize the variables" sess.run(tf.global_variables_initializer()) "see the trainable variables" # print("The trainable variables are:") variable_names = [v.name for v in tf.trainable_variables()] variable_shapes = [v.get_shape() for v in tf.trainable_variables()] parameter_num = 0 for name, shape in zip(variable_names, variable_shapes): # print('{}\nShape: {}'.format(name, shape)) parameter_num += shape[0]*shape[1] if np.size(shape)>1 else shape[0] "train the graph" training_losses = [] val_losses = [] #set early_stopping cretirion checks_without_progress = 0 best_loss = np.infty for idx, epoch in enumerate(gen_epochs_multi(raw_data_x,raw_data_y, timeindex_train, num_epochs, num_steps, batch_size,epoch_overlap)): training_loss = 0 steps = 0 s_threshold=0 training_state = None for steps,(X, Y, YP, s) in enumerate(epoch): feed_dict = {g['x']: np.dstack((X,YP)), g['y']: Y, g['batch_size']:batch_size, g['input_prob']: input_prob ,g['output_prob']: output_prob,g['state_prob']:state_prob} #start to feed 0 initial for a new set of class if s == s_threshold: s_threshold += 1 training_state = None #continue to feed in if in the same class if training_state is not None: feed_dict[g['init_state']] = training_state training_loss_, training_state, _ = sess.run([g['loss'], g['final_state'], g['train_step']], feed_dict=feed_dict) training_loss += training_loss_ # print(steps) # print(training_loss_) if verbose and idx%100==0: print("Average training total loss for Epoch", idx, ":", training_loss/(steps+1), steps, training_loss_) training_losses.append(training_loss / (steps+1)) '''Test on validation set''' if idx > epoch_before_val: # print('Using validation for early stopping') '''see performance on validation set and do early stopping''' val_loss = 0 steps_val = 0 s_val_threshold = 0 val_state = None for steps_val,(X_val, Y_val, YP_val, s_val) in enumerate(gen_batch_multi(val_data_x, val_data_y, timeindex_val, batch_size, num_steps, epoch_overlap)): feed_dict_val = {g['x']: np.dstack((X_val,YP_val)), g['y']: Y_val, g['batch_size']:batch_size, g['input_prob']: 1 ,g['output_prob']: 1,g['state_prob']:1} #start to feed 0 initial for a new set of class if s_val == s_val_threshold: s_val_threshold += 1 val_state = None #continue to feed in if in the same class if val_state is not None: feed_dict_val[g['init_state']] = val_state val_loss_,val_state = sess.run([g['loss'], g['final_state']],feed_dict=feed_dict_val) val_loss += val_loss_ print('val') print(val_loss) val_loss = val_loss/(steps_val+1) val_losses.append(val_loss) if val_loss < best_loss: best_loss = val_loss checks_without_progress = 0 g['saver'].save(sess, save) else: checks_without_progress += 1 if checks_without_progress > max_checks_without_progress: print("Early stopping!") return (training_losses, val_losses, int(parameter_num)) if isinstance(save, str): g['saver'].save(sess, save) print("Max number train epoch reached") training_losses = np.array(training_losses) val_losses = np.array(val_losses) return (training_losses,val_losses, int(parameter_num)) """ Test RNN graph 0 step """ def test_rnn(test_data_x,test_data_y, g, checkpoint, input_prob, output_prob, state_prob, num_test): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) test_data_yp = np.insert(test_data_y,0,0,axis=0)[:-1] "read the trained graph" g['saver'].restore(sess, checkpoint) "run the test points" #run the whole sequence, one class one total run for index,(X, Y, YP) in enumerate(gen_batch(test_data_x, test_data_y,test_data_yp, 1, num_test, None)): feed_dict={g['x']: np.dstack((X,YP)), g['y']:Y, g['batch_size']:1, g['input_prob']: input_prob,g['output_prob']:output_prob,g['state_prob']:state_prob} preds, rnn_outputs = sess.run([g['preds'], g['rnn_outputs']], feed_dict) loss = np.sum((preds[1:]-test_data_y[1:])**2,axis=0)/(test_data_y.shape[0]-1) return (preds,loss,rnn_outputs) """ Test RNN graph 0 step for multiplayer afterwards """ def test_rnn_layer(test_data_x,test_data_y, g, checkpoint, input_prob, output_prob, state_prob, num_test, num_layers): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) test_data_yp = np.insert(test_data_y,0,0,axis=0)[:-1] final = {} "read the trained graph" g['saver'].restore(sess, checkpoint) "run the test points" for index,(X, Y, YP) in enumerate(gen_batch(test_data_x, test_data_y,test_data_yp, 1, 1, None)): if index >0: feed_dict={g['x']: np.dstack((X,YP)), g['y']:Y,g['init_state']: rnn_outputs, g['batch_size']:1, g['input_prob']: input_prob,g['output_prob']:output_prob,g['state_prob']:state_prob} else: feed_dict={g['x']: np.dstack((X,YP)), g['y']:Y, g['batch_size']:1, g['input_prob']: input_prob,g['output_prob']:output_prob,g['state_prob']:state_prob} preds, rnn_outputs = sess.run([g['preds'],g['final_state']], feed_dict) if index>0: final_preds = np.vstack((final_preds,preds)) else: final_preds = preds for i in range(num_layers): if index >0: final[i] = np.vstack((final[i],rnn_outputs[i])) else: final[i] = rnn_outputs[i] final_inter_state=() for i in range(num_layers): final_inter_state += (final[i],) loss = np.sum((final_preds[1:]-test_data_y[1:])**2,axis=0)/(test_data_y.shape[0]-1) return (final_preds, loss, final_inter_state) """ Test RNN graph single layer """ def test_rnn_kstep(test_data_x,test_data_y, preds, rnn_outputs, g, checkpoint, input_prob, output_prob, state_prob, num_test, kstep = 3): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result= {} "read the trained graph" g['saver'].restore(sess, checkpoint) losses = [] for step_num in range(kstep): k=step_num+1 for index,(X, Y, YP, S) in enumerate(gen_batch_kstep(test_data_x[k:], test_data_y[k:], preds[:-1],rnn_outputs[:-1], num_test-k,1, None)): feed_dict={g['x']: np.dstack((X,YP)), g['y']:Y, g['init_state']: np.squeeze(S), g['batch_size']:num_test, g['input_prob']: input_prob,g['output_prob']:output_prob,g['state_prob']:state_prob} preds, rnn_outputs= sess.run([g['preds'], g['rnn_outputs']], feed_dict) loss = np.sum((preds[1:]-test_data_y[1+k:])**2,axis=0)/test_data_y[1+k:].shape[0] result[k] = preds losses.append(loss) return (result,losses) """ Test RNN graph multi layer """ def test_rnn_kstep_layer(test_data_x,test_data_y, preds, rnn_outputs, g, checkpoint, input_prob, output_prob, state_prob, num_test, kstep = 3): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result= {} "read the trained graph" g['saver'].restore(sess, checkpoint) losses = [] for step_num in range(kstep): k=step_num+1 for index,(X, Y, YP, S) in enumerate(gen_batch_kstep_layer(test_data_x[k:], test_data_y[k:], preds[:-1],rnn_outputs)): feed_dict={g['x']: np.dstack((X,YP)), g['y']:Y, g['init_state']: S, g['batch_size']:num_test, g['input_prob']: input_prob,g['output_prob']:output_prob,g['state_prob']:state_prob} preds, rnn_outputs= sess.run([g['preds'], g['final_state']], feed_dict) loss = np.sum((preds[1:]-test_data_y[k+1:])**2,axis=0)/test_data_y[k+1:].shape[0] result[k] = preds losses.append(loss) return (result,losses)
[ "tensorflow.nn.dynamic_rnn", "tensorflow.get_variable", "tensorflow.reduce_sum", "numpy.squeeze", "tensorflow.nn.l2_loss", "tensorflow.contrib.rnn.BasicRNNCell", "tensorflow.train.AdamOptimizer", "numpy.size", "tensorflow.reset_default_graph", "numpy.insert", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.trainable_variables", "tensorflow.nn.rnn_cell.GRUCell", "numpy.zeros", "tensorflow.matmul", "numpy.isnan", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.set_random_seed", "numpy.array", "numpy.sum", "tensorflow.nn.rnn_cell.DropoutWrapper", "tensorflow.contrib.rnn.DropoutWrapper", "tensorflow.nn.rnn_cell.LSTMCell", "tensorflow.reshape", "numpy.dstack", "tensorflow.constant_initializer", "numpy.shape", "tensorflow.variable_scope", "numpy.vstack" ]
Code-SPA/RNN_feedback.py
[(35, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dx]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (36, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dy]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (37, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dyp]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (127, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dx]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (128, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dy]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (129, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dyp]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (130, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, ds]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (177, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dx]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (178, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dy]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (179, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dyp]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (210, 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.set_random_seed', 'tf.set_random_seed', (['random_seed'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[]'], {'name': '"""batch_size"""'}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_steps, input_size_x]'], {'name': '"""x"""'}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, num_steps, input_size_y]'], {'name': '"""y"""'}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""input_prob"""'}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""state_prob"""'}), True, 'import tensorflow as tf\n'), (230, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""output_prob"""'}), True, 'import tensorflow as tf\n'), (280, 'tensorflow.nn.rnn_cell.DropoutWrapper', 'tf.nn.rnn_cell.DropoutWrapper', (['cell'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'input_size_x', 'output_keep_prob': 'output_prob'}), True, 'import tensorflow as tf\n'), (284, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', ([], {'cell': 'cell', 'inputs': 'rnn_inputs', 'initial_state': 'init_state'}), True, 'import tensorflow as tf\n'), (291, 'tensorflow.reshape', 'tf.reshape', (['rnn_outputs', '[-1, state_size]'], {}), True, 'import tensorflow as tf\n'), (293, 'tensorflow.reshape', 'tf.reshape', (['y', '[-1, input_size_y]'], {}), True, 'import tensorflow as tf\n'), (30, 'numpy.shape', 'np.shape', (['raw_x'], {}), True, 'import numpy as np\n'), (31, 'numpy.shape', 'np.shape', (['raw_y'], {}), True, 'import numpy as np\n'), (32, 'numpy.shape', 'np.shape', (['raw_yp'], {}), True, 'import numpy as np\n'), (84, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dx]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (85, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dy]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (86, 'numpy.zeros', 'np.zeros', (['[batch_size, batch_partition_length, dyp]'], {'dtype': 'np.float32'}), True, 'import numpy as np\n'), (120, 'numpy.shape', 'np.shape', (['raw_x'], {}), True, 'import numpy as np\n'), (121, 'numpy.shape', 'np.shape', (['raw_y'], {}), True, 'import numpy as np\n'), (122, 'numpy.shape', 'np.shape', (['raw_yp'], {}), True, 'import numpy as np\n'), (123, 'numpy.shape', 'np.shape', (['rnn_state'], {}), True, 'import numpy as np\n'), (169, 'numpy.shape', 'np.shape', (['raw_x'], {}), True, 'import numpy as np\n'), (170, 'numpy.shape', 'np.shape', (['raw_y'], {}), True, 'import numpy as np\n'), (171, 'numpy.shape', 'np.shape', (['raw_yp'], {}), True, 'import numpy as np\n'), (287, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""softmax"""'], {}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.get_variable', 'tf.get_variable', (['"""W"""', '[state_size, input_size_y]'], {}), True, 'import tensorflow as tf\n'), (292, 'tensorflow.matmul', 'tf.matmul', (['rnn_outputs', 'W'], {}), True, 'import tensorflow as tf\n'), (300, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['W'], {}), True, 'import tensorflow as tf\n'), (333, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (427, 'numpy.array', 'np.array', (['training_losses'], {}), True, 'import numpy as np\n'), (428, 'numpy.array', 'np.array', (['val_losses'], {}), True, 'import numpy as np\n'), (447, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (545, 'numpy.array', 'np.array', (['training_losses'], {}), True, 'import numpy as np\n'), (546, 'numpy.array', 'np.array', (['val_losses'], {}), True, 'import numpy as np\n'), (558, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (589, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (639, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (670, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (74, 'numpy.shape', 'np.shape', (['timeindex[s + 1]'], {}), True, 'import numpy as np\n'), (77, 'numpy.insert', 'np.insert', (['y', '(0)', '(0)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (79, 'numpy.shape', 'np.shape', (['x'], {}), True, 'import numpy as np\n'), (80, 'numpy.shape', 'np.shape', (['y'], {}), True, 'import numpy as np\n'), (81, 'numpy.shape', 'np.shape', (['yp'], {}), True, 'import numpy as np\n'), (306, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['learning_rate'], {}), True, 'import tensorflow as tf\n'), (323, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (335, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (337, 'numpy.insert', 'np.insert', (['raw_data_y', '(0)', '(0)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (338, 'numpy.insert', 'np.insert', (['val_data_y', '(0)', '(0)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (378, 'numpy.isnan', 'np.isnan', (['training_loss_'], {}), True, 'import numpy as np\n'), (449, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (559, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (561, 'numpy.insert', 'np.insert', (['test_data_y', '(0)', '(0)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (575, 'numpy.sum', 'np.sum', (['((preds[1:] - test_data_y[1:]) ** 2)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (590, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (592, 'numpy.insert', 'np.insert', (['test_data_y', '(0)', '(0)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (627, 'numpy.sum', 'np.sum', (['((final_preds[1:] - test_data_y[1:]) ** 2)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (640, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (671, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (237, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', ([], {'num_units': 'state_size', 'activation': 'tf.identity', 'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (238, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['lstm'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (289, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.reshape', 'tf.reshape', (['predictions', '[-1]'], {}), True, 'import tensorflow as tf\n'), (295, 'tensorflow.reshape', 'tf.reshape', (['yy', '[-1]'], {}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['tf_var'], {}), True, 'import tensorflow as tf\n'), (343, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (344, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (454, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (455, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (570, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (610, 'numpy.vstack', 'np.vstack', (['(final_preds, preds)'], {}), True, 'import numpy as np\n'), (240, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', ([], {'num_units': 'state_size', 'activation': 'tf.nn.relu', 'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['lstm'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (243, 'tensorflow.nn.rnn_cell.LSTMCell', 'tf.nn.rnn_cell.LSTMCell', ([], {'num_units': 'state_size', 'state_is_tuple': '(True)'}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['lstm'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['state_size'], {'activation': 'tf.identity'}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['gru'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.contrib.rnn.BasicRNNCell', 'tf.contrib.rnn.BasicRNNCell', (['state_size'], {'activation': 'tf.identity'}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['cell_basic'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (299, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (301, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(cell_l2 + Predict_l2)'], {}), True, 'import tensorflow as tf\n'), (348, 'numpy.size', 'np.size', (['shape'], {}), True, 'import numpy as np\n'), (364, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (459, 'numpy.size', 'np.size', (['shape'], {}), True, 'import numpy as np\n'), (476, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (603, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (605, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (617, 'numpy.vstack', 'np.vstack', (['(final[i], rnn_outputs[i])'], {}), True, 'import numpy as np\n'), (652, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (652, 'numpy.squeeze', 'np.squeeze', (['S'], {}), True, 'import numpy as np\n'), (655, 'numpy.sum', 'np.sum', (['((preds[1:] - test_data_y[1 + k:]) ** 2)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (683, 'numpy.dstack', 'np.dstack', (['(X, YP)'], {}), True, 'import numpy as np\n'), (686, 'numpy.sum', 'np.sum', (['((preds[1:] - test_data_y[k + 1:]) ** 2)'], {'axis': '(0)'}), True, 'import numpy as np\n'), (253, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['state_size'], {'activation': 'tf.nn.relu'}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['gru'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['state_size'], {}), True, 'import tensorflow as tf\n'), (257, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['gru'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.contrib.rnn.BasicRNNCell', 'tf.contrib.rnn.BasicRNNCell', (['state_size'], {'activation': 'tf.nn.relu'}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['cell_basic'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (270, 'tensorflow.contrib.rnn.BasicRNNCell', 'tf.contrib.rnn.BasicRNNCell', (['state_size'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['cell_basic'], {'variational_recurrent': '(True)', 'dtype': 'tf.float32', 'input_size': 'num_input', 'input_keep_prob': 'input_prob', 'state_keep_prob': 'state_prob'}), True, 'import tensorflow as tf\n'), (396, 'numpy.dstack', 'np.dstack', (['(X_val, YP_val)'], {}), True, 'import numpy as np\n'), (507, 'numpy.dstack', 'np.dstack', (['(X_val, YP_val)'], {}), True, 'import numpy as np\n')]
brandondutra/cloudml-samples
3d483593c070c4acd4a9648dbfd7db2be6524583
#!/usr/bin/env python # # Copyright 2018 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. # This tool does either batch or streaming predictions on a trained model. from __future__ import print_function import argparse import json import os import sys import tempfile import pubchem import apache_beam as beam import tensorflow as tf from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.options.pipeline_options import StandardOptions from tensorflow.python.framework import ops from tensorflow.python.saved_model import loader class Predict(beam.DoFn): def __init__(self, model_dir, id_key, meta_tag='serve', meta_signature='predict', meta_predictions='predictions'): super(Predict, self).__init__() self.model_dir = model_dir self.id_key = id_key self.meta_tag = meta_tag self.meta_signature = meta_signature self.meta_predictions = meta_predictions self.session = None self.graph = None self.feed_tensors = None self.fetch_tensors = None def process(self, inputs): # Create a session for every worker only once. The session is not # pickleable, so it can't be created at the DoFn constructor. if not self.session: self.graph = ops.Graph() with self.graph.as_default(): self.session = tf.Session() metagraph_def = loader.load( self.session, {self.meta_tag}, self.model_dir) signature_def = metagraph_def.signature_def[self.meta_signature] # inputs self.feed_tensors = { k: self.graph.get_tensor_by_name(v.name) for k, v in signature_def.inputs.items() } # outputs/predictions self.fetch_tensors = { k: self.graph.get_tensor_by_name(v.name) for k, v in signature_def.outputs.items() } # Create a feed_dict for a single element. feed_dict = { tensor: [inputs[key]] for key, tensor in self.feed_tensors.items() if key in inputs } results = self.session.run(self.fetch_tensors, feed_dict) yield { 'id': inputs[self.id_key], 'predictions': results[self.meta_predictions][0].tolist() } # [START run_definition] def run(model_dir, feature_extraction, sink, beam_options=None): with beam.Pipeline(options=beam_options) as p: _ = (p | 'Feature extraction' >> feature_extraction | 'Predict' >> beam.ParDo(Predict(model_dir, 'ID')) | 'Format as JSON' >> beam.Map(json.dumps) | 'Write predictions' >> sink) # [END run_definition] if __name__ == '__main__': """Main function""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--work-dir', type=str, default=os.path.join( tempfile.gettempdir(), 'cloudml-samples', 'molecules'), help='Directory for temporary files and preprocessed datasets to. ' 'This can be a Google Cloud Storage path.') parser.add_argument( '--model-dir', type=str, required=True, help='Path to the exported TensorFlow model. ' 'This can be a Google Cloud Storage path.') verbs = parser.add_subparsers(dest='verb') batch_verb = verbs.add_parser('batch', help='Batch prediction') batch_verb.add_argument( '--inputs-dir', type=str, required=True, help='Input directory where SDF data files are read from. ' 'This can be a Google Cloud Storage path.') batch_verb.add_argument( '--outputs-dir', type=str, required=True, help='Directory to store prediction results. ' 'This can be a Google Cloud Storage path.') stream_verb = verbs.add_parser('stream', help='Streaming prediction') stream_verb.add_argument( '--inputs-topic', type=str, default='molecules-inputs', help='PubSub topic to subscribe for molecules.') stream_verb.add_argument( '--outputs-topic', type=str, default='molecules-predictions', help='PubSub topic to publish predictions.') args, pipeline_args = parser.parse_known_args() beam_options = PipelineOptions(pipeline_args) beam_options.view_as(SetupOptions).save_main_session = True project = beam_options.view_as(GoogleCloudOptions).project # [START batch_or_stream] if args.verb == 'batch': data_files_pattern = os.path.join(args.inputs_dir, '*.sdf') results_prefix = os.path.join(args.outputs_dir, 'part') source = beam.io.Read(pubchem.ParseSDF(data_files_pattern)) sink = beam.io.WriteToText(results_prefix) elif args.verb == 'stream': if not project: parser.print_usage() print('error: argument --project is required for streaming') sys.exit(1) beam_options.view_as(StandardOptions).streaming = True source = beam.io.ReadFromPubSub(topic='projects/{}/topics/{}'.format( project, args.inputs_topic)) sink = beam.io.WriteStringsToPubSub(topic='projects/{}/topics/{}'.format( project, args.outputs_topic)) # [END batch_or_stream] else: parser.print_usage() sys.exit(1) # [START call_run] run( args.model_dir, pubchem.SimpleFeatureExtraction(source), sink, beam_options) # [END call_run]
[ "tensorflow.python.saved_model.loader.load", "tensorflow.python.framework.ops.Graph", "tensorflow.Session" ]
molecules/predict.py
[(105, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), False, 'import argparse\n'), (153, 'apache_beam.options.pipeline_options.PipelineOptions', 'PipelineOptions', (['pipeline_args'], {}), False, 'from apache_beam.options.pipeline_options import PipelineOptions\n'), (94, 'apache_beam.Pipeline', 'beam.Pipeline', ([], {'options': 'beam_options'}), True, 'import apache_beam as beam\n'), (160, 'os.path.join', 'os.path.join', (['args.inputs_dir', '"""*.sdf"""'], {}), False, 'import os\n'), (161, 'os.path.join', 'os.path.join', (['args.outputs_dir', '"""part"""'], {}), False, 'import os\n'), (163, 'apache_beam.io.WriteToText', 'beam.io.WriteToText', (['results_prefix'], {}), True, 'import apache_beam as beam\n'), (185, 'pubchem.SimpleFeatureExtraction', 'pubchem.SimpleFeatureExtraction', (['source'], {}), False, 'import pubchem\n'), (59, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (162, 'pubchem.ParseSDF', 'pubchem.ParseSDF', (['data_files_pattern'], {}), False, 'import pubchem\n'), (180, 'sys.exit', 'sys.exit', (['(1)'], {}), False, 'import sys\n'), (61, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (62, 'tensorflow.python.saved_model.loader.load', 'loader.load', (['self.session', '{self.meta_tag}', 'self.model_dir'], {}), False, 'from tensorflow.python.saved_model import loader\n'), (112, 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), False, 'import tempfile\n'), (169, 'sys.exit', 'sys.exit', (['(1)'], {}), False, 'import sys\n'), (98, 'apache_beam.Map', 'beam.Map', (['json.dumps'], {}), True, 'import apache_beam as beam\n')]
blahster/tf-models
eaa4a000ef8e5f094764c42a590bb1c49b7b6f7c
# 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. # ============================================================================== """A binary to train CIFAR-10 using multiple GPU's with synchronous updates. Accuracy: cifar10_multi_gpu_train.py achieves ~86% accuracy after 100K steps (256 epochs of data) as judged by cifar10_eval.py. Speed: With batch_size 128. System | Step Time (sec/batch) | Accuracy -------------------------------------------------------------------- 1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours) 1 Tesla K40m | 0.25-0.35 | ~86% at 100K steps (4 hours) 2 Tesla K20m | 0.13-0.20 | ~84% at 30K steps (2.5 hours) 3 Tesla K20m | 0.13-0.18 | ~84% at 30K steps 4 Tesla K20m | ~0.10 | ~84% at 30K steps Usage: Please see the tutorial and website for how to download the CIFAR-10 data set, compile the program and train the model. http://tensorflow.org/tutorials/deep_cnn/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import os.path import re import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import cifar10 FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train', """Directory where to write event logs """ """and checkpoint.""") tf.app.flags.DEFINE_integer('max_steps', 1000000, """Number of batches to run.""") tf.app.flags.DEFINE_integer('num_gpus', 1, """How many GPUs to use.""") tf.app.flags.DEFINE_boolean('log_device_placement', False, """Whether to log device placement.""") def tower_loss(scope): """Calculate the total loss on a single tower running the CIFAR model. Args: scope: unique prefix string identifying the CIFAR tower, e.g. 'tower_0' Returns: Tensor of shape [] containing the total loss for a batch of data """ # Get images and labels for CIFAR-10. images, labels = cifar10.distorted_inputs() # Build inference Graph. logits = cifar10.inference(images) # Build the portion of the Graph calculating the losses. Note that we will # assemble the total_loss using a custom function below. _ = cifar10.loss(logits, labels) # Assemble all of the losses for the current tower only. losses = tf.get_collection('losses', scope) # Calculate the total loss for the current tower. total_loss = tf.add_n(losses, name='total_loss') # Attach a scalar summary to all individual losses and the total loss; do the # same for the averaged version of the losses. for l in losses + [total_loss]: # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training # session. This helps the clarity of presentation on tensorboard. loss_name = re.sub('%s_[0-9]*/' % cifar10.TOWER_NAME, '', l.op.name) tf.summary.scalar(loss_name, l) return total_loss def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each tower. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers. """ average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(axis=0, values=grads) grad = tf.reduce_mean(grad, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def train(): """Train CIFAR-10 for a number of steps.""" with tf.Graph().as_default(), tf.device('/cpu:0'): # Create a variable to count the number of train() calls. This equals the # number of batches processed * FLAGS.num_gpus. global_step = tf.get_variable( 'global_step', [], initializer=tf.constant_initializer(0), trainable=False) # Calculate the learning rate schedule. num_batches_per_epoch = (cifar10.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size) decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY) # Decay the learning rate exponentially based on the number of steps. lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE, global_step, decay_steps, cifar10.LEARNING_RATE_DECAY_FACTOR, staircase=True) # Create an optimizer that performs gradient descent. opt = tf.train.GradientDescentOptimizer(lr) # Calculate the gradients for each model tower. tower_grads = [] with tf.variable_scope(tf.get_variable_scope()): for i in xrange(FLAGS.num_gpus): with tf.device('/gpu:%d' % i): with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope: # Calculate the loss for one tower of the CIFAR model. This function # constructs the entire CIFAR model but shares the variables across # all towers. loss = tower_loss(scope) # Reuse variables for the next tower. tf.get_variable_scope().reuse_variables() # Retain the summaries from the final tower. summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope) # Calculate the gradients for the batch of data on this CIFAR tower. grads = opt.compute_gradients(loss) # Keep track of the gradients across all towers. tower_grads.append(grads) # We must calculate the mean of each gradient. Note that this is the # synchronization point across all towers. grads = average_gradients(tower_grads) # Add a summary to track the learning rate. summaries.append(tf.summary.scalar('learning_rate', lr)) # Add histograms for gradients. for grad, var in grads: if grad is not None: summaries.append(tf.summary.histogram(var.op.name + '/gradients', grad)) # Apply the gradients to adjust the shared variables. apply_gradient_op = opt.apply_gradients(grads, global_step=global_step) # Add histograms for trainable variables. for var in tf.trainable_variables(): summaries.append(tf.summary.histogram(var.op.name, var)) # Track the moving averages of all trainable variables. variable_averages = tf.train.ExponentialMovingAverage( cifar10.MOVING_AVERAGE_DECAY, global_step) variables_averages_op = variable_averages.apply(tf.trainable_variables()) # Group all updates to into a single train op. train_op = tf.group(apply_gradient_op, variables_averages_op) # Create a saver. saver = tf.train.Saver(tf.global_variables()) # Build the summary operation from the last tower summaries. summary_op = tf.summary.merge(summaries) # Build an initialization operation to run below. init = tf.global_variables_initializer() # Start running operations on the Graph. allow_soft_placement must be set to # True to build towers on GPU, as some of the ops do not have GPU # implementations. sess = tf.Session(config=tf.ConfigProto( allow_soft_placement=True, log_device_placement=FLAGS.log_device_placement)) sess.run(init) # Start the queue runners. tf.train.start_queue_runners(sess=sess) summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) for step in xrange(FLAGS.max_steps): start_time = time.time() _, loss_value = sess.run([train_op, loss]) duration = time.time() - start_time assert not np.isnan(loss_value), 'Model diverged with loss = NaN' if step % 10 == 0: num_examples_per_step = FLAGS.batch_size * FLAGS.num_gpus examples_per_sec = num_examples_per_step / duration sec_per_batch = duration / FLAGS.num_gpus format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch)') print (format_str % (datetime.now(), step, loss_value, examples_per_sec, sec_per_batch)) if step % 100 == 0: summary_str = sess.run(summary_op) summary_writer.add_summary(summary_str, step) # Save the model checkpoint periodically. if step % 1000 == 0 or (step + 1) == FLAGS.max_steps: checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step=step) def main(argv=None): # pylint: disable=unused-argument cifar10.maybe_download_and_extract() if tf.gfile.Exists(FLAGS.train_dir): tf.gfile.DeleteRecursively(FLAGS.train_dir) tf.gfile.MakeDirs(FLAGS.train_dir) train() if __name__ == '__main__': tf.app.run()
[ "tensorflow.device", "tensorflow.concat", "tensorflow.gfile.DeleteRecursively", "tensorflow.gfile.Exists", "tensorflow.global_variables", "tensorflow.train.ExponentialMovingAverage", "tensorflow.gfile.MakeDirs", "tensorflow.app.flags.DEFINE_string", "tensorflow.app.flags.DEFINE_boolean", "tensorflow.group", "tensorflow.summary.scalar", "tensorflow.add_n", "tensorflow.Graph", "tensorflow.get_collection", "tensorflow.app.flags.DEFINE_integer", "tensorflow.train.exponential_decay", "tensorflow.ConfigProto", "tensorflow.name_scope", "tensorflow.trainable_variables", "tensorflow.app.run", "numpy.isnan", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.summary.merge", "tensorflow.summary.histogram", "tensorflow.summary.FileWriter", "tensorflow.reduce_mean", "tensorflow.train.start_queue_runners", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.get_variable_scope" ]
tutorials/image/cifar10/cifar10_multi_gpu_train.py
[(54, 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""train_dir"""', '"""/tmp/cifar10_train"""', '"""Directory where to write event logs and checkpoint."""'], {}), True, 'import tensorflow as tf\n'), (57, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""max_steps"""', '(1000000)', '"""Number of batches to run."""'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""num_gpus"""', '(1)', '"""How many GPUs to use."""'], {}), True, 'import tensorflow as tf\n'), (61, 'tensorflow.app.flags.DEFINE_boolean', 'tf.app.flags.DEFINE_boolean', (['"""log_device_placement"""', '(False)', '"""Whether to log device placement."""'], {}), True, 'import tensorflow as tf\n'), (75, 'cifar10.distorted_inputs', 'cifar10.distorted_inputs', ([], {}), False, 'import cifar10\n'), (78, 'cifar10.inference', 'cifar10.inference', (['images'], {}), False, 'import cifar10\n'), (82, 'cifar10.loss', 'cifar10.loss', (['logits', 'labels'], {}), False, 'import cifar10\n'), (85, 'tensorflow.get_collection', 'tf.get_collection', (['"""losses"""', 'scope'], {}), True, 'import tensorflow as tf\n'), (88, 'tensorflow.add_n', 'tf.add_n', (['losses'], {'name': '"""total_loss"""'}), True, 'import tensorflow as tf\n'), (263, 'cifar10.maybe_download_and_extract', 'cifar10.maybe_download_and_extract', ([], {}), False, 'import cifar10\n'), (264, 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['FLAGS.train_dir'], {}), True, 'import tensorflow as tf\n'), (266, 'tensorflow.gfile.MakeDirs', 'tf.gfile.MakeDirs', (['FLAGS.train_dir'], {}), True, 'import tensorflow as tf\n'), (271, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (95, 're.sub', 're.sub', (["('%s_[0-9]*/' % cifar10.TOWER_NAME)", '""""""', 'l.op.name'], {}), False, 'import re\n'), (96, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['loss_name', 'l'], {}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(0)', 'values': 'grads'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['grad', '(0)'], {}), True, 'import tensorflow as tf\n'), (141, 'tensorflow.device', 'tf.device', (['"""/cpu:0"""'], {}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['cifar10.INITIAL_LEARNING_RATE', 'global_step', 'decay_steps', 'cifar10.LEARNING_RATE_DECAY_FACTOR'], {'staircase': '(True)'}), True, 'import tensorflow as tf\n'), (161, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['lr'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (206, 'tensorflow.train.ExponentialMovingAverage', 'tf.train.ExponentialMovingAverage', (['cifar10.MOVING_AVERAGE_DECAY', 'global_step'], {}), True, 'import tensorflow as tf\n'), (211, 'tensorflow.group', 'tf.group', (['apply_gradient_op', 'variables_averages_op'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.summary.merge', 'tf.summary.merge', (['summaries'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (231, 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {'sess': 'sess'}), True, 'import tensorflow as tf\n'), (233, 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['FLAGS.train_dir', 'sess.graph'], {}), True, 'import tensorflow as tf\n'), (235, 'six.moves.xrange', 'xrange', (['FLAGS.max_steps'], {}), False, 'from six.moves import xrange\n'), (265, 'tensorflow.gfile.DeleteRecursively', 'tf.gfile.DeleteRecursively', (['FLAGS.train_dir'], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.expand_dims', 'tf.expand_dims', (['g', '(0)'], {}), True, 'import tensorflow as tf\n'), (166, 'six.moves.xrange', 'xrange', (['FLAGS.num_gpus'], {}), False, 'from six.moves import xrange\n'), (191, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""learning_rate"""', 'lr'], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (236, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (141, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0)'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n'), (203, 'tensorflow.summary.histogram', 'tf.summary.histogram', (['var.op.name', 'var'], {}), True, 'import tensorflow as tf\n'), (225, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)', 'log_device_placement': 'FLAGS.log_device_placement'}), True, 'import tensorflow as tf\n'), (238, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (240, 'numpy.isnan', 'np.isnan', (['loss_value'], {}), True, 'import numpy as np\n'), (167, 'tensorflow.device', 'tf.device', (["('/gpu:%d' % i)"], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.summary.histogram', 'tf.summary.histogram', (["(var.op.name + '/gradients')", 'grad'], {}), True, 'import tensorflow as tf\n'), (168, 'tensorflow.name_scope', 'tf.name_scope', (["('%s_%d' % (cifar10.TOWER_NAME, i))"], {}), True, 'import tensorflow as tf\n'), (178, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.SUMMARIES', 'scope'], {}), True, 'import tensorflow as tf\n'), (249, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (175, 'tensorflow.get_variable_scope', 'tf.get_variable_scope', ([], {}), True, 'import tensorflow as tf\n')]
smarthi/tensorflow
55b01593515817992821423fec19733bca91c918
# 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. # ============================================================================== """Text datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tarfile import numpy as np from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.python.platform import gfile DBPEDIA_URL = 'https://github.com/le-scientifique/torchDatasets/blob/master/dbpedia_csv.tar.gz' def maybe_download_dbpedia(data_dir): """Download if DBpedia data is not present.""" train_path = os.path.join(data_dir, 'dbpedia_csv/train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv/test.csv') if not (gfile.Exists(train_path) and gfile.Exists(test_path)): archive_path = base.maybe_download( 'dbpedia_csv.tar.gz', data_dir, DBPEDIA_URL) tfile = tarfile.open(archive_path, 'r:*') tfile.extractall(data_dir) def load_dbpedia(size='small', test_with_fake_data=False): """Get DBpedia datasets from CSV files.""" if not test_with_fake_data: data_dir = os.path.join(os.getenv('TF_EXP_BASE_DIR', ''), 'dbpedia_data') maybe_download_dbpedia(data_dir) train_path = os.path.join(data_dir, 'dbpedia_csv', 'train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv', 'test.csv') if size == 'small': # Reduce the size of original data by a factor of 1000. base.shrink_csv(train_path, 1000) base.shrink_csv(test_path, 1000) train_path = train_path.replace('train.csv', 'train_small.csv') test_path = test_path.replace('test.csv', 'test_small.csv') else: module_path = os.path.dirname(__file__) train_path = os.path.join(module_path, 'data', 'text_train.csv') test_path = os.path.join(module_path, 'data', 'text_test.csv') train = base.load_csv_without_header( train_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) test = base.load_csv_without_header( test_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) return base.Datasets(train=train, validation=None, test=test)
[ "tensorflow.contrib.learn.python.learn.datasets.base.Datasets", "tensorflow.python.platform.gfile.Exists", "tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header", "tensorflow.contrib.learn.python.learn.datasets.base.shrink_csv", "tensorflow.contrib.learn.python.learn.datasets.base.maybe_download" ]
tensorflow/contrib/learn/python/learn/datasets/text_datasets.py
[(35, 'os.path.join', 'os.path.join', (['data_dir', '"""dbpedia_csv/train.csv"""'], {}), False, 'import os\n'), (36, 'os.path.join', 'os.path.join', (['data_dir', '"""dbpedia_csv/test.csv"""'], {}), False, 'import os\n'), (64, 'tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header', 'base.load_csv_without_header', (['train_path'], {'target_dtype': 'np.int32', 'features_dtype': 'np.str', 'target_column': '(0)'}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (66, 'tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header', 'base.load_csv_without_header', (['test_path'], {'target_dtype': 'np.int32', 'features_dtype': 'np.str', 'target_column': '(0)'}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (69, 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets', 'base.Datasets', ([], {'train': 'train', 'validation': 'None', 'test': 'test'}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (38, 'tensorflow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', (['"""dbpedia_csv.tar.gz"""', 'data_dir', 'DBPEDIA_URL'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (40, 'tarfile.open', 'tarfile.open', (['archive_path', '"""r:*"""'], {}), False, 'import tarfile\n'), (50, 'os.path.join', 'os.path.join', (['data_dir', '"""dbpedia_csv"""', '"""train.csv"""'], {}), False, 'import os\n'), (51, 'os.path.join', 'os.path.join', (['data_dir', '"""dbpedia_csv"""', '"""test.csv"""'], {}), False, 'import os\n'), (60, 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), False, 'import os\n'), (61, 'os.path.join', 'os.path.join', (['module_path', '"""data"""', '"""text_train.csv"""'], {}), False, 'import os\n'), (62, 'os.path.join', 'os.path.join', (['module_path', '"""data"""', '"""text_test.csv"""'], {}), False, 'import os\n'), (37, 'tensorflow.python.platform.gfile.Exists', 'gfile.Exists', (['train_path'], {}), False, 'from tensorflow.python.platform import gfile\n'), (37, 'tensorflow.python.platform.gfile.Exists', 'gfile.Exists', (['test_path'], {}), False, 'from tensorflow.python.platform import gfile\n'), (47, 'os.getenv', 'os.getenv', (['"""TF_EXP_BASE_DIR"""', '""""""'], {}), False, 'import os\n'), (55, 'tensorflow.contrib.learn.python.learn.datasets.base.shrink_csv', 'base.shrink_csv', (['train_path', '(1000)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (56, 'tensorflow.contrib.learn.python.learn.datasets.base.shrink_csv', 'base.shrink_csv', (['test_path', '(1000)'], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n')]
smarthi/tensorflow
55b01593515817992821423fec19733bca91c918
# 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. # ============================================================================== """Regression test for DNNLinearCombinedEstimator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import tempfile from tensorflow.contrib.layers.python.layers import feature_column from tensorflow.contrib.learn.python.learn.datasets import base from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils from tensorflow.contrib.learn.python.learn.estimators import run_config from tensorflow.contrib.learn.python.learn.estimators import test_data 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 array_ops from tensorflow.python.platform import test from tensorflow.python.training import adagrad from tensorflow.python.training import ftrl from tensorflow.python.training import server_lib FLAGS = tf.flags.FLAGS # Desired training steps, reported in benchmark. Actual steps might be slightly # more than this since supervisor training runs for a non-detrministic number of # steps. _ITERS = 100 _METRIC_KEYS = { 'accuracy', 'auc', 'accuracy/threshold_0.500000_mean', 'loss', 'precision/positive_threshold_0.500000_mean', 'recall/positive_threshold_0.500000_mean', } class DNNLinearCombinedClassifierBenchmark(test.Benchmark): def _assertSingleClassMetrics(self, metrics): estimator_test_utils.assert_in_range(0.9, 1.0, 'auc', metrics) estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy/threshold_0.500000_mean', metrics) estimator_test_utils.assert_in_range( 0.9, 1.0, 'precision/positive_threshold_0.500000_mean', metrics) estimator_test_utils.assert_in_range( 0.9, 1.0, 'recall/positive_threshold_0.500000_mean', metrics) self._assertCommonMetrics(metrics) def _assertCommonMetrics(self, metrics): estimator_test_utils.assert_in_range(_ITERS, _ITERS + 5, 'global_step', metrics) estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy', metrics) estimator_test_utils.assert_in_range(0.0, 0.2, 'loss', metrics) self.report_benchmark( iters=metrics['global_step'], extras={k: v for k, v in metrics.items() if k in _METRIC_KEYS}) def benchmarkMatrixData(self): iris = test_data.prepare_iris_data_for_logistic_regression() cont_feature = feature_column.real_valued_column('feature', dimension=4) bucketized_feature = feature_column.bucketized_column( cont_feature, test_data.get_quantile_based_buckets(iris.data, 10)) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( model_dir=tempfile.mkdtemp(), linear_feature_columns=(bucketized_feature,), dnn_feature_columns=(cont_feature,), dnn_hidden_units=(3, 3)) input_fn = test_data.iris_input_logistic_fn metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate( input_fn=input_fn, steps=100) self._assertSingleClassMetrics(metrics) def benchmarkTensorData(self): def _input_fn(): iris = test_data.prepare_iris_data_for_logistic_regression() features = {} for i in range(4): # The following shows how to provide the Tensor data for # RealValuedColumns. features.update({ str(i): array_ops.reshape( constant_op.constant( iris.data[:, i], dtype=dtypes.float32), (-1, 1)) }) # The following shows how to provide the SparseTensor data for # a SparseColumn. features['dummy_sparse_column'] = sparse_tensor.SparseTensor( values=('en', 'fr', 'zh'), indices=((0, 0), (0, 1), (60, 0)), dense_shape=(len(iris.target), 2)) labels = array_ops.reshape( constant_op.constant( iris.target, dtype=dtypes.int32), (-1, 1)) return features, labels iris = test_data.prepare_iris_data_for_logistic_regression() cont_features = [ feature_column.real_valued_column(str(i)) for i in range(4) ] linear_features = [ feature_column.bucketized_column( cont_features[i], test_data.get_quantile_based_buckets(iris.data[:, i], 10)) for i in range(4) ] linear_features.append( feature_column.sparse_column_with_hash_bucket( 'dummy_sparse_column', hash_bucket_size=100)) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( model_dir=tempfile.mkdtemp(), linear_feature_columns=linear_features, dnn_feature_columns=cont_features, dnn_hidden_units=(3, 3)) metrics = classifier.fit(input_fn=_input_fn, steps=_ITERS).evaluate( input_fn=_input_fn, steps=100) self._assertSingleClassMetrics(metrics) def benchmarkCustomOptimizer(self): iris = test_data.prepare_iris_data_for_logistic_regression() cont_feature = feature_column.real_valued_column('feature', dimension=4) bucketized_feature = feature_column.bucketized_column( cont_feature, test_data.get_quantile_based_buckets(iris.data, 10)) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( model_dir=tempfile.mkdtemp(), linear_feature_columns=(bucketized_feature,), linear_optimizer=ftrl.FtrlOptimizer(learning_rate=0.1), dnn_feature_columns=(cont_feature,), dnn_hidden_units=(3, 3), dnn_optimizer=adagrad.AdagradOptimizer(learning_rate=0.1)) input_fn = test_data.iris_input_logistic_fn metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate( input_fn=input_fn, steps=100) self._assertSingleClassMetrics(metrics) def benchmarkMultiClass(self): iris = base.load_iris() cont_feature = feature_column.real_valued_column('feature', dimension=4) bucketized_feature = feature_column.bucketized_column( cont_feature, test_data.get_quantile_based_buckets(iris.data, 10)) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( n_classes=3, linear_feature_columns=(bucketized_feature,), dnn_feature_columns=(cont_feature,), dnn_hidden_units=(3, 3)) input_fn = test_data.iris_input_multiclass_fn metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate( input_fn=input_fn, steps=100) self._assertCommonMetrics(metrics) def benchmarkPartitionedVariables(self): def _input_fn(): features = { 'language': sparse_tensor.SparseTensor( values=('en', 'fr', 'zh'), indices=((0, 0), (0, 1), (2, 0)), dense_shape=(3, 2)) } labels = constant_op.constant(((1,), (0,), (0,))) return features, labels # The given hash_bucket_size results in variables larger than the # default min_slice_size attribute, so the variables are partitioned. sparse_feature = feature_column.sparse_column_with_hash_bucket( 'language', hash_bucket_size=2e7) embedding_feature = feature_column.embedding_column( sparse_feature, dimension=1) tf_config = { 'cluster': { run_config.TaskType.PS: ['fake_ps_0', 'fake_ps_1'] } } with test.mock.patch.dict('os.environ', {'TF_CONFIG': json.dumps(tf_config)}): config = run_config.RunConfig() # Because we did not start a distributed cluster, we need to pass an # empty ClusterSpec, otherwise the device_setter will look for # distributed jobs, such as "/job:ps" which are not present. config._cluster_spec = server_lib.ClusterSpec({}) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( linear_feature_columns=(sparse_feature,), dnn_feature_columns=(embedding_feature,), dnn_hidden_units=(3, 3), config=config) metrics = classifier.fit(input_fn=_input_fn, steps=_ITERS).evaluate( input_fn=_input_fn, steps=100) self._assertCommonMetrics(metrics) if __name__ == '__main__': test.main()
[ "tensorflow.contrib.layers.python.layers.feature_column.embedding_column", "tensorflow.python.training.ftrl.FtrlOptimizer", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.contrib.learn.python.learn.datasets.base.load_iris", "tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket", "tensorflow.python.training.adagrad.AdagradOptimizer", "tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.platform.test.main", "tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression", "tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range", "tensorflow.contrib.layers.python.layers.feature_column.real_valued_column", "tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets", "tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier", "tensorflow.python.framework.constant_op.constant" ]
tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined_benchmark_test.py
[(225, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (58, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.9)', '(1.0)', '"""auc"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (59, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.9)', '(1.0)', '"""accuracy/threshold_0.500000_mean"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (62, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.9)', '(1.0)', '"""precision/positive_threshold_0.500000_mean"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (64, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.9)', '(1.0)', '"""recall/positive_threshold_0.500000_mean"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (69, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['_ITERS', '(_ITERS + 5)', '"""global_step"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (71, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.9)', '(1.0)', '"""accuracy"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (72, 'tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range', 'estimator_test_utils.assert_in_range', (['(0.0)', '(0.2)', '"""loss"""', 'metrics'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils\n'), (79, 'tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression', 'test_data.prepare_iris_data_for_logistic_regression', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (80, 'tensorflow.contrib.layers.python.layers.feature_column.real_valued_column', 'feature_column.real_valued_column', (['"""feature"""'], {'dimension': '(4)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (120, 'tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression', 'test_data.prepare_iris_data_for_logistic_regression', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (145, 'tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression', 'test_data.prepare_iris_data_for_logistic_regression', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (146, 'tensorflow.contrib.layers.python.layers.feature_column.real_valued_column', 'feature_column.real_valued_column', (['"""feature"""'], {'dimension': '(4)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (164, 'tensorflow.contrib.learn.python.learn.datasets.base.load_iris', 'base.load_iris', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), (165, 'tensorflow.contrib.layers.python.layers.feature_column.real_valued_column', 'feature_column.real_valued_column', (['"""feature"""'], {'dimension': '(4)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (169, 'tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier', 'dnn_linear_combined.DNNLinearCombinedClassifier', ([], {'n_classes': '(3)', 'linear_feature_columns': '(bucketized_feature,)', 'dnn_feature_columns': '(cont_feature,)', 'dnn_hidden_units': '(3, 3)'}), False, 'from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined\n'), (195, 'tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket', 'feature_column.sparse_column_with_hash_bucket', (['"""language"""'], {'hash_bucket_size': '(20000000.0)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (197, 'tensorflow.contrib.layers.python.layers.feature_column.embedding_column', 'feature_column.embedding_column', (['sparse_feature'], {'dimension': '(1)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (213, 'tensorflow.contrib.learn.python.learn.estimators.dnn_linear_combined.DNNLinearCombinedClassifier', 'dnn_linear_combined.DNNLinearCombinedClassifier', ([], {'linear_feature_columns': '(sparse_feature,)', 'dnn_feature_columns': '(embedding_feature,)', 'dnn_hidden_units': '(3, 3)', 'config': 'config'}), False, 'from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined\n'), (82, 'tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets', 'test_data.get_quantile_based_buckets', (['iris.data', '(10)'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (98, 'tensorflow.contrib.learn.python.learn.estimators.test_data.prepare_iris_data_for_logistic_regression', 'test_data.prepare_iris_data_for_logistic_regression', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (131, 'tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket', 'feature_column.sparse_column_with_hash_bucket', (['"""dummy_sparse_column"""'], {'hash_bucket_size': '(100)'}), False, 'from tensorflow.contrib.layers.python.layers import feature_column\n'), (148, 'tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets', 'test_data.get_quantile_based_buckets', (['iris.data', '(10)'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (167, 'tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets', 'test_data.get_quantile_based_buckets', (['iris.data', '(10)'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (190, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['((1,), (0,), (0,))'], {}), False, 'from tensorflow.python.framework import constant_op\n'), (207, 'tensorflow.contrib.learn.python.learn.estimators.run_config.RunConfig', 'run_config.RunConfig', ([], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import run_config\n'), (211, 'tensorflow.python.training.server_lib.ClusterSpec', 'server_lib.ClusterSpec', (['{}'], {}), False, 'from tensorflow.python.training import server_lib\n'), (85, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (116, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['iris.target'], {'dtype': 'dtypes.int32'}), False, 'from tensorflow.python.framework import constant_op\n'), (127, 'tensorflow.contrib.learn.python.learn.estimators.test_data.get_quantile_based_buckets', 'test_data.get_quantile_based_buckets', (['iris.data[:, (i)]', '(10)'], {}), False, 'from tensorflow.contrib.learn.python.learn.estimators import test_data\n'), (135, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (151, 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), False, 'import tempfile\n'), (153, 'tensorflow.python.training.ftrl.FtrlOptimizer', 'ftrl.FtrlOptimizer', ([], {'learning_rate': '(0.1)'}), False, 'from tensorflow.python.training import ftrl\n'), (156, 'tensorflow.python.training.adagrad.AdagradOptimizer', 'adagrad.AdagradOptimizer', ([], {'learning_rate': '(0.1)'}), False, 'from tensorflow.python.training import adagrad\n'), (185, 'tensorflow.python.framework.sparse_tensor.SparseTensor', 'sparse_tensor.SparseTensor', ([], {'values': "('en', 'fr', 'zh')", 'indices': '((0, 0), (0, 1), (2, 0))', 'dense_shape': '(3, 2)'}), False, 'from tensorflow.python.framework import sparse_tensor\n'), (206, 'json.dumps', 'json.dumps', (['tf_config'], {}), False, 'import json\n'), (106, 'tensorflow.python.framework.constant_op.constant', 'constant_op.constant', (['iris.data[:, (i)]'], {'dtype': 'dtypes.float32'}), False, 'from tensorflow.python.framework import constant_op\n')]
thodan/epos
d67657bbb06da5a6adb8a035a2f58fc305e396f7
# 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 the definition for Gated Separable 3D nets (S3D-G). The nets architecture is proposed by: Saining Xie, Chen Sun, Jonathan Huang, Zhuowen Tu and Kevin Murphy, Rethinking Spatiotemporal Feature Learning For Video Understanding. https://arxiv.org/abs/1712.04851. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import i3d_utils trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev) conv3d_spatiotemporal = i3d_utils.conv3d_spatiotemporal inception_block_v1_3d = i3d_utils.inception_block_v1_3d # Orignaly, arg_scope = slim.arg_scope and layers = slim, now switch to more # update-to-date tf.contrib.* API. arg_scope = tf.contrib.framework.arg_scope layers = tf.contrib.layers def s3dg_arg_scope(weight_decay=1e-7, batch_norm_decay=0.999, batch_norm_epsilon=0.001): """Defines default arg_scope for S3D-G. Args: weight_decay: The weight decay to use for regularizing the nets. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. Returns: sc: An arg_scope to use for the models. """ batch_norm_params = { # Decay for the moving averages. 'decay': batch_norm_decay, # epsilon to prevent 0s in variance. 'epsilon': batch_norm_epsilon, # Turns off fused batch norm. 'fused': False, # collection containing the moving mean and moving variance. 'variables_collections': { 'beta': None, 'gamma': None, 'moving_mean': ['moving_vars'], 'moving_variance': ['moving_vars'], } } with arg_scope( [layers.conv3d, conv3d_spatiotemporal], weights_regularizer=layers.l2_regularizer(weight_decay), activation_fn=tf.nn.relu, normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params): with arg_scope([conv3d_spatiotemporal], separable=True) as sc: return sc def self_gating(input_tensor, scope, data_format='NDHWC'): """Feature gating as used in S3D-G. Transforms the input features by aggregating features from all spatial and temporal locations, and applying gating conditioned on the aggregated features. More details can be found at: https://arxiv.org/abs/1712.04851 Args: input_tensor: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. scope: scope for `variable_scope`. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. Returns: A tensor with the same shape as input_tensor. """ index_c = data_format.index('C') index_d = data_format.index('D') index_h = data_format.index('H') index_w = data_format.index('W') input_shape = input_tensor.get_shape().as_list() t = input_shape[index_d] w = input_shape[index_w] h = input_shape[index_h] num_channels = input_shape[index_c] spatiotemporal_average = layers.avg_pool3d( input_tensor, [t, w, h], stride=1, data_format=data_format, scope=scope + '/self_gating/avg_pool3d') weights = layers.conv3d( spatiotemporal_average, num_channels, [1, 1, 1], activation_fn=None, normalizer_fn=None, biases_initializer=None, data_format=data_format, weights_initializer=trunc_normal(0.01), scope=scope + '/self_gating/transformer_W') tile_multiples = [1, t, w, h] tile_multiples.insert(index_c, 1) weights = tf.tile(weights, tile_multiples) weights = tf.nn.sigmoid(weights) return tf.multiply(weights, input_tensor) def s3dg_base(inputs, first_temporal_kernel_size=3, temporal_conv_startat='Conv2d_2c_3x3', gating_startat='Conv2d_2c_3x3', final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, data_format='NDHWC', scope='InceptionV1'): """Defines the I3D/S3DG base architecture. Note that we use the names as defined in Inception V1 to facilitate checkpoint conversion from an image-trained Inception V1 checkpoint to I3D checkpoint. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. first_temporal_kernel_size: Specifies the temporal kernel size for the first conv3d filter. A larger value slows down the nets but provides little accuracy improvement. The default is 7 in the original I3D and S3D-G but 3 gives better performance. Must be set to one of 1, 3, 5 or 7. temporal_conv_startat: Specifies the first conv block to use 3D or separable 3D convs rather than 2D convs (implemented as [1, k, k] 3D conv). This is used to construct the inverted pyramid models. 'Conv2d_2c_3x3' is the first valid block to use separable 3D convs. If provided block name is not present, all valid blocks will use separable 3D convs. Note that 'Conv2d_1a_7x7' cannot be made into a separable 3D conv, but can be made into a 2D or 3D conv using the `first_temporal_kernel_size` option. gating_startat: Specifies the first conv block to use self gating. 'Conv2d_2c_3x3' is the first valid block to use self gating. If provided block name is not present, all valid blocks will use separable 3D convs. final_endpoint: Specifies the endpoint to construct the nets up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the nets. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: Optional variable_scope. Returns: A dictionary from components of the nets to the corresponding activation. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or if depth_multiplier <= 0. """ assert data_format in ['NDHWC', 'NCDHW'] end_points = {} t = 1 # For inverted pyramid models, we start with gating switched off. use_gating = False self_gating_fn = None def gating_fn(inputs, scope): return self_gating(inputs, scope, data_format=data_format) if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV1', [inputs]): with arg_scope([layers.conv3d], weights_initializer=trunc_normal(0.01)): with arg_scope( [layers.conv3d, layers.max_pool3d, conv3d_spatiotemporal], stride=1, data_format=data_format, padding='SAME'): # batch_size x 32 x 112 x 112 x 64 end_point = 'Conv2d_1a_7x7' if first_temporal_kernel_size not in [1, 3, 5, 7]: raise ValueError( 'first_temporal_kernel_size can only be 1, 3, 5 or 7.') # Separable conv is slow when used at first conv layer. net = conv3d_spatiotemporal( inputs, depth(64), [first_temporal_kernel_size, 7, 7], stride=2, separable=False, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 64 end_point = 'MaxPool_2a_3x3' net = layers.max_pool3d( net, [1, 3, 3], stride=[1, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 64 end_point = 'Conv2d_2b_1x1' net = layers.conv3d(net, depth(64), [1, 1, 1], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 56 x 56 x 192 end_point = 'Conv2d_2c_3x3' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = conv3d_spatiotemporal(net, depth(192), [t, 3, 3], scope=end_point) if use_gating: net = self_gating(net, scope=end_point, data_format=data_format) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 28 x 28 x 192 end_point = 'MaxPool_3a_3x3' net = layers.max_pool3d( net, [1, 3, 3], stride=[1, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 32 x 28 x 28 x 256 end_point = 'Mixed_3b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(64), num_outputs_1_0a=depth(96), num_outputs_1_0b=depth(128), num_outputs_2_0a=depth(16), num_outputs_2_0b=depth(32), num_outputs_3_0b=depth(32), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'Mixed_3c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(128), num_outputs_1_0a=depth(128), num_outputs_1_0b=depth(192), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(96), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_4a_3x3' net = layers.max_pool3d( net, [3, 3, 3], stride=[2, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(192), num_outputs_1_0a=depth(96), num_outputs_1_0b=depth(208), num_outputs_2_0a=depth(16), num_outputs_2_0b=depth(48), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(160), num_outputs_1_0a=depth(112), num_outputs_1_0b=depth(224), num_outputs_2_0a=depth(24), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 512 end_point = 'Mixed_4d' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(128), num_outputs_1_0a=depth(128), num_outputs_1_0b=depth(256), num_outputs_2_0a=depth(24), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 528 end_point = 'Mixed_4e' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(112), num_outputs_1_0a=depth(144), num_outputs_1_0b=depth(288), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(64), num_outputs_3_0b=depth(64), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 16 x 14 x 14 x 832 end_point = 'Mixed_4f' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(256), num_outputs_1_0a=depth(160), num_outputs_1_0b=depth(320), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points end_point = 'MaxPool_5a_2x2' net = layers.max_pool3d( net, [2, 2, 2], stride=[2, 2, 2], scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 8 x 7 x 7 x 832 end_point = 'Mixed_5b' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(256), num_outputs_1_0a=depth(160), num_outputs_1_0b=depth(320), num_outputs_2_0a=depth(32), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points # batch_size x 8 x 7 x 7 x 1024 end_point = 'Mixed_5c' if temporal_conv_startat == end_point: t = 3 if gating_startat == end_point: use_gating = True self_gating_fn = gating_fn net = inception_block_v1_3d( net, num_outputs_0_0a=depth(384), num_outputs_1_0a=depth(192), num_outputs_1_0b=depth(384), num_outputs_2_0a=depth(48), num_outputs_2_0b=depth(128), num_outputs_3_0b=depth(128), temporal_kernel_size=t, self_gating_fn=self_gating_fn, data_format=data_format, scope=end_point) end_points[end_point] = net if final_endpoint == end_point: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint) def s3dg(inputs, num_classes=1000, first_temporal_kernel_size=3, temporal_conv_startat='Conv2d_2c_3x3', gating_startat='Conv2d_2c_3x3', final_endpoint='Mixed_5c', min_depth=16, depth_multiplier=1.0, dropout_keep_prob=0.8, is_training=True, prediction_fn=layers.softmax, spatial_squeeze=True, reuse=None, data_format='NDHWC', scope='InceptionV1'): """Defines the S3D-G architecture. The default image size used to train this nets is 224x224. Args: inputs: A 5-D float tensor of size [batch_size, num_frames, height, width, channels]. num_classes: number of predicted classes. first_temporal_kernel_size: Specifies the temporal kernel size for the first conv3d filter. A larger value slows down the nets but provides little accuracy improvement. Must be set to one of 1, 3, 5 or 7. temporal_conv_startat: Specifies the first conv block to use separable 3D convs rather than 2D convs (implemented as [1, k, k] 3D conv). This is used to construct the inverted pyramid models. 'Conv2d_2c_3x3' is the first valid block to use separable 3D convs. If provided block name is not present, all valid blocks will use separable 3D convs. gating_startat: Specifies the first conv block to use self gating. 'Conv2d_2c_3x3' is the first valid block to use self gating. If provided block name is not present, all valid blocks will use separable 3D convs. final_endpoint: Specifies the endpoint to construct the nets up to. It can be one of ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool_5a_2x2', 'Mixed_5b', 'Mixed_5c'] min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the nets. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the nets and its variables should be reused. To be able to reuse 'scope' must be given. data_format: An optional string from: "NDHWC", "NCDHW". Defaults to "NDHWC". The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in_depth, in_height, in_width, in_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in_channels, in_depth, in_height, in_width]. scope: Optional variable_scope. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, num_classes] end_points: a dictionary from components of the nets to the corresponding activation. """ assert data_format in ['NDHWC', 'NCDHW'] # Final pooling and prediction with tf.variable_scope( scope, 'InceptionV1', [inputs, num_classes], reuse=reuse) as scope: with arg_scope( [layers.batch_norm, layers.dropout], is_training=is_training): net, end_points = s3dg_base( inputs, first_temporal_kernel_size=first_temporal_kernel_size, temporal_conv_startat=temporal_conv_startat, gating_startat=gating_startat, final_endpoint=final_endpoint, min_depth=min_depth, depth_multiplier=depth_multiplier, data_format=data_format, scope=scope) with tf.variable_scope('Logits'): if data_format.startswith('NC'): net = tf.transpose(net, [0, 2, 3, 4, 1]) kernel_size = i3d_utils.reduced_kernel_size_3d(net, [2, 7, 7]) net = layers.avg_pool3d( net, kernel_size, stride=1, data_format='NDHWC', scope='AvgPool_0a_7x7') net = layers.dropout(net, dropout_keep_prob, scope='Dropout_0b') logits = layers.conv3d( net, num_classes, [1, 1, 1], activation_fn=None, normalizer_fn=None, data_format='NDHWC', scope='Conv2d_0c_1x1') # Temporal average pooling. logits = tf.reduce_mean(logits, axis=1) if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points s3dg.default_image_size = 224
[ "tensorflow.multiply", "tensorflow.nn.sigmoid", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.truncated_normal_initializer", "tensorflow.squeeze", "tensorflow.variable_scope", "tensorflow.tile" ]
external/slim/nets/s3dg.py
[(31, 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', (['(0.0)', 'stddev'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.tile', 'tf.tile', (['weights', 'tile_multiples'], {}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['weights'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.multiply', 'tf.multiply', (['weights', 'input_tensor'], {}), True, 'import tensorflow as tf\n'), (210, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""InceptionV1"""', '[inputs]'], {}), True, 'import tensorflow as tf\n'), (557, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope', '"""InceptionV1"""', '[inputs, num_classes]'], {'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (571, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Logits"""'], {}), True, 'import tensorflow as tf\n'), (574, 'nets.i3d_utils.reduced_kernel_size_3d', 'i3d_utils.reduced_kernel_size_3d', (['net', '[2, 7, 7]'], {}), False, 'from nets import i3d_utils\n'), (590, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['logits'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (573, 'tensorflow.transpose', 'tf.transpose', (['net', '[0, 2, 3, 4, 1]'], {}), True, 'import tensorflow as tf\n'), (592, 'tensorflow.squeeze', 'tf.squeeze', (['logits', '[1, 2]'], {'name': '"""SpatialSqueeze"""'}), True, 'import tensorflow as tf\n')]
okojoalg/Creative-Adversarial-Networks
7f06f395b9f317f9235dc8c60c7b385cd6530471
# 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. # ============================================================================== """DCGAN generator and discriminator from https://arxiv.org/abs/1511.06434.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from math import log import tensorflow as tf import tf_slim as slim def _validate_image_inputs(inputs): inputs.get_shape().assert_has_rank(4) inputs.get_shape()[1:3].assert_is_fully_defined() if inputs.get_shape()[1] != inputs.get_shape()[2]: raise ValueError('Input tensor does not have equal width and height: ', inputs.get_shape()[1:3]) width = inputs.get_shape().as_list()[1] if log(width, 2) != int(log(width, 2)): raise ValueError('Input tensor `width` is not a power of 2: ', width) # TODO(joelshor): Use fused batch norm by default. Investigate why some GAN # setups need the gradient of gradient FusedBatchNormGrad. def discriminator(inputs, depth=64, is_training=True, reuse=None, scope='Discriminator', fused_batch_norm=False): """Discriminator network for DCGAN. Construct discriminator network from inputs to the final endpoint. Args: inputs: A tensor of size [batch_size, height, width, channels]. Must be floating point. depth: Number of channels in first convolution layer. is_training: Whether the network is for training or not. reuse: Whether or not the network variables should be reused. `scope` must be given to be reused. scope: Optional variable_scope. fused_batch_norm: If `True`, use a faster, fused implementation of batch norm. Returns: logits: The pre-softmax activations, a tensor of size [batch_size, 1] end_points: a dictionary from components of the network to their activation. Raises: ValueError: If the input image shape is not 4-dimensional, if the spatial dimensions aren't defined at graph construction time, if the spatial dimensions aren't square, or if the spatial dimensions aren't a power of two. """ normalizer_fn = slim.batch_norm normalizer_fn_args = { 'is_training': is_training, 'zero_debias_moving_mean': True, 'fused': fused_batch_norm, } _validate_image_inputs(inputs) inp_shape = inputs.get_shape().as_list()[1] end_points = {} with tf.compat.v1.variable_scope(scope, values=[inputs], reuse=reuse) as scope: with slim.arg_scope([normalizer_fn], **normalizer_fn_args): with slim.arg_scope([slim.conv2d], stride=2, kernel_size=4, activation_fn=tf.nn.leaky_relu): net = inputs for i in xrange(int(log(inp_shape, 2))): scope = 'conv%i' % (i + 1) current_depth = depth * 2**i normalizer_fn_ = None if i == 0 else normalizer_fn net = slim.conv2d( net, current_depth, normalizer_fn=normalizer_fn_, scope=scope) end_points[scope] = net logits = slim.conv2d(net, 1, kernel_size=1, stride=1, padding='VALID', normalizer_fn=None, activation_fn=None) logits = tf.reshape(logits, [-1, 1]) end_points['logits'] = logits return logits, end_points # TODO(joelshor): Use fused batch norm by default. Investigate why some GAN # setups need the gradient of gradient FusedBatchNormGrad. def generator(inputs, depth=64, final_size=32, num_outputs=3, is_training=True, reuse=None, scope='Generator', fused_batch_norm=False): """Generator network for DCGAN. Construct generator network from inputs to the final endpoint. Args: inputs: A tensor with any size N. [batch_size, N] depth: Number of channels in last deconvolution layer. final_size: The shape of the final output. num_outputs: Number of output features. For images, this is the number of channels. is_training: whether is training or not. reuse: Whether or not the network has its variables should be reused. scope must be given to be reused. scope: Optional variable_scope. fused_batch_norm: If `True`, use a faster, fused implementation of batch norm. Returns: logits: the pre-softmax activations, a tensor of size [batch_size, 32, 32, channels] end_points: a dictionary from components of the network to their activation. Raises: ValueError: If `inputs` is not 2-dimensional. ValueError: If `final_size` isn't a power of 2 or is less than 8. """ normalizer_fn = slim.batch_norm normalizer_fn_args = { 'is_training': is_training, 'zero_debias_moving_mean': True, 'fused': fused_batch_norm, } inputs.get_shape().assert_has_rank(2) if log(final_size, 2) != int(log(final_size, 2)): raise ValueError('`final_size` (%i) must be a power of 2.' % final_size) if final_size < 8: raise ValueError('`final_size` (%i) must be greater than 8.' % final_size) end_points = {} num_layers = int(log(final_size, 2)) - 1 with tf.compat.v1.variable_scope(scope, values=[inputs], reuse=reuse) as scope: with slim.arg_scope([normalizer_fn], **normalizer_fn_args): with slim.arg_scope([slim.conv2d_transpose], normalizer_fn=normalizer_fn, stride=2, kernel_size=4): net = tf.expand_dims(tf.expand_dims(inputs, 1), 1) # First upscaling is different because it takes the input vector. current_depth = depth * 2 ** (num_layers - 1) scope = 'deconv1' net = slim.conv2d_transpose( net, current_depth, stride=1, padding='VALID', scope=scope) end_points[scope] = net for i in xrange(2, num_layers): scope = 'deconv%i' % (i) current_depth = depth * 2 ** (num_layers - i) net = slim.conv2d_transpose(net, current_depth, scope=scope) end_points[scope] = net # Last layer has different normalizer and activation. scope = 'deconv%i' % (num_layers) net = slim.conv2d_transpose( net, depth, normalizer_fn=None, activation_fn=None, scope=scope) end_points[scope] = net # Convert to proper channels. scope = 'logits' logits = slim.conv2d( net, num_outputs, normalizer_fn=None, activation_fn=None, kernel_size=1, stride=1, padding='VALID', scope=scope) end_points[scope] = logits logits.get_shape().assert_has_rank(4) logits.get_shape().assert_is_compatible_with( [None, final_size, final_size, num_outputs]) return logits, end_points
[ "tensorflow.reshape", "tensorflow.compat.v1.variable_scope", "tensorflow.expand_dims" ]
slim/nets/dcgan.py
[(33, 'math.log', 'log', (['width', '(2)'], {}), False, 'from math import log\n'), (82, 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['scope'], {'values': '[inputs]', 'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (149, 'math.log', 'log', (['final_size', '(2)'], {}), False, 'from math import log\n'), (156, 'tensorflow.compat.v1.variable_scope', 'tf.compat.v1.variable_scope', (['scope'], {'values': '[inputs]', 'reuse': 'reuse'}), True, 'import tensorflow as tf\n'), (33, 'math.log', 'log', (['width', '(2)'], {}), False, 'from math import log\n'), (83, 'tf_slim.arg_scope', 'slim.arg_scope', (['[normalizer_fn]'], {}), True, 'import tf_slim as slim\n'), (149, 'math.log', 'log', (['final_size', '(2)'], {}), False, 'from math import log\n'), (155, 'math.log', 'log', (['final_size', '(2)'], {}), False, 'from math import log\n'), (157, 'tf_slim.arg_scope', 'slim.arg_scope', (['[normalizer_fn]'], {}), True, 'import tf_slim as slim\n'), (84, 'tf_slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d]'], {'stride': '(2)', 'kernel_size': '(4)', 'activation_fn': 'tf.nn.leaky_relu'}), True, 'import tf_slim as slim\n'), (97, 'tf_slim.conv2d', 'slim.conv2d', (['net', '(1)'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '"""VALID"""', 'normalizer_fn': 'None', 'activation_fn': 'None'}), True, 'import tf_slim as slim\n'), (99, 'tensorflow.reshape', 'tf.reshape', (['logits', '[-1, 1]'], {}), True, 'import tensorflow as tf\n'), (158, 'tf_slim.arg_scope', 'slim.arg_scope', (['[slim.conv2d_transpose]'], {'normalizer_fn': 'normalizer_fn', 'stride': '(2)', 'kernel_size': '(4)'}), True, 'import tf_slim as slim\n'), (167, 'tf_slim.conv2d_transpose', 'slim.conv2d_transpose', (['net', 'current_depth'], {'stride': '(1)', 'padding': '"""VALID"""', 'scope': 'scope'}), True, 'import tf_slim as slim\n'), (179, 'tf_slim.conv2d_transpose', 'slim.conv2d_transpose', (['net', 'depth'], {'normalizer_fn': 'None', 'activation_fn': 'None', 'scope': 'scope'}), True, 'import tf_slim as slim\n'), (185, 'tf_slim.conv2d', 'slim.conv2d', (['net', 'num_outputs'], {'normalizer_fn': 'None', 'activation_fn': 'None', 'kernel_size': '(1)', 'stride': '(1)', 'padding': '"""VALID"""', 'scope': 'scope'}), True, 'import tf_slim as slim\n'), (93, 'tf_slim.conv2d', 'slim.conv2d', (['net', 'current_depth'], {'normalizer_fn': 'normalizer_fn_', 'scope': 'scope'}), True, 'import tf_slim as slim\n'), (162, 'tensorflow.expand_dims', 'tf.expand_dims', (['inputs', '(1)'], {}), True, 'import tensorflow as tf\n'), (174, 'tf_slim.conv2d_transpose', 'slim.conv2d_transpose', (['net', 'current_depth'], {'scope': 'scope'}), True, 'import tf_slim as slim\n'), (89, 'math.log', 'log', (['inp_shape', '(2)'], {}), False, 'from math import log\n')]
dhirajpatnaik16297/text-gan-tensorflow
fb9897ee55e8d674a16c6041a2c1fb67abad131b
""" TensorFlow Layers Convenience functions but Input and Output should be tensors. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow.contrib import seq2seq _phase = tf.Variable(False, name='phase', trainable=False, collections=[tf.GraphKeys.LOCAL_VARIABLES]) _phase_train = _phase.assign(True) _phase_infer = _phase.assign(False) # TODO: move to ops def _rank(x): return len(x.get_shape()) def _apply_dropout_mask(tensor_shape, keep_prob=1.0, normalize=True): random_tensor = keep_prob + tf.random_uniform(tensor_shape, dtype=tf.float32) binary_mask = tf.floor(random_tensor) if normalize: binary_mask = tf.reciprocal(keep_prob) * binary_mask return binary_mask def _global_keep_prob(keep_prob): keep_prob = tf.convert_to_tensor(keep_prob, dtype=tf.float32) keep_prob = tf.cond(_phase, lambda: keep_prob, lambda: keep_prob * 0.0 + 1.0) return keep_prob def layer(func): class Layer(object): def __init__(self, *args, **kwargs): self.func = func self.args = args self.kwargs = kwargs self.name = self.kwargs.get("name", self.func.__name__) self._template = tf.make_template(self.name, self.func, create_scope_now_=True) self._unique_name = self._template.variable_scope.name.split("/")[-1] self._summary_added = False def __call__(self, x): out = self.template(x, *self.args, **self.kwargs) self._layer_logging(x, out) self._add_summary() return out def __rrshift__(self, other): """ >> """ return self.__call__(other) def _layer_logging(self, other, out): tf.logging.info(" {} {} {} -> {}".format( self.unique_name, "shape", str(other.get_shape()), str(out.get_shape()))) def _add_summary(self): if not self.kwargs.get("summary"): return None if self.summary_added: return None for var in self.get_variables_in_scope(): # TODO: different summary types tf.summary.scalar(var.name, tf.reduce_mean(var)) self._summary_added = True def get_variables_in_scope(self): assert self.template._variables_created, "Variables not yet created or undefined." variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.variable_scope_name) return variables @property def template(self): return self._template @property def unique_name(self): return self._unique_name @property def variable_scope_name(self): return self.template._variable_scope._name @property def summary_added(self): return self._summary_added return Layer @layer def identity_layer(tensor, **opts): out = tf.identity(tensor) return out @layer def embedding_layer(tensor, vocab_size=None, embedding_dim=None, embedding_matrix=None, **opts): if embedding_matrix is None: initializer = tf.contrib.layers.xavier_initializer(uniform=True) embedding_matrix = tf.get_variable("embedding_matrix", initializer=initializer(shape=(vocab_size, embedding_dim))) out = tf.nn.embedding_lookup(embedding_matrix, tensor) return out @layer def recurrent_layer(tensor, cell=None, hidden_dims=128, sequence_length=None, decoder_fn=None, activation=tf.nn.tanh, initializer=tf.orthogonal_initializer(), initial_state=None, keep_prob=1.0, return_final_state=False, return_next_cell_input=True, **opts): if cell is None: cell = tf.contrib.rnn.BasicRNNCell(hidden_dims, activation=activation) # cell = tf.contrib.rnn.LSTMCell(hidden_dims, activation=activation) if keep_prob < 1.0: keep_prob = _global_keep_prob(keep_prob) cell = tf.contrib.rnn.DropoutWrapper(cell, keep_prob, keep_prob) if opts.get("name"): tf.add_to_collection(opts.get("name"), cell) if decoder_fn is None: outputs, final_state = tf.nn.dynamic_rnn(cell, tensor, sequence_length=sequence_length, initial_state=initial_state, dtype=tf.float32) final_context_state = None else: # TODO: turn off sequence_length? outputs, final_state, final_context_state = seq2seq.dynamic_rnn_decoder( cell, decoder_fn, inputs=None, sequence_length=sequence_length) if return_final_state: return final_state else: return outputs @layer def reshape_layer(tensor, shape, **opts): out = tf.reshape(tensor, shape=shape) return out @layer def dense_layer(tensor, hidden_dims, weight=None, bias=None, **opts): original_tensor_shape = tf.shape(tensor) in_dim = int(tensor.get_shape()[-1]) rank = _rank(tensor) if rank > 2: # -- time distributed dense tensor = tf.reshape(tensor, shape=(-1, in_dim)) name = opts.get("name", "") if weight is None: initializer = tf.contrib.layers.xavier_initializer(uniform=True) weight = tf.get_variable("{}_dense_W".format(name), initializer=initializer(shape=(in_dim, hidden_dims))) if bias is None: bias = tf.get_variable("{}_dense_b".format(name), initializer=tf.zeros(shape=hidden_dims)) out = tf.add(tf.matmul(tensor, weight), bias) if rank > 2: # reshape back to time dimension out = tf.reshape(out, shape=original_tensor_shape) return out @layer def dropout_layer(tensor, keep_prob=1.0, **opts): keep_prob = _global_keep_prob(keep_prob) out = tf.nn.dropout(tensor, keep_prob=keep_prob) return out # TODO: should i normalize? @layer def word_dropout_layer(tensor, keep_prob=1.0, **opts): keep_prob = _global_keep_prob(keep_prob) rank = _rank(tensor) assert rank == 3, "Use embedding lookup layer" binary_mask = _apply_dropout_mask(tf.shape(tensor)[:2], keep_prob, normalize=False) binary_mask = tf.expand_dims(binary_mask, axis=-1) # proper broadcasting to zero out entire word vectors out = tensor * binary_mask return out @layer def relu_layer(tensor): out = tf.nn.relu(tensor) return out @layer def tanh_layer(tensor): out = tf.nn.tanh(tensor) return out @layer def softmax_layer(tensor, softmax_func=None, **opts): if softmax_func is None: softmax_func = tf.nn.softmax out = softmax_func(tensor) return out @layer def cross_entropy_layer(tensor, target, **opts): if _rank(tensor) > 1: target = tf.reshape(target, shape=(-1, )) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=tensor, labels=target) mask = tf.cast(tf.not_equal(target, tf.zeros_like(target)), dtype=tf.float32) out = cross_entropy * mask return out @layer def sigmoid_cross_entropy_layer(tensor, target, **opts): out = tf.nn.sigmoid_cross_entropy_with_logits(logits=tensor, labels=target) return out @layer def mean_loss_by_example_layer(tensor, sequence_length, **opts): loss = tf.div( tf.reduce_sum(tensor, axis=1), tf.cast(sequence_length, dtype=tf.float32) ) out = tf.reduce_mean(loss) tf.summary.scalar('cost', out) return out @layer def conv1d_layer(tensor, dilation_rate=1, **opts): raise NotImplementedError @layer def residual_layer(tensor, **opts): raise NotImplementedError @layer def highway_layer(tensor, **opts): raise NotImplementedError if __name__ == "__main__": import numpy as np batch_size = 10 sequence_length = 5 vocab_size = 100 embedding_dim = 32 word_ids = np.random.randint(0, vocab_size, batch_size * sequence_length).reshape(batch_size, sequence_length) tensor = tf.constant(word_ids) # print(word_ids >> identity_layer() >> embedding_layer(vocab_size, embedding_dim)) print(tensor >> identity_layer() >> embedding_layer(vocab_size, embedding_dim))
[ "tensorflow.convert_to_tensor", "tensorflow.cond", "tensorflow.nn.dynamic_rnn", "tensorflow.zeros", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.orthogonal_initializer", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.contrib.rnn.BasicRNNCell", "tensorflow.make_template", "tensorflow.summary.scalar", "numpy.random.randint", "tensorflow.Variable", "tensorflow.get_collection", "tensorflow.floor", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.nn.dropout", "tensorflow.reciprocal", "tensorflow.matmul", "tensorflow.shape", "tensorflow.identity", "tensorflow.nn.tanh", "tensorflow.zeros_like", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.nn.embedding_lookup", "tensorflow.nn.relu", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.contrib.rnn.DropoutWrapper", "tensorflow.reshape", "tensorflow.contrib.seq2seq.dynamic_rnn_decoder", "tensorflow.expand_dims", "tensorflow.random_uniform" ]
layers.py
[(13, 'tensorflow.Variable', 'tf.Variable', (['(False)'], {'name': '"""phase"""', 'trainable': '(False)', 'collections': '[tf.GraphKeys.LOCAL_VARIABLES]'}), True, 'import tensorflow as tf\n'), (25, 'tensorflow.floor', 'tf.floor', (['random_tensor'], {}), True, 'import tensorflow as tf\n'), (32, 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['keep_prob'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (33, 'tensorflow.cond', 'tf.cond', (['_phase', '(lambda : keep_prob)', '(lambda : keep_prob * 0.0 + 1.0)'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.identity', 'tf.identity', (['tensor'], {}), True, 'import tensorflow as tf\n'), (110, 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embedding_matrix', 'tensor'], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.orthogonal_initializer', 'tf.orthogonal_initializer', ([], {}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.reshape', 'tf.reshape', (['tensor'], {'shape': 'shape'}), True, 'import tensorflow as tf\n'), (153, 'tensorflow.shape', 'tf.shape', (['tensor'], {}), True, 'import tensorflow as tf\n'), (181, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['tensor'], {'keep_prob': 'keep_prob'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.expand_dims', 'tf.expand_dims', (['binary_mask'], {'axis': '(-1)'}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.nn.relu', 'tf.nn.relu', (['tensor'], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.nn.tanh', 'tf.nn.tanh', (['tensor'], {}), True, 'import tensorflow as tf\n'), (226, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'tensor', 'labels': 'target'}), True, 'import tensorflow as tf\n'), (234, 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'logits': 'tensor', 'labels': 'target'}), True, 'import tensorflow as tf\n'), (244, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), True, 'import tensorflow as tf\n'), (245, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""cost"""', 'out'], {}), True, 'import tensorflow as tf\n'), (273, 'tensorflow.constant', 'tf.constant', (['word_ids'], {}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.random_uniform', 'tf.random_uniform', (['tensor_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {'uniform': '(True)'}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.contrib.rnn.BasicRNNCell', 'tf.contrib.rnn.BasicRNNCell', (['hidden_dims'], {'activation': 'activation'}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.contrib.rnn.DropoutWrapper', 'tf.contrib.rnn.DropoutWrapper', (['cell', 'keep_prob', 'keep_prob'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['cell', 'tensor'], {'sequence_length': 'sequence_length', 'initial_state': 'initial_state', 'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.contrib.seq2seq.dynamic_rnn_decoder', 'seq2seq.dynamic_rnn_decoder', (['cell', 'decoder_fn'], {'inputs': 'None', 'sequence_length': 'sequence_length'}), False, 'from tensorflow.contrib import seq2seq\n'), (159, 'tensorflow.reshape', 'tf.reshape', (['tensor'], {'shape': '(-1, in_dim)'}), True, 'import tensorflow as tf\n'), (164, 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {'uniform': '(True)'}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.matmul', 'tf.matmul', (['tensor', 'weight'], {}), True, 'import tensorflow as tf\n'), (173, 'tensorflow.reshape', 'tf.reshape', (['out'], {'shape': 'original_tensor_shape'}), True, 'import tensorflow as tf\n'), (224, 'tensorflow.reshape', 'tf.reshape', (['target'], {'shape': '(-1,)'}), True, 'import tensorflow as tf\n'), (241, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['tensor'], {'axis': '(1)'}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.cast', 'tf.cast', (['sequence_length'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.reciprocal', 'tf.reciprocal', (['keep_prob'], {}), True, 'import tensorflow as tf\n'), (46, 'tensorflow.make_template', 'tf.make_template', (['self.name', 'self.func'], {'create_scope_now_': '(True)'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {'scope': 'self.variable_scope_name'}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.shape', 'tf.shape', (['tensor'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.zeros_like', 'tf.zeros_like', (['target'], {}), True, 'import tensorflow as tf\n'), (272, 'numpy.random.randint', 'np.random.randint', (['(0)', 'vocab_size', '(batch_size * sequence_length)'], {}), True, 'import numpy as np\n'), (167, 'tensorflow.zeros', 'tf.zeros', ([], {'shape': 'hidden_dims'}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['var'], {}), True, 'import tensorflow as tf\n')]
aglitoiu/pennylane
fd99be754d55bbb919aadbbbdff70e40fbe3bcbf
# Copyright 2018-2021 Xanadu Quantum Technologies 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. """This module contains the classes and functions for integrating QNodes with the Keras Layer API.""" import inspect from collections.abc import Iterable from typing import Optional try: import tensorflow as tf from tensorflow.keras.layers import Layer CORRECT_TF_VERSION = int(tf.__version__.split(".")[0]) > 1 except ImportError: # The following allows this module to be imported even if TensorFlow is not installed. Users # will instead see an ImportError when instantiating the KerasLayer. from abc import ABC Layer = ABC CORRECT_TF_VERSION = False class KerasLayer(Layer): """Converts a :func:`~.QNode` to a Keras `Layer <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer>`__. The result can be used within the Keras `Sequential <https://www.tensorflow.org/api_docs/python/tf/keras/Sequential>`__ or `Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>`__ classes for creating quantum and hybrid models. Args: qnode (qml.QNode): the PennyLane QNode to be converted into a Keras Layer_ weight_shapes (dict[str, tuple]): a dictionary mapping from all weights used in the QNode to their corresponding shapes output_dim (int): the output dimension of the QNode weight_specs (dict[str, dict]): An optional dictionary for users to provide additional specifications for weights used in the QNode, such as the method of parameter initialization. This specification is provided as a dictionary with keys given by the arguments of the `add_weight() <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_weight>`__. method and values being the corresponding specification. **kwargs: additional keyword arguments passed to the Layer_ base class **Example** First let's define the QNode that we want to convert into a Keras Layer_: .. code-block:: python n_qubits = 2 dev = qml.device("default.qubit", wires=n_qubits) @qml.qnode(dev) def qnode(inputs, weights_0, weight_1): qml.RX(inputs[0], wires=0) qml.RX(inputs[1], wires=1) qml.Rot(*weights_0, wires=0) qml.RY(weight_1, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) The signature of the QNode **must** contain an ``inputs`` named argument for input data, with all other arguments to be treated as internal weights. We can then convert to a Keras Layer_ with: >>> weight_shapes = {"weights_0": 3, "weight_1": 1} >>> qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=2) The internal weights of the QNode are automatically initialized within the :class:`~.KerasLayer` and must have their shapes specified in a ``weight_shapes`` dictionary. It is then easy to combine with other neural network layers from the `tensorflow.keras.layers <https://www.tensorflow.org/api_docs/python/tf/keras/layers>`__ module and create a hybrid: >>> clayer = tf.keras.layers.Dense(2) >>> model = tf.keras.models.Sequential([qlayer, clayer]) .. UsageDetails:: **QNode signature** The QNode must have a signature that satisfies the following conditions: - Contain an ``inputs`` named argument for input data. - All other arguments must accept an array or tensor and are treated as internal weights of the QNode. - All other arguments must have no default value. - The ``inputs`` argument is permitted to have a default value provided the gradient with respect to ``inputs`` is not required. - There cannot be a variable number of positional or keyword arguments, e.g., no ``*args`` or ``**kwargs`` present in the signature. **Initializing weights** The optional ``weight_specs`` argument of :class:`~.KerasLayer` allows for a more fine-grained specification of the QNode weights, such as the method of initialization and any regularization or constraints. For example, the initialization method of the ``weights`` argument in the example above could be specified by: .. code-block:: weight_specs = {"weights": {"initializer": "random_uniform"}} The values of ``weight_specs`` are dictionaries with keys given by arguments of the Keras `add_weight() <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_weight>`__ method. For the ``"initializer"`` argument, one can specify a string such as ``"random_uniform"`` or an instance of an `Initializer <https://www.tensorflow.org/api_docs/python/tf/keras/initializers>`__ class, such as `tf.keras.initializers.RandomUniform <https://www.tensorflow.org/api_docs/python/tf/random_uniform_initializer>`__. If ``weight_specs`` is not specified, weights will be added using the Keras default initialization and without any regularization or constraints. **Additional example** The code block below shows how a circuit composed of templates from the :doc:`/code/qml_templates` module can be combined with classical `Dense <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense>`__ layers to learn the two-dimensional `moons <https://scikit-learn.org/stable/modules/generated/sklearn .datasets.make_moons.html>`__ dataset. .. code-block:: python import pennylane as qml import tensorflow as tf import sklearn.datasets n_qubits = 2 dev = qml.device("default.qubit", wires=n_qubits) @qml.qnode(dev) def qnode(inputs, weights): qml.templates.AngleEmbedding(inputs, wires=range(n_qubits)) qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits)) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) weight_shapes = {"weights": (3, n_qubits, 3)} qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=2) clayer1 = tf.keras.layers.Dense(2) clayer2 = tf.keras.layers.Dense(2, activation="softmax") model = tf.keras.models.Sequential([clayer1, qlayer, clayer2]) data = sklearn.datasets.make_moons() X = tf.constant(data[0]) Y = tf.one_hot(data[1], depth=2) opt = tf.keras.optimizers.SGD(learning_rate=0.5) model.compile(opt, loss='mae') The model can be trained using: >>> model.fit(X, Y, epochs=8, batch_size=5) Train on 100 samples Epoch 1/8 100/100 [==============================] - 9s 90ms/sample - loss: 0.3524 Epoch 2/8 100/100 [==============================] - 9s 87ms/sample - loss: 0.2441 Epoch 3/8 100/100 [==============================] - 9s 87ms/sample - loss: 0.1908 Epoch 4/8 100/100 [==============================] - 9s 87ms/sample - loss: 0.1832 Epoch 5/8 100/100 [==============================] - 9s 88ms/sample - loss: 0.1596 Epoch 6/8 100/100 [==============================] - 9s 87ms/sample - loss: 0.1637 Epoch 7/8 100/100 [==============================] - 9s 86ms/sample - loss: 0.1613 Epoch 8/8 100/100 [==============================] - 9s 87ms/sample - loss: 0.1474 **Returning a state** If your QNode returns the state of the quantum circuit using :func:`~.state` or :func:`~.density_matrix`, you must immediately follow your quantum Keras Layer with a layer that casts to reals. For example, you could use `tf.keras.layers.Lambda <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda>`__ with the function ``lambda x: tf.abs(x)``. This casting is required because TensorFlow's Keras layers require a real input and are differentiated with respect to real parameters. .. _Layer: https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer """ def __init__( self, qnode, weight_shapes: dict, output_dim, weight_specs: Optional[dict] = None, **kwargs ): if not CORRECT_TF_VERSION: raise ImportError( "KerasLayer requires TensorFlow version 2 or above. The latest " "version of TensorFlow can be installed using:\n" "pip install tensorflow --upgrade\nAlternatively, visit " "https://www.tensorflow.org/install for detailed instructions." ) self.weight_shapes = { weight: (tuple(size) if isinstance(size, Iterable) else (size,) if size > 1 else ()) for weight, size in weight_shapes.items() } self._signature_validation(qnode, weight_shapes) self.qnode = qnode dtype = tf.float32 if tf.keras.backend.floatx() == tf.float32 else tf.float64 if self.qnode.diff_method != "backprop": self.qnode.to_tf(dtype=dtype) # Allows output_dim to be specified as an int or as a tuple, e.g, 5, (5,), (5, 2), [5, 2] # Note: Single digit values will be considered an int and multiple as a tuple, e.g [5,] or (5,) # are passed as integer 5 and [5, 2] will be passes as tuple (5, 2) if isinstance(output_dim, Iterable) and len(output_dim) > 1: self.output_dim = tuple(output_dim) else: self.output_dim = output_dim[0] if isinstance(output_dim, Iterable) else output_dim self.weight_specs = weight_specs if weight_specs is not None else {} self.qnode_weights = {} super().__init__(dynamic=True, **kwargs) def _signature_validation(self, qnode, weight_shapes): sig = inspect.signature(qnode.func).parameters if self.input_arg not in sig: raise TypeError( "QNode must include an argument with name {} for inputting data".format( self.input_arg ) ) if self.input_arg in set(weight_shapes.keys()): raise ValueError( "{} argument should not have its dimension specified in " "weight_shapes".format(self.input_arg) ) param_kinds = [p.kind for p in sig.values()] if inspect.Parameter.VAR_POSITIONAL in param_kinds: raise TypeError("Cannot have a variable number of positional arguments") if inspect.Parameter.VAR_KEYWORD not in param_kinds: if set(weight_shapes.keys()) | {self.input_arg} != set(sig.keys()): raise ValueError("Must specify a shape for every non-input parameter in the QNode") def build(self, input_shape): """Initializes the QNode weights. Args: input_shape (tuple or tf.TensorShape): shape of input data """ for weight, size in self.weight_shapes.items(): spec = self.weight_specs.get(weight, {}) self.qnode_weights[weight] = self.add_weight(name=weight, shape=size, **spec) super().build(input_shape) def call(self, inputs): """Evaluates the QNode on input data using the initialized weights. Args: inputs (tensor): data to be processed Returns: tensor: output data """ if len(tf.shape(inputs)) > 1: # If the input size is not 1-dimensional, unstack the input along its first dimension, # recursively call the forward pass on each of the yielded tensors, and then stack the # outputs back into the correct shape reconstructor = [] for x in tf.unstack(inputs): reconstructor.append(self.call(x)) return tf.stack(reconstructor) return self._evaluate_qnode(inputs) def _evaluate_qnode(self, x): """Evaluates a QNode for a single input datapoint. Args: x (tensor): the datapoint Returns: tensor: output datapoint """ kwargs = {**{self.input_arg: x}, **{k: 1.0 * w for k, w in self.qnode_weights.items()}} return self.qnode(**kwargs) def compute_output_shape(self, input_shape): """Computes the output shape after passing data of shape ``input_shape`` through the QNode. Args: input_shape (tuple or tf.TensorShape): shape of input data Returns: tf.TensorShape: shape of output data """ return tf.TensorShape([input_shape[0]]).concatenate(self.output_dim) def __str__(self): detail = "<Quantum Keras Layer: func={}>" return detail.format(self.qnode.func.__name__) __repr__ = __str__ _input_arg = "inputs" @property def input_arg(self): """Name of the argument to be used as the input to the Keras `Layer <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer>`__. Set to ``"inputs"``.""" return self._input_arg
[ "tensorflow.keras.backend.floatx", "tensorflow.__version__.split", "tensorflow.TensorShape", "tensorflow.unstack", "tensorflow.shape", "tensorflow.stack" ]
pennylane/qnn/keras.py
[(236, 'inspect.signature', 'inspect.signature', (['qnode.func'], {}), False, 'import inspect\n'), (286, 'tensorflow.unstack', 'tf.unstack', (['inputs'], {}), True, 'import tensorflow as tf\n'), (288, 'tensorflow.stack', 'tf.stack', (['reconstructor'], {}), True, 'import tensorflow as tf\n'), (24, 'tensorflow.__version__.split', 'tf.__version__.split', (['"""."""'], {}), True, 'import tensorflow as tf\n'), (216, 'tensorflow.keras.backend.floatx', 'tf.keras.backend.floatx', ([], {}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.shape', 'tf.shape', (['inputs'], {}), True, 'import tensorflow as tf\n'), (314, 'tensorflow.TensorShape', 'tf.TensorShape', (['[input_shape[0]]'], {}), True, 'import tensorflow as tf\n')]
shengfuintel/tensorflow
5828e285209ff8c3d1bef2e4bd7c55ca611080d5
# 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. # ============================================================================== """Benchmarks for Cudnn RNN models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from tensorflow.contrib.rnn.python.ops import core_rnn from tensorflow.contrib.rnn.python.ops import lstm_ops from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import init_ops from tensorflow.python.ops import rnn_cell from tensorflow.python.ops import variables from tensorflow.python.platform import test class CudnnRNNBenchmark(test.Benchmark): """Benchmarks Cudnn LSTM and other related models. """ def _GetTestConfig(self): return { "large": { "num_layers": 4, "num_units": 1024, "seq_length": 40, "batch_size": 64, }, "medium": { "num_layers": 4, "num_units": 512, "seq_length": 30, "batch_size": 64, }, "small": { "num_layers": 4, "num_units": 128, "seq_length": 20, "batch_size": 64, }, } def _GetConfigDesc(self, config): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] return "y%d_u%d_b%d_q%d" % (num_layers, num_units, batch_size, seq_length) def _BenchmarkOp(self, op, desc): burn_in_steps = 10 benchmark_steps = 40 with session.Session() as sess: sess.run(variables.global_variables_initializer()) for i in xrange(burn_in_steps + benchmark_steps): if i == burn_in_steps: start_time = time.time() sess.run(op) total_time = time.time() - start_time step_time = total_time / benchmark_steps print("%s takes %.4f sec/step" % (desc, step_time)) self.report_benchmark( name=desc, iters=benchmark_steps, wall_time=total_time) def benchmarkCudnnLSTMTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): config = test_configs[config_name] num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): model = cudnn_rnn_ops.CudnnLSTM(num_layers, num_units, num_units) params_size_t = model.params_size() input_data = variables.Variable( array_ops.ones([seq_length, batch_size, num_units])) input_h = variables.Variable( array_ops.ones([num_layers, batch_size, num_units])) input_c = variables.Variable( array_ops.ones([num_layers, batch_size, num_units])) params = variables.Variable( array_ops.ones([params_size_t]), validate_shape=False) output, output_h, output_c = model( is_training=True, input_data=input_data, input_h=input_h, input_c=input_c, params=params) all_grads = gradients_impl.gradients( [output, output_h, output_c], [params, input_data, input_h, input_c]) training_op = control_flow_ops.group(*all_grads) self._BenchmarkOp(training_op, "cudnn_lstm %s %s" % (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): inputs = seq_length * [ array_ops.zeros([batch_size, num_units], dtypes.float32) ] initializer = init_ops.random_uniform_initializer(-0.01, 0.01, seed=127) cell = rnn_cell.LSTMCell( num_units=num_units, initializer=initializer, state_is_tuple=True) multi_cell = rnn_cell.MultiRNNCell( [cell() for _ in range(num_layers)]) outputs, final_state = core_rnn.static_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm %s %s" % (config_name, self._GetConfigDesc(config))) def benchmarkTfRNNLSTMBlockCellTraining(self): test_configs = self._GetTestConfig() for config_name, config in test_configs.items(): num_layers = config["num_layers"] num_units = config["num_units"] batch_size = config["batch_size"] seq_length = config["seq_length"] with ops.Graph().as_default(), ops.device("/device:GPU:0"): inputs = seq_length * [ array_ops.zeros([batch_size, num_units], dtypes.float32) ] cell = lambda: lstm_ops.LSTMBlockCell(num_units=num_units) # pylint: disable=cell-var-from-loop multi_cell = rnn_cell.MultiRNNCell( [cell() for _ in range(num_layers)]) outputs, final_state = core_rnn.static_rnn( multi_cell, inputs, dtype=dtypes.float32) trainable_variables = ops.get_collection( ops.GraphKeys.TRAINABLE_VARIABLES) gradients = gradients_impl.gradients([outputs, final_state], trainable_variables) training_op = control_flow_ops.group(*gradients) self._BenchmarkOp(training_op, "tf_rnn_lstm_block_cell %s %s" % (config_name, self._GetConfigDesc(config))) if __name__ == "__main__": test.main()
[ "tensorflow.python.framework.ops.device", "tensorflow.python.ops.rnn_cell.LSTMCell", "tensorflow.contrib.rnn.python.ops.lstm_ops.LSTMBlockCell", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.contrib.rnn.python.ops.core_rnn.static_rnn", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.init_ops.random_uniform_initializer", "tensorflow.python.client.session.Session", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.array_ops.ones", "tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops.CudnnLSTM", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.ops.gradients_impl.gradients" ]
tensorflow/contrib/cudnn_rnn/python/kernel_tests/cudnn_rnn_ops_benchmark.py
[(176, 'tensorflow.python.platform.test.main', 'test.main', ([], {}), False, 'from tensorflow.python.platform import test\n'), (75, 'tensorflow.python.client.session.Session', 'session.Session', ([], {}), False, 'from tensorflow.python.client import session\n'), (76, 'tensorflow.python.ops.variables.global_variables_initializer', 'variables.global_variables_initializer', ([], {}), False, 'from tensorflow.python.ops import variables\n'), (81, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (96, 'tensorflow.python.framework.ops.device', 'ops.device', (['"""/device:GPU:0"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (97, 'tensorflow.contrib.cudnn_rnn.python.ops.cudnn_rnn_ops.CudnnLSTM', 'cudnn_rnn_ops.CudnnLSTM', (['num_layers', 'num_units', 'num_units'], {}), False, 'from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops\n'), (113, 'tensorflow.python.ops.gradients_impl.gradients', 'gradients_impl.gradients', (['[output, output_h, output_c]', '[params, input_data, input_h, input_c]'], {}), False, 'from tensorflow.python.ops import gradients_impl\n'), (116, 'tensorflow.python.ops.control_flow_ops.group', 'control_flow_ops.group', (['*all_grads'], {}), False, 'from tensorflow.python.ops import control_flow_ops\n'), (128, 'tensorflow.python.framework.ops.device', 'ops.device', (['"""/device:GPU:0"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (132, 'tensorflow.python.ops.init_ops.random_uniform_initializer', 'init_ops.random_uniform_initializer', (['(-0.01)', '(0.01)'], {'seed': '(127)'}), False, 'from tensorflow.python.ops import init_ops\n'), (134, 'tensorflow.python.ops.rnn_cell.LSTMCell', 'rnn_cell.LSTMCell', ([], {'num_units': 'num_units', 'initializer': 'initializer', 'state_is_tuple': '(True)'}), False, 'from tensorflow.python.ops import rnn_cell\n'), (138, 'tensorflow.contrib.rnn.python.ops.core_rnn.static_rnn', 'core_rnn.static_rnn', (['multi_cell', 'inputs'], {'dtype': 'dtypes.float32'}), False, 'from tensorflow.contrib.rnn.python.ops import core_rnn\n'), (140, 'tensorflow.python.framework.ops.get_collection', 'ops.get_collection', (['ops.GraphKeys.TRAINABLE_VARIABLES'], {}), False, 'from tensorflow.python.framework import ops\n'), (142, 'tensorflow.python.ops.gradients_impl.gradients', 'gradients_impl.gradients', (['[outputs, final_state]', 'trainable_variables'], {}), False, 'from tensorflow.python.ops import gradients_impl\n'), (144, 'tensorflow.python.ops.control_flow_ops.group', 'control_flow_ops.group', (['*gradients'], {}), False, 'from tensorflow.python.ops import control_flow_ops\n'), (156, 'tensorflow.python.framework.ops.device', 'ops.device', (['"""/device:GPU:0"""'], {}), False, 'from tensorflow.python.framework import ops\n'), (164, 'tensorflow.contrib.rnn.python.ops.core_rnn.static_rnn', 'core_rnn.static_rnn', (['multi_cell', 'inputs'], {'dtype': 'dtypes.float32'}), False, 'from tensorflow.contrib.rnn.python.ops import core_rnn\n'), (166, 'tensorflow.python.framework.ops.get_collection', 'ops.get_collection', (['ops.GraphKeys.TRAINABLE_VARIABLES'], {}), False, 'from tensorflow.python.framework import ops\n'), (168, 'tensorflow.python.ops.gradients_impl.gradients', 'gradients_impl.gradients', (['[outputs, final_state]', 'trainable_variables'], {}), False, 'from tensorflow.python.ops import gradients_impl\n'), (170, 'tensorflow.python.ops.control_flow_ops.group', 'control_flow_ops.group', (['*gradients'], {}), False, 'from tensorflow.python.ops import control_flow_ops\n'), (79, 'time.time', 'time.time', ([], {}), False, 'import time\n'), (100, 'tensorflow.python.ops.array_ops.ones', 'array_ops.ones', (['[seq_length, batch_size, num_units]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (102, 'tensorflow.python.ops.array_ops.ones', 'array_ops.ones', (['[num_layers, batch_size, num_units]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (104, 'tensorflow.python.ops.array_ops.ones', 'array_ops.ones', (['[num_layers, batch_size, num_units]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (106, 'tensorflow.python.ops.array_ops.ones', 'array_ops.ones', (['[params_size_t]'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (160, 'tensorflow.contrib.rnn.python.ops.lstm_ops.LSTMBlockCell', 'lstm_ops.LSTMBlockCell', ([], {'num_units': 'num_units'}), False, 'from tensorflow.contrib.rnn.python.ops import lstm_ops\n'), (96, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (128, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (130, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[batch_size, num_units]', 'dtypes.float32'], {}), False, 'from tensorflow.python.ops import array_ops\n'), (156, 'tensorflow.python.framework.ops.Graph', 'ops.Graph', ([], {}), False, 'from tensorflow.python.framework import ops\n'), (158, 'tensorflow.python.ops.array_ops.zeros', 'array_ops.zeros', (['[batch_size, num_units]', 'dtypes.float32'], {}), False, 'from tensorflow.python.ops import array_ops\n')]
FeynmanDNA/singa-auto
e96982adc689335a323a5a32d03b23942e01d09f
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 tensorflow.python.client import device_lib from tensorflow.python.training import moving_averages import os import math import json import random from datetime import datetime from collections import namedtuple import numpy as np import argparse from singa_auto.constants import ModelDependency from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, \ FixedKnob, ArchKnob, KnobValue, PolicyKnob from singa_auto.model.dev import test_model_class _Model = namedtuple('_Model', ['train_dataset_init_op', 'pred_dataset_init_op', 'train_op', 'summary_op', 'pred_probs', 'pred_corrects', 'train_corrects', 'step', 'vars_assign_op', 'ph', 'var_phs']) _ModelMemo = namedtuple('_ModelMemo', ['train_params', 'use_dynamic_arch', 'knobs', 'model', 'graph', 'sess', 'saver', 'monitored_values']) _ModelPlaceholder = namedtuple('_ModelPlaceholder', ['train_images', 'train_classes', 'pred_images', 'pred_classes', 'normal_arch', 'reduction_arch']) OPS = [0, 1, 2, 3, 4] CELL_NUM_BLOCKS = 5 # No. of blocks in a cell TF_COLLECTION_MONITORED = 'MONITORED' class TfEnas(BaseModel): ''' Implements the child model of cell-based "Efficient Neural Architecture Search via Parameter Sharing" (ENAS) for IMAGE_CLASSIFICATION, configured for *architecture tuning with ENAS* . Original paper: https://arxiv.org/abs/1802.03268 Implementation is with credits to https://github.com/melodyguan/enas ''' # Memoise across trials to speed up training _datasets_memo = {} # { <dataset_path> -> <dataset> } _model_memo = None # of class `_MemoModel` _loaded_tf_vars_id_memo = None # ID of TF vars loaded _loaded_train_dataset_memo = None # Train dataset <dataset_path> loaded into the graph _loaded_pred_dataset_memo = None # Predict dataset <dataset_path> loaded into the graph @staticmethod def get_knob_config(): return { 'cell_archs': TfEnas.make_arch_knob(), 'max_image_size': FixedKnob(32), 'epochs': FixedKnob(310), # Total no. of epochs during a standard train 'batch_size': FixedKnob(128), 'learning_rate': FixedKnob(0.05), 'initial_block_ch': FixedKnob(36), 'stem_ch_mul': FixedKnob(3), 'reg_decay': FixedKnob(4e-4), 'dropout_keep_prob': FixedKnob(0.8), 'opt_momentum': FixedKnob(0.9), 'use_sgdr': FixedKnob(True), 'sgdr_alpha': FixedKnob(0.002), 'sgdr_decay_epochs': FixedKnob(10), 'sgdr_t_mul': FixedKnob(2), 'num_layers': FixedKnob(15), 'aux_loss_mul': FixedKnob(0.4), 'drop_path_keep_prob': FixedKnob(0.6), 'drop_path_decay_epochs': FixedKnob(310), 'cutout_size': FixedKnob(0), 'grad_clip_norm': FixedKnob(0), 'use_aux_head': FixedKnob(False), 'share_params': PolicyKnob('SHARE_PARAMS'), # Affects whether model constructed is a scaled-down version with fewer layers 'downscale': PolicyKnob('DOWNSCALE'), 'enas_num_layers': FixedKnob(6), 'enas_initial_block_ch': FixedKnob(20), 'enas_dropout_keep_prob': FixedKnob(0.9), 'enas_sgdr_alpha': FixedKnob(0.01), 'enas_drop_path_keep_prob': FixedKnob(0.9), 'enas_drop_path_decay_epochs': FixedKnob(150), # Affects whether training is shortened using a reduced no. of epochs 'quick_train': PolicyKnob('EARLY_STOP'), 'enas_epochs': FixedKnob(1), # Affects whether training is skipped 'skip_train': PolicyKnob('SKIP_TRAIN'), # Affects whether evaluation is done on only a batch of the validation dataset 'quick_eval': PolicyKnob('QUICK_EVAL') } @staticmethod def make_arch_knob(): # Make knob values for ops # Operations across blocks are considered identical for the purposes of architecture search # E.g. operation "conv3x3" with op code 0 has the same meaning across blocks ops = [KnobValue(i) for i in OPS] # Build list of knobs for ``cell_archs`` cell_archs = [] for c in range(2): # 1 for normal cell, 1 for reduction cell # Make knob values for inputs # Input indices across blocks in the same cell are considered identical for the purposes of architecture search # E.g. input from block 0 with index 2 has the same meaning across blocks in the same cell input_knob_values = [KnobValue(i) for i in range(CELL_NUM_BLOCKS + 2)] # For each block for b in range(CELL_NUM_BLOCKS): # Input 1 & input 2 can only can take input from prev prev cell, prev cell, or one of prev blocks inputs = input_knob_values[:(b + 2)] cell_archs.extend([inputs, ops, inputs, ops]) return ArchKnob(cell_archs) def __init__(self, **knobs): super().__init__(**knobs) self._model = None self._graph = None self._sess = None self._saver = None self._monitored_values = None self._train_params = None self._knobs = self._process_knobs(knobs) def train(self, dataset_path, shared_params=None): knobs = self._knobs # Load dataset (images, classes, self._train_params) = self._maybe_load_dataset(dataset_path, **knobs) # Build model (self._model, self._graph, self._sess, self._saver, self._monitored_values) = self._maybe_build_model(**knobs) if not knobs['skip_train']: # Maybe load shared variables, then train model with self._graph.as_default(): if knobs['share_params'] and shared_params is not None: self._maybe_load_tf_vars(shared_params) self._train_model(images, classes, dataset_path=dataset_path, **knobs) def evaluate(self, dataset_path): (images, classes, _) = self._maybe_load_dataset(dataset_path, train_params=self._train_params, **self._knobs) with self._graph.as_default(): acc = self._evaluate_model(images, classes, dataset_path=dataset_path, **self._knobs) return acc def predict(self, queries): image_size = self._train_params['image_size'] images = utils.dataset.transform_images(queries, image_size=image_size, mode='RGB') with self._graph.as_default(): probs = self._predict_with_model(images, **self._knobs) return probs.tolist() def dump_parameters(self): params = {} # Add train params params['train_params'] = json.dumps(self._train_params) # Add model parameters with self._graph.as_default(): tf_vars = tf.global_variables() values = self._sess.run(tf_vars) for (tf_var, value) in zip(tf_vars, values): params[tf_var.name] = np.asarray(value) # Add an ID for diffing vars_id = np.random.rand() params['vars_id'] = vars_id # Memo ID TfEnas._loaded_tf_vars_id_memo = vars_id return params def load_parameters(self, params): # Add train params self._train_params = json.loads(params['train_params']) # Build model (self._model, self._graph, self._sess, self._saver, self._monitored_values) = self._maybe_build_model(**self._knobs) # Add model parameters with self._graph.as_default(): self._maybe_load_tf_vars(params) @staticmethod def teardown(): if TfEnas._model_memo is not None: TfEnas._model_memo.sess.close() TfEnas._model_memo = None #################################### # Memoized methods #################################### def _maybe_load_dataset(self, dataset_path, train_params=None, **knobs): # Try to use memoized dataset if dataset_path in TfEnas._datasets_memo: dataset = TfEnas._datasets_memo[dataset_path] return dataset dataset = self._load_dataset(dataset_path, train_params, **knobs) TfEnas._datasets_memo[dataset_path] = dataset return dataset def _maybe_load_tf_vars(self, params): # If same TF vars has been loaded in previous trial, don't bother loading again vars_id = params['vars_id'] if TfEnas._loaded_tf_vars_id_memo == vars_id: return # Skipping loading of vars self._load_tf_vars(params) # Memo ID TfEnas._loaded_tf_vars_id_memo = vars_id def _maybe_feed_dataset_to_model(self, images, classes=None, dataset_path=None, is_train=False): memo = TfEnas._loaded_train_dataset_memo if is_train else TfEnas._loaded_pred_dataset_memo if dataset_path is None or memo != dataset_path: # To load new dataset self._feed_dataset_to_model(images, classes, is_train=is_train) if is_train: TfEnas._loaded_train_dataset_memo = dataset_path else: TfEnas._loaded_pred_dataset_memo = dataset_path else: # Otherwise, dataset has previously been loaded, so do nothing pass def _maybe_build_model(self, **knobs): train_params = self._train_params use_dynamic_arch = knobs['downscale'] # Use memoized model when possible if not self._if_model_same(TfEnas._model_memo, knobs, train_params, use_dynamic_arch): (model, graph, sess, saver, monitored_values) = \ self._build_model(**knobs) TfEnas._model_memo = _ModelMemo( train_params, use_dynamic_arch, knobs, model, graph, sess, saver, monitored_values ) model_memo = TfEnas._model_memo return (model_memo.model, model_memo.graph, model_memo.sess, model_memo.saver, model_memo.monitored_values) def _if_model_same(self, model_memo, knobs, train_params, use_dynamic_arch): if model_memo is None: return False # Must have the same `train_params` & `use_dynamic_arch` if (train_params, use_dynamic_arch) != (model_memo.train_params, model_memo.use_dynamic_arch): return False # Knobs must be the same except for some that doesn't affect model construction # If arch is dynamic, knobs can differ by `cell_archs` ignored_knobs = ['skip_train', 'quick_train', 'quick_eval', 'downscale', 'epochs'] if use_dynamic_arch: ignored_knobs.append('cell_archs') for (name, value) in knobs.items(): if name not in ignored_knobs and value != model_memo.knobs.get(name): utils.logger.log('Detected that knob "{}" is different!'.format(name)) return False return True #################################### # Private methods #################################### def _process_knobs(self, knobs): # Activates dynamic architecture with fewer layers if knobs['downscale']: knobs = { **knobs, 'num_layers': knobs['enas_num_layers'], 'initial_block_ch': knobs['enas_initial_block_ch'], 'dropout_keep_prob': knobs['enas_dropout_keep_prob'], 'sgdr_alpha': knobs['enas_sgdr_alpha'], 'drop_path_keep_prob': knobs['enas_drop_path_keep_prob'], 'drop_path_decay_epochs': knobs['enas_drop_path_decay_epochs'], } # Activates mode where training finishes with fewer epochs if knobs['quick_train']: knobs = { **knobs, 'epochs': knobs['enas_epochs'] } return knobs def _load_dataset(self, dataset_path, train_params=None, **knobs): max_image_size = knobs['max_image_size'] image_size = train_params['image_size'] if train_params is not None else max_image_size utils.logger.log('Loading dataset...') dataset = utils.dataset.load_dataset_of_image_files(dataset_path, max_image_size=image_size, mode='RGB') (images, classes) = zip(*[(image, image_class) for (image, image_class) in dataset]) norm_mean = np.mean(images, axis=(0, 1, 2)).tolist() norm_std = np.std(images, axis=(0, 1, 2)).tolist() train_params = { 'N': len(images), 'image_size': dataset.image_size, 'K': dataset.classes, 'norm_mean': norm_mean, 'norm_std': norm_std } return (images, classes, train_params) def _build_model(self, **knobs): use_dynamic_arch = knobs['downscale'] # Create graph graph = tf.Graph() with graph.as_default(): # Define input placeholders to graph ph = self._make_placeholders() # Use fixed archs if specified, otherwise use placeholders' (normal_arch, reduction_arch) = self._get_fixed_cell_archs(**knobs) normal_arch = normal_arch if not use_dynamic_arch else ph.normal_arch reduction_arch = reduction_arch if not use_dynamic_arch else ph.reduction_arch # Initialize steps variable step = self._make_var('step', (), dtype=tf.int32, trainable=False, initializer=tf.initializers.constant(0)) # For train dataset, preprocess & do inference utils.logger.log('Building model for training...') (train_X, train_classes, train_dataset_init_op) = \ self._preprocess(ph.train_images, ph.train_classes, is_train=True, **knobs) (train_logits, train_aux_logits_list) = self._forward(train_X, step, normal_arch, reduction_arch, is_train=True, **knobs) # Compute training loss total_loss = self._compute_loss(train_logits, train_aux_logits_list, train_classes, **knobs) # Optimize training loss train_op = self._optimize(total_loss, step, **knobs) # Compute predictions (_, train_corrects) = self._compute_predictions(train_logits, train_classes) # For pred dataset, preprocess & do inference utils.logger.log('Building model for predictions...') (pred_X, pred_classes, pred_dataset_init_op) = \ self._preprocess(ph.pred_images, ph.pred_classes, is_train=False, **knobs) (pred_logits, _) = self._forward(pred_X, step, normal_arch, reduction_arch, is_train=False, **knobs) # Compute predictions (pred_probs, pred_corrects) = self._compute_predictions(pred_logits, pred_classes) # Count model parameters model_params_count = self._count_model_parameters() # Monitor values (summary_op, monitored_values) = self._add_monitoring_of_values() # Add saver tf_vars = tf.global_variables() saver = tf.train.Saver(tf_vars) # Allow loading of model variables (var_phs, vars_assign_op) = self._add_vars_assign_op(tf_vars) model = _Model(train_dataset_init_op, pred_dataset_init_op, train_op, summary_op, pred_probs, pred_corrects, train_corrects, step, vars_assign_op, ph, var_phs) # Make session sess = self._make_session() self._init_session(sess, model) return (model, graph, sess, saver, monitored_values) def _load_tf_vars(self, params): m = self._model utils.logger.log('Loading TF vars...') tf_vars = tf.global_variables() values = self._sess.run(tf_vars) # Get current values for vars # Build feed dict for op for loading vars # For each var, use current value of param in session if not in params var_feeddict = { m.var_phs[tf_var.name]: params[tf_var.name] if tf_var.name in params else values[i] for (i, tf_var) in enumerate(tf_vars) } self._sess.run(m.vars_assign_op, feed_dict=var_feeddict) def _make_placeholders(self): w = self._train_params['image_size'] h = self._train_params['image_size'] in_ch = 3 # Num channels of input images train_images_ph = tf.placeholder(tf.int32, name='train_images_ph', shape=(None, w, h, in_ch)) # Train images pred_images_ph = tf.placeholder(tf.int32, name='pred_images_ph', shape=(None, w, h, in_ch)) # Predict images train_classes_ph = tf.placeholder(tf.int32, name='train_classes_ph', shape=(None,)) # Train classes pred_classes_ph = tf.placeholder(tf.int32, name='pred_classes_ph', shape=(None,)) # Predict classes normal_arch_ph = tf.placeholder(tf.int32, name='normal_arch_ph', shape=(CELL_NUM_BLOCKS, 4)) reduction_arch_ph = tf.placeholder(tf.int32, name='reduction_arch_ph', shape=(CELL_NUM_BLOCKS, 4)) return _ModelPlaceholder(train_images_ph, train_classes_ph, pred_images_ph, pred_classes_ph, normal_arch_ph, reduction_arch_ph) def _forward(self, X, step, normal_arch, reduction_arch, is_train=False, **knobs): K = self._train_params['K'] # No. of classes in_ch = 3 # Num channels of input images w = self._train_params['image_size'] # Initial input width h = self._train_params['image_size'] # Initial input height dropout_keep_prob = knobs['dropout_keep_prob'] use_dynamic_arch = knobs['downscale'] L = knobs['num_layers'] # Total number of layers initial_block_ch = knobs['initial_block_ch'] # Initial no. of channels for operations in block stem_ch_mul = knobs['stem_ch_mul'] # No. of channels for stem convolution as multiple of initial block channels use_aux_head = knobs['use_aux_head'] # Whether to use auxiliary head stem_ch = initial_block_ch * stem_ch_mul # Layers with reduction cells (otherwise, normal cells) reduction_layers = [L // 3, L // 3 * 2 + 1] # Layers with auxiliary heads # Aux heads speed up training of good feature repsentations early in the network # Add aux heads only if enabled and downsampling width can happen 3 times aux_head_layers = [] if use_aux_head and w % (2 << 3) == 0: aux_head_layers.append(reduction_layers[-1] + 1) with tf.variable_scope('model', reuse=(not is_train)): # "Stem" convolution layer (layer -1) with tf.variable_scope('layer_stem'): X = self._do_conv(X, w, h, in_ch, stem_ch, filter_size=3, no_relu=True, is_train=is_train) # 3x3 convolution stem = (X, w, h, stem_ch) # Core layers of cells block_ch = initial_block_ch aux_logits_list = [] # Stores list of logits from aux heads layers = [stem, stem] # Stores previous layers. layers[i] = (<layer (i + 1)>, <width>, <height>, <channels>) for l in range(L + 2): utils.logger.log('Building layer {}...'.format(l)) with tf.variable_scope('layer_{}'.format(l)): layers_ratio = (l + 1) / (L + 2) drop_path_keep_prob = self._get_drop_path_keep_prob(layers_ratio, step, is_train, **knobs) # Either add a reduction cell or normal cell if l in reduction_layers: block_ch *= 2 w >>= 1 h >>= 1 with tf.variable_scope('reduction_cell'): if use_dynamic_arch: self._add_dynamic_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train) else: self._add_static_cell(reduction_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train, is_reduction=True) else: with tf.variable_scope('normal_cell'): if use_dynamic_arch: self._add_dynamic_cell(normal_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train) else: self._add_static_cell(normal_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train) # Maybe add auxiliary heads if l in aux_head_layers: with tf.variable_scope('aux_head'): aux_logits = self._add_aux_head(*layers[-1], K, is_train) aux_logits_list.append(aux_logits) # Global average pooling (X, w, h, ch) = layers[-1] X = self._add_global_avg_pool(X, w, h, ch) # Add dropout if training if is_train: X = tf.nn.dropout(X, dropout_keep_prob) # Compute logits from X with tf.variable_scope('fully_connected'): logits = self._add_fully_connected(X, (ch,), K) return (logits, aux_logits_list) def _optimize(self, loss, step, **knobs): opt_momentum = knobs['opt_momentum'] # Momentum optimizer momentum grad_clip_norm = knobs['grad_clip_norm'] # L2 norm to clip gradients by # Compute learning rate, gradients tf_trainable_vars = tf.trainable_variables() lr = self._get_learning_rate(step, **knobs) grads = tf.gradients(loss, tf_trainable_vars) self._mark_for_monitoring('lr', lr) # Clip gradients if grad_clip_norm > 0: grads = [tf.clip_by_norm(x, grad_clip_norm) for x in grads] # Init optimizer opt = tf.train.MomentumOptimizer(lr, opt_momentum, use_locking=True, use_nesterov=True) train_op = opt.apply_gradients(zip(grads, tf_trainable_vars), global_step=step) return train_op def _preprocess(self, images, classes, is_train=False, **knobs): batch_size = knobs['batch_size'] cutout_size = knobs['cutout_size'] image_norm_mean = self._train_params['norm_mean'] image_norm_std = self._train_params['norm_std'] w = self._train_params['image_size'] h = self._train_params['image_size'] in_ch = 3 # Num channels of input images def _prepare(images, classes): # Bulk preprocessing of images images = tf.cast(images, tf.float32) images = (images - image_norm_mean) / image_norm_std # Normalize images = images / 255 # Convert to [0, 1] return (images, classes) # Prepare train dataset def _preprocess_train(image, clazz): # Do random crop + horizontal flip for each train image image = tf.pad(image, [[4, 4], [4, 4], [0, 0]]) image = tf.image.random_crop(image, (w, h, in_ch)) image = tf.image.random_flip_left_right(image) if cutout_size > 0: image = self._do_cutout(image, w, h, cutout_size) return (image, clazz) (images, classes) = _prepare(images, classes) dataset = tf.data.Dataset.from_tensor_slices((images, classes)).repeat() if is_train: dataset = dataset.apply(tf.data.experimental.map_and_batch(map_func=_preprocess_train, batch_size=batch_size)) else: dataset = dataset.batch(batch_size) dataset_itr = dataset.make_initializable_iterator() (images_batch, classes_batch) = dataset_itr.get_next() dataset_init_op = dataset_itr.initializer return (images_batch, classes_batch, dataset_init_op) def _get_drop_path_keep_prob(self, layers_ratio, step, is_train=False, **knobs): batch_size = knobs['batch_size'] drop_path_keep_prob = knobs['drop_path_keep_prob'] # Base keep prob for drop path drop_path_decay_epochs = knobs['drop_path_decay_epochs'] N = self._train_params['N'] # Only drop path during training keep_prob = tf.constant(1, dtype=tf.float32) if is_train: # Decrease keep prob deeper into network keep_prob = 1 - layers_ratio * (1 - drop_path_keep_prob) # Decrease keep prob with increasing steps steps_per_epoch = math.ceil(N / batch_size) steps_ratio = tf.minimum(((step + 1) / steps_per_epoch) / drop_path_decay_epochs, 1) keep_prob = 1 - steps_ratio * (1 - keep_prob) keep_prob = tf.cast(keep_prob, tf.float32) # Monitor last layer's keep prob if layers_ratio == 1: self._mark_for_monitoring('drop_path_keep_prob', keep_prob) return keep_prob def _get_learning_rate(self, step, **knobs): N = self._train_params['N'] batch_size = knobs['batch_size'] lr = knobs['learning_rate'] # Learning rate use_sgdr = knobs['use_sgdr'] sgdr_decay_epochs = knobs['sgdr_decay_epochs'] sgdr_alpha = knobs['sgdr_alpha'] sgdr_t_mul = knobs['sgdr_t_mul'] # Compute epoch from step steps_per_epoch = math.ceil(N / batch_size) epoch = step // steps_per_epoch if use_sgdr is True: # Apply Stoachastic Gradient Descent with Warm Restarts (SGDR) lr = tf.train.cosine_decay_restarts(lr, epoch, sgdr_decay_epochs, t_mul=sgdr_t_mul, alpha=sgdr_alpha) return lr def _init_session(self, sess, model): w = self._train_params['image_size'] h = self._train_params['image_size'] in_ch = 3 m = model # Do initialization of all variables sess.run(tf.global_variables_initializer()) # Load datasets with defaults sess.run([m.train_dataset_init_op, m.pred_dataset_init_op], feed_dict={ m.ph.train_images: np.zeros((1, w, h, in_ch)), m.ph.train_classes: np.zeros((1,)), m.ph.pred_images: np.zeros((1, w, h, in_ch)), m.ph.pred_classes: np.zeros((1,)) }) def _make_session(self): config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True sess = tf.Session(config=config) return sess def _feed_dataset_to_model(self, images, classes=None, is_train=False): m = self._model utils.logger.log('Feeding dataset to model...') # Mock classes if required classes = classes or [0 for _ in range(len(images))] if is_train: self._sess.run(m.train_dataset_init_op, feed_dict={ m.ph.train_images: images, m.ph.train_classes: classes }) else: self._sess.run(m.pred_dataset_init_op, feed_dict={ m.ph.pred_images: images, m.ph.pred_classes: classes, }) def _train_model(self, images, classes, dataset_path=None, **knobs): num_epochs = knobs['epochs'] m = self._model N = len(images) self._maybe_feed_dataset_to_model(images, classes, dataset_path=dataset_path, is_train=True) # Define plots # TODO: Investigate bug where plots for acc and loss are always 1 and 0 utils.logger.define_plot('Train accuracy over Epochs', ['mean_acc'], 'epoch') for (name, _) in self._monitored_values.items(): utils.logger.define_plot('"{}" Over Time'.format(name), [name]) log_condition = TimedRepeatCondition() for epoch in range(num_epochs): utils.logger.log('Running epoch {}...'.format(epoch)) corrects = [] itr = self._get_dataset_iterator(N,[m.train_op, m.train_corrects, m.step, m.pred_probs, *self._monitored_values.values()], **knobs) for (_, batch_corrects, batch_steps, batch_probs, *values) in itr: # To track mean batch accuracy corrects.extend(batch_corrects) # Periodically, log monitored values if log_condition.check(): utils.logger.log(step=batch_steps, **{ name: v for (name, v) in zip(self._monitored_values.keys(), values) }) # Log mean batch accuracy and epoch mean_acc = np.mean(corrects) utils.logger.log(epoch=epoch, mean_acc=mean_acc) def _evaluate_model(self, images, classes, dataset_path=None, **knobs): batch_size = self._knobs['batch_size'] m = self._model N = batch_size if self._knobs['quick_eval'] else len(images) self._maybe_feed_dataset_to_model(images, classes, dataset_path=dataset_path) corrects = [] itr = self._get_dataset_iterator(N, [m.pred_corrects], **knobs) for (batch_corrects,) in itr: corrects.extend(batch_corrects) acc = np.mean(corrects) return acc def _predict_with_model(self, images, **knobs): m = self._model N = len(images) self._maybe_feed_dataset_to_model(images) all_probs = [] itr = self._get_dataset_iterator(N, [m.pred_probs], **knobs) for (batch_probs,) in itr: all_probs.extend(batch_probs) all_probs = np.asarray(all_probs) return all_probs def _get_dataset_iterator(self, N, run_ops, **knobs): batch_size = knobs['batch_size'] steps_per_epoch = math.ceil(N / batch_size) m = self._model (normal_arch, reduction_arch) = self._get_fixed_cell_archs(**knobs) feed_dict = { m.ph.normal_arch: normal_arch, m.ph.reduction_arch: reduction_arch } for itr_step in range(steps_per_epoch): results = self._sess.run(run_ops, feed_dict=feed_dict) yield results def _get_fixed_cell_archs(self, **knobs): cell_archs = knobs['cell_archs'] b = CELL_NUM_BLOCKS normal_arch = [cell_archs[(4 * i):(4 * i + 4)] for i in range(b)] reduction_arch = [cell_archs[(4 * i):(4 * i + 4)] for i in range(b, b + b)] return (normal_arch, reduction_arch) def _add_aux_head(self, X, in_w, in_h, in_ch, K, is_train): pool_ksize = 5 pool_stride = 3 conv_ch = 128 global_conv_ch = 768 w = in_w h = in_h ch = in_ch # Pool with tf.variable_scope('pool'): X = tf.nn.relu(X) X = tf.nn.avg_pool(X, ksize=(1, pool_ksize, pool_ksize, 1), strides=(1, pool_stride, pool_stride, 1), padding='VALID') w //= pool_stride h //= pool_stride # Conv 1x1 with tf.variable_scope('conv_0'): X = self._do_conv(X, w, h, ch, conv_ch, filter_size=1, no_reg=True, is_train=is_train) ch = conv_ch # Global conv with tf.variable_scope('conv_1'): X = self._do_conv(X, w, h, ch, global_conv_ch, filter_size=w, no_reg=True, is_train=is_train) ch = global_conv_ch # Global pooling X = self._add_global_avg_pool(X, w, h, ch) # Fully connected with tf.variable_scope('fully_connected'): aux_logits = self._add_fully_connected(X, (ch,), K, no_reg=True) return aux_logits def _compute_predictions(self, logits, classes): probs = tf.nn.softmax(logits) preds = tf.argmax(logits, axis=1, output_type=tf.int32) corrects = tf.equal(preds, classes) return (probs, corrects) def _compute_loss(self, logits, aux_logits_list, classes, **knobs): reg_decay = knobs['reg_decay'] aux_loss_mul = knobs['aux_loss_mul'] # Multiplier for auxiliary loss # Compute sparse softmax cross entropy loss from logits & labels log_probs = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=classes) loss = tf.reduce_mean(log_probs) self._mark_for_monitoring('loss', loss) # Add regularization loss reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) reg_loss = reg_decay * tf.add_n(reg_losses) self._mark_for_monitoring('reg_loss', reg_loss) # Add loss from auxiliary logits aux_loss = tf.constant(0, dtype=tf.float32) for aux_logits in aux_logits_list: log_probs = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=aux_logits, labels=classes) aux_loss += aux_loss_mul * tf.reduce_mean(log_probs) total_loss = loss + reg_loss + aux_loss return total_loss def _add_global_avg_pool(self, X, in_w, in_h, in_ch): X = tf.nn.relu(X) X = tf.reduce_mean(X, (1, 2)) X = tf.reshape(X, (-1, in_ch)) # Sanity shape check return X def _count_model_parameters(self): tf_trainable_vars = tf.trainable_variables() num_params = 0 # utils.logger.log('Model parameters:') for var in tf_trainable_vars: # utils.logger.log(str(var)) num_params += np.prod([dim.value for dim in var.get_shape()]) utils.logger.log('Model has {} parameters'.format(num_params)) return num_params def _add_vars_assign_op(self, vars): var_phs = { tf_var.name: tf.placeholder(dtype=tf_var.dtype, shape=tf_var.shape) for tf_var in vars } vars_assign_op = tf.group([ tf.assign(tf_var, ph) for (tf_var, ph) in zip(vars, var_phs.values()) ], name='vars_assign_op') return (var_phs, vars_assign_op) #################################### # Cells #################################### def _add_dynamic_cell(self, cell_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train=False): b = CELL_NUM_BLOCKS # Downsample inputs to have same dimensions as blocks with tf.variable_scope('layer_-1_calibrate'): layers[-1] = (self._calibrate(*layers[-1], w, h, block_ch, is_train=is_train), w, h, block_ch) with tf.variable_scope('layer_-2_calibrate'): layers[-2] = (self._calibrate(*layers[-2], w, h, block_ch, is_train=is_train), w, h, block_ch) cell_inputs = [layers[-2][0] if len(layers) > 1 else layers[-1][0], layers[-1][0]] blocks = [] for bi in range(b): with tf.variable_scope('block_{}'.format(bi)): idx1 = cell_arch[bi][0] op1 = cell_arch[bi][1] idx2 = cell_arch[bi][2] op2 = cell_arch[bi][3] with tf.variable_scope('X1'): X1 = self._add_op_dynamic(cell_inputs, blocks, idx1, op1, w, h, block_ch, is_train=is_train) X1 = self._add_drop_path(X1, drop_path_keep_prob) with tf.variable_scope('X2'): X2 = self._add_op_dynamic(cell_inputs, blocks, idx2, op2, w, h, block_ch, is_train=is_train) X2 = self._add_drop_path(X2, drop_path_keep_prob) X = tf.add_n([X1, X2]) blocks.append(X) (X, comb_ch) = self._combine_cell_blocks_dynamic(cell_inputs, blocks, cell_arch, w, h, block_ch, is_train) X = tf.reshape(X, (-1, w, h, comb_ch)) # Sanity shape check layers.append((X, w, h, comb_ch)) def _add_static_cell(self, cell_arch, layers, w, h, block_ch, drop_path_keep_prob, is_train=False, is_reduction=False): b = CELL_NUM_BLOCKS # Calibrate inputs as necessary to last input layer's dimensions and add them to hidden states cell_inputs = [layers[-2] if len(layers) > 1 else layers[-1], layers[-1]] (_, w_inp_last, h_inp_last, _) = cell_inputs[-1] for (i, (inp, w_inp, h_inp, ch_inp)) in enumerate(cell_inputs): with tf.variable_scope('input_{}_calibrate'.format(i)): inp = self._calibrate(inp, w_inp, h_inp, ch_inp, w_inp_last, h_inp_last, block_ch, is_train=is_train) # Apply conv 1x1 on last input if i == len(cell_inputs) - 1: with tf.variable_scope('input_{}_conv'.format(i)): inp = self._do_conv(inp, w_inp_last, h_inp_last, block_ch, block_ch, is_train=is_train) cell_inputs[i] = inp blocks = [] for bi in range(b): with tf.variable_scope('block_{}'.format(bi)): idx1 = cell_arch[bi][0] op1 = cell_arch[bi][1] idx2 = cell_arch[bi][2] op2 = cell_arch[bi][3] with tf.variable_scope('X1'): X1 = self._add_op(cell_inputs, blocks, idx1, op1, w, h, block_ch, is_reduction=is_reduction, is_train=is_train) X1 = self._add_drop_path(X1, drop_path_keep_prob) with tf.variable_scope('X2'): X2 = self._add_op(cell_inputs, blocks, idx2, op2, w, h, block_ch, is_reduction=is_reduction, is_train=is_train) X2 = self._add_drop_path(X2, drop_path_keep_prob) X = tf.add_n([X1, X2]) blocks.append(X) (X, comb_ch) = self._combine_cell_blocks(cell_inputs, blocks, cell_arch, w, h, block_ch, is_train) X = tf.reshape(X, (-1, w, h, comb_ch)) # Sanity shape check layers.append((X, w, h, comb_ch)) def _combine_cell_blocks(self, cell_inputs, blocks, cell_arch, w, h, block_ch, is_train=False): # Count usage of inputs input_use_counts = [0] * len(cell_inputs + blocks) for (idx1, _, idx2, _) in cell_arch: input_use_counts[idx1] += 1 input_use_counts[idx2] += 1 # Concat only unused blocks with tf.variable_scope('combine'): block_use_counts = input_use_counts[len(cell_inputs):] out_blocks = [block for (block, use_count) in zip(blocks, block_use_counts) if use_count == 0] comb_ch = len(out_blocks) * block_ch X = tf.concat(out_blocks, axis=3) return (X, comb_ch) def _combine_cell_blocks_dynamic(self, cell_inputs, blocks, cell_arch, w, h, block_ch, is_train=False): ni = len(cell_inputs + blocks) b = len(blocks) # Count usage of inputs block_uses = [] for bi in range(b): idx1 = cell_arch[bi][0] idx2 = cell_arch[bi][2] block_use = tf.one_hot(idx1, ni, dtype=tf.int32) + tf.one_hot(idx2, ni, dtype=tf.int32) block_uses.append(block_use) block_uses = tf.add_n(block_uses) unused_indices = tf.reshape(tf.cast(tf.where(tf.equal(block_uses, 0)), tf.int32), [-1]) num_out_blocks = tf.size(unused_indices) # Select only unused blocks with tf.variable_scope('select'): stacked_blocks = tf.stack(cell_inputs + blocks) out_blocks = tf.gather(stacked_blocks, unused_indices, axis=0) out_blocks = tf.transpose(out_blocks, (1, 2, 3, 0, 4)) # Combine to constant channels with tf.variable_scope('combine'): W = self._make_var('W', (ni, block_ch * block_ch)) W = tf.gather(W, unused_indices, axis=0) W = tf.reshape(W, (1, 1, num_out_blocks * block_ch, block_ch)) X = tf.reshape(out_blocks, (-1, w, h, num_out_blocks * block_ch)) X = tf.nn.relu(X) X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME') X = self._add_batch_norm(X, block_ch, is_train=is_train) return (X, block_ch) def _add_op(self, cell_inputs, blocks, input_idx, op, w, h, ch, is_reduction=False, is_train=False): ni = len(cell_inputs + blocks) inputs = cell_inputs + blocks op_map = self._get_op_map() # Just build output for select operation X = inputs[input_idx] op_no = OPS[op] op_method = op_map[op_no] # If we were to account for reduction if is_reduction and input_idx < len(cell_inputs): X = op_method(X, input_idx, ni, w << 1, h << 1, ch, is_reduction=True, is_dynamic=False, is_train=is_train) else: X = op_method(X, input_idx, ni, w, h, ch, is_reduction=False, is_dynamic=False, is_train=is_train) return X def _add_op_dynamic(self, cell_inputs, blocks, input_idx, op, w, h, ch, is_train=False): ni = len(cell_inputs + blocks) inputs = tf.stack(cell_inputs + blocks, axis=0) op_map = self._get_op_map() # Build output for each available operation X = inputs[input_idx] op_Xs = [] for op_no in OPS: op_method = op_map[op_no] op_X = op_method(X, input_idx, ni, w, h, ch, is_reduction=False, is_dynamic=True, is_train=is_train) op_Xs.append(op_X) # Stack operation outputs and index by op op_Xs = tf.stack(op_Xs) X = op_Xs[op] return X #################################### # Block Ops #################################### def _get_op_map(self): # List of all possible operations and their associated numbers return { 0: self._add_separable_conv_3x3_op, 1: self._add_separable_conv_5x5_op, 2: self._add_avg_pool_3x3_op, 3: self._add_max_pool_3x3_op, 4: self._add_identity_op, 5: self._add_separable_conv_7x7_op } def _add_avg_pool_3x3_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): filter_size = 3 stride = 2 if is_reduction else 1 with tf.variable_scope('avg_pool_3x3_op'): X = tf.nn.avg_pool(X, ksize=(1, filter_size, filter_size, 1), strides=[1, stride, stride, 1], padding='SAME') X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_identity_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): stride = 2 if is_reduction else 1 with tf.variable_scope('identity_op'): # If stride > 1, calibrate, else, just return itself if stride > 1: X = self._calibrate(X, w, h, ch, w // stride, h // stride, ch, is_train=is_train) X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_max_pool_3x3_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): filter_size = 3 stride = 2 if is_reduction else 1 with tf.variable_scope('max_pool_3x3_op'): X = tf.nn.max_pool(X, ksize=(1, filter_size, filter_size, 1), strides=[1, stride, stride, 1], padding='SAME') X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_separable_conv_3x3_op(self, *args, **kwargs): return self._add_separable_conv_op(*args, **kwargs, filter_size=3) def _add_separable_conv_5x5_op(self, *args, **kwargs): return self._add_separable_conv_op(*args, **kwargs, filter_size=5) def _add_separable_conv_7x7_op(self, *args, **kwargs): return self._add_separable_conv_op(*args, **kwargs, filter_size=7) def _add_separable_conv_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train, filter_size=3): num_stacks = 2 stride = 2 if is_reduction else 1 with tf.variable_scope('separable_conv_{}x{}_op'.format(filter_size, filter_size)): # For each stack of separable convolution (default of 2) for stack_no in range(num_stacks): # Only have > 1 stride for first stack stack_stride = stride if stack_no == 0 else 1 with tf.variable_scope('stack_{}'.format(stack_no)): W_d = None W_p = None batch_norm_offset = None batch_norm_scale = None if is_dynamic: # Select weights corresponding to input index W_d = self._make_var('W_d', (ni, filter_size, filter_size, ch, 1)) W_d = W_d[input_idx] W_p = self._make_var('W_p', (ni, 1, 1, ch, ch)) W_p = W_p[input_idx] batch_norm_offset = self._make_var('batch_norm_offset', (ni, ch), init_constant=0) batch_norm_offset = batch_norm_offset[input_idx] batch_norm_scale = self._make_var('batch_norm_scale', (ni, ch), init_constant=1) batch_norm_scale = batch_norm_scale[input_idx] X = self._do_separable_conv(X, w, h, ch, filter_size=filter_size, stride=stack_stride, W_d=W_d, W_p=W_p, no_batch_norm=True) X = self._add_batch_norm(X, ch, offset=batch_norm_offset, scale=batch_norm_scale, no_moving_average=is_dynamic, is_train=is_train) X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X #################################### # Utils #################################### def _do_cutout(self, image, im_width, im_height, cutout_size): mask = tf.ones([cutout_size, cutout_size], dtype=tf.int32) start_x = tf.random.uniform(shape=(1,), minval=0, maxval=im_width, dtype=tf.int32) start_y = tf.random.uniform(shape=(1,), minval=0, maxval=im_height, dtype=tf.int32) mask = tf.pad(mask, [[cutout_size + start_y[0], im_height - start_y[0]], [cutout_size + start_x[0], im_width - start_x[0]]]) mask = mask[cutout_size: cutout_size + im_height, cutout_size: cutout_size + im_width] mask = tf.tile(tf.reshape(mask, (im_height, im_width, 1)), (1, 1, 3)) image = tf.where(tf.equal(mask, 0), x=image, y=tf.zeros_like(image)) return image def _add_drop_path(self, X, keep_prob): with tf.variable_scope('drop_path'): batch_size = tf.shape(X)[0] noise_shape = (batch_size, 1, 1, 1) random_tensor = keep_prob + tf.random_uniform(noise_shape, dtype=tf.float32) binary_tensor = tf.floor(random_tensor) X = (X / keep_prob) * binary_tensor return X def _do_conv(self, X, w, h, in_ch, out_ch, filter_size=1, no_relu=False, no_reg=False, is_train=False): W = self._make_var('W', (filter_size, filter_size, in_ch, out_ch), no_reg=no_reg) if not no_relu: X = tf.nn.relu(X) X = tf.nn.conv2d(X, W, (1, 1, 1, 1), padding='SAME') X = self._add_batch_norm(X, out_ch, is_train=is_train) X = tf.reshape(X, (-1, w, h, out_ch)) # Sanity shape check return X def _do_separable_conv(self, X, w, h, ch, filter_size=3, stride=1, ch_mul=1, no_batch_norm=False, W_d=None, W_p=None, is_train=False): if W_d is None: W_d = self._make_var('W_d', (filter_size, filter_size, ch, ch_mul)) if W_p is None: W_p = self._make_var('W_p', (1, 1, ch_mul * ch, ch)) X = tf.nn.relu(X) X = tf.nn.separable_conv2d(X, W_d, W_p, strides=(1, stride, stride, 1), padding='SAME') if not no_batch_norm: X = self._add_batch_norm(X, ch, is_train=is_train) return X def _calibrate(self, X, w, h, ch, w_out, h_out, ch_out, is_train=False): ''' Calibrate input of shape (-1, w, h, ch) to (-1, w_out, h_out, ch_out), assuming (w, h) / (w_out, h_out) is power of 2 ''' # Downsample with factorized reduction downsample_no = 0 while w > w_out or h > h_out: downsample_no += 1 with tf.variable_scope('downsample_{}x'.format(downsample_no)): X = tf.nn.relu(X) X = self._add_factorized_reduction(X, w, h, ch, ch_out, is_train=is_train) ch = ch_out w >>= 1 h >>= 1 # If channel counts finally don't match, convert channel counts with 1x1 conv if ch != ch_out: with tf.variable_scope('convert_conv'): X = self._do_conv(X, w, h, ch, ch_out, filter_size=1, is_train=is_train) X = tf.reshape(X, (-1, w_out, h_out, ch_out)) # Sanity shape check return X def _add_fully_connected(self, X, in_shape, out_ch, no_reg=False): ch = np.prod(in_shape) X = tf.reshape(X, (-1, ch)) W = self._make_var('W', (ch, out_ch), no_reg=no_reg) X = tf.matmul(X, W) X = tf.reshape(X, (-1, out_ch)) # Sanity shape check return X def _add_factorized_reduction(self, X, in_w, in_h, in_ch, out_ch, is_train=False): ''' Output is of shape (in_w // 2, in_h // 2, out_ch) ''' assert in_w % 2 == 0 and in_h % 2 == 0, 'Width & height ({} & {}) must both be even!'.format(in_w, in_h) with tf.variable_scope('fac_reduc'): # Split area into 2 halves half_1 = tf.nn.avg_pool(X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID') shifted_X = tf.pad(X, ((0, 0), (0, 1), (0, 1), (0, 0)))[:, 1:, 1:, :] half_2 = tf.nn.avg_pool(shifted_X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID') # Apply 1 x 1 convolution to each half separately W_half_1 = self._make_var('W_half_1', (1, 1, in_ch, out_ch >> 1)) X_half_1 = tf.nn.conv2d(half_1, W_half_1, (1, 1, 1, 1), padding='VALID') W_half_2 = self._make_var('W_half_2', (1, 1, in_ch, out_ch >> 1)) X_half_2 = tf.nn.conv2d(half_2, W_half_2, (1, 1, 1, 1), padding='VALID') # Concat both halves across channels X = tf.concat([X_half_1, X_half_2], axis=3) # Apply batch normalization X = self._add_batch_norm(X, out_ch, is_train=is_train) X = tf.reshape(X, (-1, in_w // 2, in_h // 2, out_ch)) # Sanity shape check return X def _add_batch_norm(self, X, in_ch, decay=0.9, epsilon=1e-5, offset=None, scale=None, is_train=False, no_moving_average=False): with tf.variable_scope('batch_norm'): if offset is None: offset = self._make_var('offset', (in_ch,), init_constant=0) if scale is None: scale = self._make_var('scale', (in_ch,), init_constant=1) if not no_moving_average: moving_mean = self._make_var('moving_mean', (in_ch,), trainable=False, init_constant=0) moving_variance = self._make_var('moving_variance', (in_ch,), trainable=False, init_constant=1) if is_train: # For training, do batch norm with batch mean & variance # Update moving averages if training (X, mean, variance) = tf.nn.fused_batch_norm(X, scale, offset, epsilon=epsilon, is_training=True) update_mean = moving_averages.assign_moving_average(moving_mean, mean, decay) update_variance = moving_averages.assign_moving_average(moving_variance, variance, decay) with tf.control_dependencies([update_mean, update_variance]): X = tf.identity(X) else: # For prediction, do batch norm with computed moving mean & variance from training # Don't update moving averages if predicting (X, _, _) = tf.nn.fused_batch_norm(X, scale, offset, mean=moving_mean, variance=moving_variance, epsilon=epsilon, is_training=False) else: (X, _, _) = tf.nn.fused_batch_norm(X, scale, offset, epsilon=epsilon, is_training=True) return X def _mark_for_monitoring(self, name, value): tf.add_to_collection(TF_COLLECTION_MONITORED, tf.identity(value, name)) def _add_monitoring_of_values(self): monitored_values = tf.get_collection(TF_COLLECTION_MONITORED) monitored_values = { value.name.split(':')[0]: value # Get rid of ':0' from name for value in monitored_values } for (name, value) in monitored_values.items(): tf.summary.scalar(name, value) summary_op = tf.summary.merge_all() return (summary_op, monitored_values) def _make_var(self, name, shape, dtype=None, no_reg=False, initializer=None, init_constant=None, trainable=True): if initializer is None: if init_constant is not None: initializer = tf.constant_initializer(init_constant, dtype=tf.float32) else: initializer = tf.contrib.keras.initializers.he_normal() # Ensure that name is unique by shape too name += '-shape-{}'.format('x'.join([str(x) for x in shape])) var = tf.get_variable(name, shape=shape, dtype=dtype, initializer=initializer, trainable=trainable) # Add L2 regularization node for trainable var if trainable and not no_reg: l2_loss = tf.nn.l2_loss(var) tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, l2_loss) return var class TimedRepeatCondition(): def __init__(self, every_secs=60): self._every_secs = every_secs self._last_trigger_time = datetime.now() def check(self) -> bool: if (datetime.now() - self._last_trigger_time).total_seconds() >= self._every_secs: self._last_trigger_time = datetime.now() return True else: return False if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--train_path', type=str, default='data/cifar10_train.zip', help='Path to train dataset') parser.add_argument('--val_path', type=str, default='data/cifar10_val.zip', help='Path to validation dataset') parser.add_argument('--test_path', type=str, default='data/cifar10_test.zip', help='Path to test dataset') parser.add_argument('--query_path', type=str, default='examples/data/image_classification/cifar10_test_1.png', help='Path(s) to query image(s), delimited by commas') (args, _) = parser.parse_known_args() queries = utils.dataset.load_images(args.query_path.split(',')).tolist() test_model_class( model_file_path=__file__, model_class='TfEnas', task='IMAGE_CLASSIFICATION', dependencies={ ModelDependency.TENSORFLOW: '1.12.0' }, train_dataset_path=args.train_path, val_dataset_path=args.val_path, test_dataset_path=args.test_path, queries=queries )
[ "tensorflow.get_variable", "tensorflow.concat", "tensorflow.contrib.keras.initializers.he_normal", "tensorflow.control_dependencies", "numpy.asarray", "tensorflow.stack", "tensorflow.nn.max_pool", "tensorflow.global_variables", "tensorflow.equal", "tensorflow.cast", "tensorflow.minimum", "tensorflow.train.cosine_decay_restarts", "tensorflow.image.random_crop", "tensorflow.data.experimental.map_and_batch", "tensorflow.nn.l2_loss", "numpy.mean", "tensorflow.pad", "tensorflow.initializers.constant", "tensorflow.add_n", "tensorflow.summary.scalar", "tensorflow.nn.conv2d", "tensorflow.Graph", "tensorflow.python.training.moving_averages.assign_moving_average", "tensorflow.image.random_flip_left_right", "tensorflow.get_collection", "tensorflow.floor", "tensorflow.gradients", "tensorflow.ConfigProto", "tensorflow.gather", "numpy.std", "tensorflow.train.MomentumOptimizer", "tensorflow.clip_by_norm", "tensorflow.Session", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.argmax", "numpy.zeros", "tensorflow.nn.dropout", "tensorflow.nn.fused_batch_norm", "tensorflow.matmul", "tensorflow.shape", "tensorflow.random.uniform", "tensorflow.identity", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.zeros_like", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.random.rand", "tensorflow.summary.merge_all", "tensorflow.nn.avg_pool", "tensorflow.one_hot", "tensorflow.add_to_collection", "tensorflow.size", "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.reshape", "tensorflow.nn.separable_conv2d", "tensorflow.ones", "tensorflow.assign", "tensorflow.constant_initializer", "numpy.prod", "tensorflow.variable_scope", "tensorflow.random_uniform" ]
examples/models/image_classification/TfEnas.py
[(37, 'collections.namedtuple', 'namedtuple', (['"""_Model"""', "['train_dataset_init_op', 'pred_dataset_init_op', 'train_op', 'summary_op',\n 'pred_probs', 'pred_corrects', 'train_corrects', 'step',\n 'vars_assign_op', 'ph', 'var_phs']"], {}), False, 'from collections import namedtuple\n'), (41, 'collections.namedtuple', 'namedtuple', (['"""_ModelMemo"""', "['train_params', 'use_dynamic_arch', 'knobs', 'model', 'graph', 'sess',\n 'saver', 'monitored_values']"], {}), False, 'from collections import namedtuple\n'), (44, 'collections.namedtuple', 'namedtuple', (['"""_ModelPlaceholder"""', "['train_images', 'train_classes', 'pred_images', 'pred_classes',\n 'normal_arch', 'reduction_arch']"], {}), False, 'from collections import namedtuple\n'), (1288, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), False, 'import argparse\n'), (1297, 'singa_auto.model.dev.test_model_class', 'test_model_class', ([], {'model_file_path': '__file__', 'model_class': '"""TfEnas"""', 'task': '"""IMAGE_CLASSIFICATION"""', 'dependencies': "{ModelDependency.TENSORFLOW: '1.12.0'}", 'train_dataset_path': 'args.train_path', 'val_dataset_path': 'args.val_path', 'test_dataset_path': 'args.test_path', 'queries': 'queries'}), False, 'from singa_auto.model.dev import test_model_class\n'), (135, 'singa_auto.model.ArchKnob', 'ArchKnob', (['cell_archs'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (174, 'singa_auto.model.utils.dataset.transform_images', 'utils.dataset.transform_images', (['queries'], {'image_size': 'image_size', 'mode': '"""RGB"""'}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (183, 'json.dumps', 'json.dumps', (['self._train_params'], {}), False, 'import json\n'), (194, 'numpy.random.rand', 'np.random.rand', ([], {}), True, 'import numpy as np\n'), (204, 'json.loads', 'json.loads', (["params['train_params']"], {}), False, 'import json\n'), (329, 'singa_auto.model.utils.logger.log', 'utils.logger.log', (['"""Loading dataset..."""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (330, 'singa_auto.model.utils.dataset.load_dataset_of_image_files', 'utils.dataset.load_dataset_of_image_files', (['dataset_path'], {'max_image_size': 'image_size', 'mode': '"""RGB"""'}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (350, 'tensorflow.Graph', 'tf.Graph', ([], {}), True, 'import tensorflow as tf\n'), (414, 'singa_auto.model.utils.logger.log', 'utils.logger.log', (['"""Loading TF vars..."""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (416, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (434, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""train_images_ph"""', 'shape': '(None, w, h, in_ch)'}), True, 'import tensorflow as tf\n'), (435, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""pred_images_ph"""', 'shape': '(None, w, h, in_ch)'}), True, 'import tensorflow as tf\n'), (436, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""train_classes_ph"""', 'shape': '(None,)'}), True, 'import tensorflow as tf\n'), (437, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""pred_classes_ph"""', 'shape': '(None,)'}), True, 'import tensorflow as tf\n'), (438, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""normal_arch_ph"""', 'shape': '(CELL_NUM_BLOCKS, 4)'}), True, 'import tensorflow as tf\n'), (439, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""reduction_arch_ph"""', 'shape': '(CELL_NUM_BLOCKS, 4)'}), True, 'import tensorflow as tf\n'), (529, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (531, 'tensorflow.gradients', 'tf.gradients', (['loss', 'tf_trainable_vars'], {}), True, 'import tensorflow as tf\n'), (539, 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', (['lr', 'opt_momentum'], {'use_locking': '(True)', 'use_nesterov': '(True)'}), True, 'import tensorflow as tf\n'), (591, 'tensorflow.constant', 'tf.constant', (['(1)'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (618, 'math.ceil', 'math.ceil', (['(N / batch_size)'], {}), False, 'import math\n'), (645, 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), True, 'import tensorflow as tf\n'), (647, 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), True, 'import tensorflow as tf\n'), (652, 'singa_auto.model.utils.logger.log', 'utils.logger.log', (['"""Feeding dataset to model..."""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (677, 'singa_auto.model.utils.logger.define_plot', 'utils.logger.define_plot', (['"""Train accuracy over Epochs"""', "['mean_acc']", '"""epoch"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (713, 'numpy.mean', 'np.mean', (['corrects'], {}), True, 'import numpy as np\n'), (728, 'numpy.asarray', 'np.asarray', (['all_probs'], {}), True, 'import numpy as np\n'), (734, 'math.ceil', 'math.ceil', (['(N / batch_size)'], {}), False, 'import math\n'), (792, 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), True, 'import tensorflow as tf\n'), (793, 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(1)', 'output_type': 'tf.int32'}), True, 'import tensorflow as tf\n'), (794, 'tensorflow.equal', 'tf.equal', (['preds', 'classes'], {}), True, 'import tensorflow as tf\n'), (802, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'logits', 'labels': 'classes'}), True, 'import tensorflow as tf\n'), (803, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['log_probs'], {}), True, 'import tensorflow as tf\n'), (807, 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES'], {}), True, 'import tensorflow as tf\n'), (812, 'tensorflow.constant', 'tf.constant', (['(0)'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (822, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (823, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['X', '(1, 2)'], {}), True, 'import tensorflow as tf\n'), (824, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, in_ch)'], {}), True, 'import tensorflow as tf\n'), (828, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (887, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w, h, comb_ch)'], {}), True, 'import tensorflow as tf\n'), (932, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w, h, comb_ch)'], {}), True, 'import tensorflow as tf\n'), (963, 'tensorflow.add_n', 'tf.add_n', (['block_uses'], {}), True, 'import tensorflow as tf\n'), (965, 'tensorflow.size', 'tf.size', (['unused_indices'], {}), True, 'import tensorflow as tf\n'), (1005, 'tensorflow.stack', 'tf.stack', (['(cell_inputs + blocks)'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (1017, 'tensorflow.stack', 'tf.stack', (['op_Xs'], {}), True, 'import tensorflow as tf\n'), (1042, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w // stride, h // stride, ch)'], {}), True, 'import tensorflow as tf\n'), (1051, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w // stride, h // stride, ch)'], {}), True, 'import tensorflow as tf\n'), (1059, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w // stride, h // stride, ch)'], {}), True, 'import tensorflow as tf\n'), (1101, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w // stride, h // stride, ch)'], {}), True, 'import tensorflow as tf\n'), (1109, 'tensorflow.ones', 'tf.ones', (['[cutout_size, cutout_size]'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (1110, 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(1,)', 'minval': '(0)', 'maxval': 'im_width', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (1111, 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(1,)', 'minval': '(0)', 'maxval': 'im_height', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (1112, 'tensorflow.pad', 'tf.pad', (['mask', '[[cutout_size + start_y[0], im_height - start_y[0]], [cutout_size + start_x\n [0], im_width - start_x[0]]]'], {}), True, 'import tensorflow as tf\n'), (1133, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['X', 'W', '(1, 1, 1, 1)'], {'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (1135, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w, h, out_ch)'], {}), True, 'import tensorflow as tf\n'), (1144, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (1145, 'tensorflow.nn.separable_conv2d', 'tf.nn.separable_conv2d', (['X', 'W_d', 'W_p'], {'strides': '(1, stride, stride, 1)', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (1170, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, w_out, h_out, ch_out)'], {}), True, 'import tensorflow as tf\n'), (1174, 'numpy.prod', 'np.prod', (['in_shape'], {}), True, 'import numpy as np\n'), (1175, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, ch)'], {}), True, 'import tensorflow as tf\n'), (1177, 'tensorflow.matmul', 'tf.matmul', (['X', 'W'], {}), True, 'import tensorflow as tf\n'), (1178, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, out_ch)'], {}), True, 'import tensorflow as tf\n'), (1205, 'tensorflow.reshape', 'tf.reshape', (['X', '(-1, in_w // 2, in_h // 2, out_ch)'], {}), True, 'import tensorflow as tf\n'), (1243, 'tensorflow.get_collection', 'tf.get_collection', (['TF_COLLECTION_MONITORED'], {}), True, 'import tensorflow as tf\n'), (1252, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (1266, 'tensorflow.get_variable', 'tf.get_variable', (['name'], {'shape': 'shape', 'dtype': 'dtype', 'initializer': 'initializer', 'trainable': 'trainable'}), True, 'import tensorflow as tf\n'), (1278, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (71, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(32)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (72, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(310)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (73, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(128)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (74, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.05)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (75, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(36)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (76, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(3)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (77, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.0004)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (78, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.8)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (79, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.9)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (80, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(True)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (81, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.002)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (82, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(10)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (83, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(2)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (84, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(15)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (85, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.4)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (86, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.6)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (87, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(310)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (88, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (89, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (90, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(False)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (91, 'singa_auto.model.PolicyKnob', 'PolicyKnob', (['"""SHARE_PARAMS"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (94, 'singa_auto.model.PolicyKnob', 'PolicyKnob', (['"""DOWNSCALE"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (95, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(6)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (96, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(20)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (97, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.9)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (98, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.01)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (99, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(0.9)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (100, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(150)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (103, 'singa_auto.model.PolicyKnob', 'PolicyKnob', (['"""EARLY_STOP"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (104, 'singa_auto.model.FixedKnob', 'FixedKnob', (['(1)'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (107, 'singa_auto.model.PolicyKnob', 'PolicyKnob', (['"""SKIP_TRAIN"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (110, 'singa_auto.model.PolicyKnob', 'PolicyKnob', (['"""QUICK_EVAL"""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (118, 'singa_auto.model.KnobValue', 'KnobValue', (['i'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (187, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (365, 'singa_auto.model.utils.logger.log', 'utils.logger.log', (['"""Building model for training..."""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (380, 'singa_auto.model.utils.logger.log', 'utils.logger.log', (['"""Building model for predictions..."""'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (396, 'tensorflow.global_variables', 'tf.global_variables', ([], {}), True, 'import tensorflow as tf\n'), (397, 'tensorflow.train.Saver', 'tf.train.Saver', (['tf_vars'], {}), True, 'import tensorflow as tf\n'), (467, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {'reuse': '(not is_train)'}), True, 'import tensorflow as tf\n'), (555, 'tensorflow.cast', 'tf.cast', (['images', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (563, 'tensorflow.pad', 'tf.pad', (['image', '[[4, 4], [4, 4], [0, 0]]'], {}), True, 'import tensorflow as tf\n'), (564, 'tensorflow.image.random_crop', 'tf.image.random_crop', (['image', '(w, h, in_ch)'], {}), True, 'import tensorflow as tf\n'), (565, 'tensorflow.image.random_flip_left_right', 'tf.image.random_flip_left_right', (['image'], {}), True, 'import tensorflow as tf\n'), (597, 'math.ceil', 'math.ceil', (['(N / batch_size)'], {}), False, 'import math\n'), (598, 'tensorflow.minimum', 'tf.minimum', (['((step + 1) / steps_per_epoch / drop_path_decay_epochs)', '(1)'], {}), True, 'import tensorflow as tf\n'), (600, 'tensorflow.cast', 'tf.cast', (['keep_prob', 'tf.float32'], {}), True, 'import tensorflow as tf\n'), (623, 'tensorflow.train.cosine_decay_restarts', 'tf.train.cosine_decay_restarts', (['lr', 'epoch', 'sgdr_decay_epochs'], {'t_mul': 'sgdr_t_mul', 'alpha': 'sgdr_alpha'}), True, 'import tensorflow as tf\n'), (634, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (698, 'numpy.mean', 'np.mean', (['corrects'], {}), True, 'import numpy as np\n'), (699, 'singa_auto.model.utils.logger.log', 'utils.logger.log', ([], {'epoch': 'epoch', 'mean_acc': 'mean_acc'}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (765, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""pool"""'], {}), True, 'import tensorflow as tf\n'), (766, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (767, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['X'], {'ksize': '(1, pool_ksize, pool_ksize, 1)', 'strides': '(1, pool_stride, pool_stride, 1)', 'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (773, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_0"""'], {}), True, 'import tensorflow as tf\n'), (778, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv_1"""'], {}), True, 'import tensorflow as tf\n'), (786, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fully_connected"""'], {}), True, 'import tensorflow as tf\n'), (808, 'tensorflow.add_n', 'tf.add_n', (['reg_losses'], {}), True, 'import tensorflow as tf\n'), (814, 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'aux_logits', 'labels': 'classes'}), True, 'import tensorflow as tf\n'), (840, 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf_var.dtype', 'shape': 'tf_var.shape'}), True, 'import tensorflow as tf\n'), (858, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer_-1_calibrate"""'], {}), True, 'import tensorflow as tf\n'), (861, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer_-2_calibrate"""'], {}), True, 'import tensorflow as tf\n'), (944, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""combine"""'], {}), True, 'import tensorflow as tf\n'), (948, 'tensorflow.concat', 'tf.concat', (['out_blocks'], {'axis': '(3)'}), True, 'import tensorflow as tf\n'), (968, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""select"""'], {}), True, 'import tensorflow as tf\n'), (969, 'tensorflow.stack', 'tf.stack', (['(cell_inputs + blocks)'], {}), True, 'import tensorflow as tf\n'), (970, 'tensorflow.gather', 'tf.gather', (['stacked_blocks', 'unused_indices'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (971, 'tensorflow.transpose', 'tf.transpose', (['out_blocks', '(1, 2, 3, 0, 4)'], {}), True, 'import tensorflow as tf\n'), (974, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""combine"""'], {}), True, 'import tensorflow as tf\n'), (976, 'tensorflow.gather', 'tf.gather', (['W', 'unused_indices'], {'axis': '(0)'}), True, 'import tensorflow as tf\n'), (977, 'tensorflow.reshape', 'tf.reshape', (['W', '(1, 1, num_out_blocks * block_ch, block_ch)'], {}), True, 'import tensorflow as tf\n'), (978, 'tensorflow.reshape', 'tf.reshape', (['out_blocks', '(-1, w, h, num_out_blocks * block_ch)'], {}), True, 'import tensorflow as tf\n'), (979, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (980, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['X', 'W', '(1, 1, 1, 1)'], {'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (1040, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""avg_pool_3x3_op"""'], {}), True, 'import tensorflow as tf\n'), (1041, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['X'], {'ksize': '(1, filter_size, filter_size, 1)', 'strides': '[1, stride, stride, 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (1047, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""identity_op"""'], {}), True, 'import tensorflow as tf\n'), (1057, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""max_pool_3x3_op"""'], {}), True, 'import tensorflow as tf\n'), (1058, 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['X'], {'ksize': '(1, filter_size, filter_size, 1)', 'strides': '[1, stride, stride, 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (1116, 'tensorflow.reshape', 'tf.reshape', (['mask', '(im_height, im_width, 1)'], {}), True, 'import tensorflow as tf\n'), (1117, 'tensorflow.equal', 'tf.equal', (['mask', '(0)'], {}), True, 'import tensorflow as tf\n'), (1121, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""drop_path"""'], {}), True, 'import tensorflow as tf\n'), (1125, 'tensorflow.floor', 'tf.floor', (['random_tensor'], {}), True, 'import tensorflow as tf\n'), (1132, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (1187, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fac_reduc"""'], {}), True, 'import tensorflow as tf\n'), (1189, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['X'], {'ksize': '(1, 1, 1, 1)', 'strides': '(1, 2, 2, 1)', 'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (1191, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['shifted_X'], {'ksize': '(1, 1, 1, 1)', 'strides': '(1, 2, 2, 1)', 'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (1195, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['half_1', 'W_half_1', '(1, 1, 1, 1)'], {'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (1197, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['half_2', 'W_half_2', '(1, 1, 1, 1)'], {'padding': '"""VALID"""'}), True, 'import tensorflow as tf\n'), (1200, 'tensorflow.concat', 'tf.concat', (['[X_half_1, X_half_2]'], {'axis': '(3)'}), True, 'import tensorflow as tf\n'), (1211, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""batch_norm"""'], {}), True, 'import tensorflow as tf\n'), (1240, 'tensorflow.identity', 'tf.identity', (['value', 'name'], {}), True, 'import tensorflow as tf\n'), (1250, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['name', 'value'], {}), True, 'import tensorflow as tf\n'), (1270, 'tensorflow.nn.l2_loss', 'tf.nn.l2_loss', (['var'], {}), True, 'import tensorflow as tf\n'), (1271, 'tensorflow.add_to_collection', 'tf.add_to_collection', (['tf.GraphKeys.REGULARIZATION_LOSSES', 'l2_loss'], {}), True, 'import tensorflow as tf\n'), (1282, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (127, 'singa_auto.model.KnobValue', 'KnobValue', (['i'], {}), False, 'from singa_auto.model import utils, BaseModel, IntegerKnob, CategoricalKnob, FloatKnob, FixedKnob, ArchKnob, KnobValue, PolicyKnob\n'), (191, 'numpy.asarray', 'np.asarray', (['value'], {}), True, 'import numpy as np\n'), (333, 'numpy.mean', 'np.mean', (['images'], {'axis': '(0, 1, 2)'}), True, 'import numpy as np\n'), (334, 'numpy.std', 'np.std', (['images'], {'axis': '(0, 1, 2)'}), True, 'import numpy as np\n'), (470, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""layer_stem"""'], {}), True, 'import tensorflow as tf\n'), (516, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['X', 'dropout_keep_prob'], {}), True, 'import tensorflow as tf\n'), (519, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""fully_connected"""'], {}), True, 'import tensorflow as tf\n'), (536, 'tensorflow.clip_by_norm', 'tf.clip_by_norm', (['x', 'grad_clip_norm'], {}), True, 'import tensorflow as tf\n'), (573, 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['(images, classes)'], {}), True, 'import tensorflow as tf\n'), (575, 'tensorflow.data.experimental.map_and_batch', 'tf.data.experimental.map_and_batch', ([], {'map_func': '_preprocess_train', 'batch_size': 'batch_size'}), True, 'import tensorflow as tf\n'), (815, 'tensorflow.reduce_mean', 'tf.reduce_mean', (['log_probs'], {}), True, 'import tensorflow as tf\n'), (844, 'tensorflow.assign', 'tf.assign', (['tf_var', 'ph'], {}), True, 'import tensorflow as tf\n'), (881, 'tensorflow.add_n', 'tf.add_n', (['[X1, X2]'], {}), True, 'import tensorflow as tf\n'), (926, 'tensorflow.add_n', 'tf.add_n', (['[X1, X2]'], {}), True, 'import tensorflow as tf\n'), (961, 'tensorflow.one_hot', 'tf.one_hot', (['idx1', 'ni'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (961, 'tensorflow.one_hot', 'tf.one_hot', (['idx2', 'ni'], {'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (1117, 'tensorflow.zeros_like', 'tf.zeros_like', (['image'], {}), True, 'import tensorflow as tf\n'), (1122, 'tensorflow.shape', 'tf.shape', (['X'], {}), True, 'import tensorflow as tf\n'), (1124, 'tensorflow.random_uniform', 'tf.random_uniform', (['noise_shape'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (1159, 'tensorflow.nn.relu', 'tf.nn.relu', (['X'], {}), True, 'import tensorflow as tf\n'), (1167, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""convert_conv"""'], {}), True, 'import tensorflow as tf\n'), (1190, 'tensorflow.pad', 'tf.pad', (['X', '((0, 0), (0, 1), (0, 1), (0, 0))'], {}), True, 'import tensorflow as tf\n'), (1235, 'tensorflow.nn.fused_batch_norm', 'tf.nn.fused_batch_norm', (['X', 'scale', 'offset'], {'epsilon': 'epsilon', 'is_training': '(True)'}), True, 'import tensorflow as tf\n'), (1259, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['init_constant'], {'dtype': 'tf.float32'}), True, 'import tensorflow as tf\n'), (1261, 'tensorflow.contrib.keras.initializers.he_normal', 'tf.contrib.keras.initializers.he_normal', ([], {}), True, 'import tensorflow as tf\n'), (362, 'tensorflow.initializers.constant', 'tf.initializers.constant', (['(0)'], {}), True, 'import tensorflow as tf\n'), (638, 'numpy.zeros', 'np.zeros', (['(1, w, h, in_ch)'], {}), True, 'import numpy as np\n'), (639, 'numpy.zeros', 'np.zeros', (['(1,)'], {}), True, 'import numpy as np\n'), (640, 'numpy.zeros', 'np.zeros', (['(1, w, h, in_ch)'], {}), True, 'import numpy as np\n'), (641, 'numpy.zeros', 'np.zeros', (['(1,)'], {}), True, 'import numpy as np\n'), (873, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""X1"""'], {}), True, 'import tensorflow as tf\n'), (877, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""X2"""'], {}), True, 'import tensorflow as tf\n'), (916, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""X1"""'], {}), True, 'import tensorflow as tf\n'), (921, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""X2"""'], {}), True, 'import tensorflow as tf\n'), (964, 'tensorflow.equal', 'tf.equal', (['block_uses', '(0)'], {}), True, 'import tensorflow as tf\n'), (1224, 'tensorflow.nn.fused_batch_norm', 'tf.nn.fused_batch_norm', (['X', 'scale', 'offset'], {'epsilon': 'epsilon', 'is_training': '(True)'}), True, 'import tensorflow as tf\n'), (1225, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', (['moving_mean', 'mean', 'decay'], {}), False, 'from tensorflow.python.training import moving_averages\n'), (1226, 'tensorflow.python.training.moving_averages.assign_moving_average', 'moving_averages.assign_moving_average', (['moving_variance', 'variance', 'decay'], {}), False, 'from tensorflow.python.training import moving_averages\n'), (1232, 'tensorflow.nn.fused_batch_norm', 'tf.nn.fused_batch_norm', (['X', 'scale', 'offset'], {'mean': 'moving_mean', 'variance': 'moving_variance', 'epsilon': 'epsilon', 'is_training': '(False)'}), True, 'import tensorflow as tf\n'), (1227, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_mean, update_variance]'], {}), True, 'import tensorflow as tf\n'), (1228, 'tensorflow.identity', 'tf.identity', (['X'], {}), True, 'import tensorflow as tf\n'), (1281, 'datetime.datetime.now', 'datetime.now', ([], {}), False, 'from datetime import datetime\n'), (491, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""reduction_cell"""'], {}), True, 'import tensorflow as tf\n'), (498, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""normal_cell"""'], {}), True, 'import tensorflow as tf\n'), (506, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""aux_head"""'], {}), True, 'import tensorflow as tf\n')]
vikatelis/baselines
668abf167f54317dca7795588c61f1055a4d017f
import os import numpy as np import tensorflow as tf from collections import deque def sample(logits): noise = tf.random_uniform(tf.shape(logits)) return tf.argmax(logits - tf.log(-tf.log(noise)), 1) def cat_entropy(logits): a0 = logits - tf.reduce_max(logits, 1, keepdims=True) ea0 = tf.exp(a0) z0 = tf.reduce_sum(ea0, 1, keepdims=True) p0 = ea0 / z0 return tf.reduce_sum(p0 * (tf.log(z0) - a0), 1) def cat_entropy_softmax(p0): return - tf.reduce_sum(p0 * tf.log(p0 + 1e-6), axis = 1) def ortho_init(scale=1.0): def _ortho_init(shape, dtype, partition_info=None): #lasagne ortho init for tf shape = tuple(shape) if len(shape) == 2: flat_shape = shape elif len(shape) == 4: # assumes NHWC flat_shape = (np.prod(shape[:-1]), shape[-1]) else: raise NotImplementedError a = np.random.normal(0.0, 1.0, flat_shape) u, _, v = np.linalg.svd(a, full_matrices=False) q = u if u.shape == flat_shape else v # pick the one with the correct shape q = q.reshape(shape) return (scale * q[:shape[0], :shape[1]]).astype(np.float32) return _ortho_init def conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, data_format='NHWC', one_dim_bias=False): if data_format == 'NHWC': channel_ax = 3 strides = [1, stride, stride, 1] bshape = [1, 1, 1, nf] elif data_format == 'NCHW': channel_ax = 1 strides = [1, 1, stride, stride] bshape = [1, nf, 1, 1] else: raise NotImplementedError bias_var_shape = [nf] if one_dim_bias else [1, nf, 1, 1] nin = x.get_shape()[channel_ax].value wshape = [rf, rf, nin, nf] with tf.variable_scope(scope): w = tf.get_variable("w", wshape, initializer=ortho_init(init_scale)) b = tf.get_variable("b", bias_var_shape, initializer=tf.constant_initializer(0.0)) if not one_dim_bias and data_format == 'NHWC': b = tf.reshape(b, bshape) return tf.nn.conv2d(x, w, strides=strides, padding=pad, data_format=data_format) + b def fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0): with tf.variable_scope(scope): nin = x.get_shape()[1].value w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale)) print("w is "+str(w)) b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias)) return tf.matmul(x, w)+b def batch_to_seq(h, nbatch, nsteps, flat=False): if flat: h = tf.reshape(h, [nbatch, nsteps]) else: h = tf.reshape(h, [nbatch, nsteps, -1]) return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)] def seq_to_batch(h, flat = False): shape = h[0].get_shape().as_list() if not flat: assert(len(shape) > 1) nh = h[0].get_shape()[-1].value return tf.reshape(tf.concat(axis=1, values=h), [-1, nh]) else: return tf.reshape(tf.stack(values=h, axis=1), [-1]) def lstm(xs, ms, s, scope, nh, init_scale=1.0): nbatch, nin = [v.value for v in xs[0].get_shape()] with tf.variable_scope(scope): wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale)) wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s) for idx, (x, m) in enumerate(zip(xs, ms)): c = c*(1-m) h = h*(1-m) z = tf.matmul(x, wx) + tf.matmul(h, wh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def _ln(x, g, b, e=1e-5, axes=[1]): u, s = tf.nn.moments(x, axes=axes, keep_dims=True) x = (x-u)/tf.sqrt(s+e) x = x*g+b return x def lnlstm(xs, ms, s, scope, nh, init_scale=1.0): nbatch, nin = [v.value for v in xs[0].get_shape()] with tf.variable_scope(scope): wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale)) gx = tf.get_variable("gx", [nh*4], initializer=tf.constant_initializer(1.0)) bx = tf.get_variable("bx", [nh*4], initializer=tf.constant_initializer(0.0)) wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale)) gh = tf.get_variable("gh", [nh*4], initializer=tf.constant_initializer(1.0)) bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0)) bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s) for idx, (x, m) in enumerate(zip(xs, ms)): c = c*(1-m) h = h*(1-m) z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(_ln(c, gc, bc)) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def conv_to_fc(x): nh = np.prod([v.value for v in x.get_shape()[1:]]) x = tf.reshape(x, [-1, nh]) return x def discount_with_dones(rewards, dones, gamma): discounted = [] r = 0 for reward, done in zip(rewards[::-1], dones[::-1]): r = reward + gamma*r*(1.-done) # fixed off by one bug discounted.append(r) return discounted[::-1] def find_trainable_variables(key): return tf.trainable_variables(key) def make_path(f): return os.makedirs(f, exist_ok=True) def constant(p): return 1 def linear(p): return 1-p def middle_drop(p): eps = 0.75 if 1-p<eps: return eps*0.1 return 1-p def double_linear_con(p): p *= 2 eps = 0.125 if 1-p<eps: return eps return 1-p def double_middle_drop(p): eps1 = 0.75 eps2 = 0.25 if 1-p<eps1: if 1-p<eps2: return eps2*0.5 return eps1*0.1 return 1-p schedules = { 'linear':linear, 'constant':constant, 'double_linear_con': double_linear_con, 'middle_drop': middle_drop, 'double_middle_drop': double_middle_drop } class Scheduler(object): def __init__(self, v, nvalues, schedule): self.n = 0. self.v = v self.nvalues = nvalues self.schedule = schedules[schedule] def value(self): current_value = self.v*self.schedule(self.n/self.nvalues) self.n += 1. return current_value def value_steps(self, steps): return self.v*self.schedule(steps/self.nvalues) class EpisodeStats: def __init__(self, nsteps, nenvs): self.episode_rewards = [] for i in range(nenvs): self.episode_rewards.append([]) self.lenbuffer = deque(maxlen=40) # rolling buffer for episode lengths self.rewbuffer = deque(maxlen=40) # rolling buffer for episode rewards self.nsteps = nsteps self.nenvs = nenvs def feed(self, rewards, masks): rewards = np.reshape(rewards, [self.nenvs, self.nsteps]) masks = np.reshape(masks, [self.nenvs, self.nsteps]) for i in range(0, self.nenvs): for j in range(0, self.nsteps): self.episode_rewards[i].append(rewards[i][j]) if masks[i][j]: l = len(self.episode_rewards[i]) s = sum(self.episode_rewards[i]) self.lenbuffer.append(l) self.rewbuffer.append(s) self.episode_rewards[i] = [] def mean_length(self): if self.lenbuffer: return np.mean(self.lenbuffer) else: return 0 # on the first params dump, no episodes are finished def mean_reward(self): if self.rewbuffer: return np.mean(self.rewbuffer) else: return 0 # For ACER def get_by_index(x, idx): assert(len(x.get_shape()) == 2) assert(len(idx.get_shape()) == 1) idx_flattened = tf.range(0, x.shape[0]) * x.shape[1] + idx y = tf.gather(tf.reshape(x, [-1]), # flatten input idx_flattened) # use flattened indices return y def check_shape(ts,shapes): i = 0 for (t,shape) in zip(ts,shapes): assert t.get_shape().as_list()==shape, "id " + str(i) + " shape " + str(t.get_shape()) + str(shape) i += 1 def avg_norm(t): return tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square(t), axis=-1))) def gradient_add(g1, g2, param): print([g1, g2, param.name]) assert (not (g1 is None and g2 is None)), param.name if g1 is None: return g2 elif g2 is None: return g1 else: return g1 + g2 def q_explained_variance(qpred, q): _, vary = tf.nn.moments(q, axes=[0, 1]) _, varpred = tf.nn.moments(q - qpred, axes=[0, 1]) check_shape([vary, varpred], [[]] * 2) return 1.0 - (varpred / vary)
[ "tensorflow.concat", "tensorflow.reduce_sum", "tensorflow.stack", "tensorflow.tanh", "numpy.mean", "tensorflow.nn.conv2d", "numpy.linalg.svd", "numpy.reshape", "tensorflow.nn.moments", "tensorflow.squeeze", "tensorflow.square", "tensorflow.trainable_variables", "tensorflow.matmul", "tensorflow.nn.sigmoid", "tensorflow.shape", "tensorflow.exp", "tensorflow.split", "tensorflow.reduce_max", "tensorflow.range", "tensorflow.reshape", "tensorflow.constant_initializer", "numpy.random.normal", "tensorflow.log", "numpy.prod", "tensorflow.variable_scope", "tensorflow.sqrt" ]
baselines/a2c/utils.py
[(12, 'tensorflow.exp', 'tf.exp', (['a0'], {}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['ea0', '(1)'], {'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (89, 'tensorflow.split', 'tf.split', ([], {'axis': '(1)', 'num_or_size_splits': '(2)', 'value': 's'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': '[c, h]'}), True, 'import tensorflow as tf\n'), (106, 'tensorflow.nn.moments', 'tf.nn.moments', (['x'], {'axes': 'axes', 'keep_dims': '(True)'}), True, 'import tensorflow as tf\n'), (127, 'tensorflow.split', 'tf.split', ([], {'axis': '(1)', 'num_or_size_splits': '(2)', 'value': 's'}), True, 'import tensorflow as tf\n'), (140, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': '[c, h]'}), True, 'import tensorflow as tf\n'), (145, 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, nh]'], {}), True, 'import tensorflow as tf\n'), (157, 'tensorflow.trainable_variables', 'tf.trainable_variables', (['key'], {}), True, 'import tensorflow as tf\n'), (160, 'os.makedirs', 'os.makedirs', (['f'], {'exist_ok': '(True)'}), False, 'import os\n'), (280, 'tensorflow.nn.moments', 'tf.nn.moments', (['q'], {'axes': '[0, 1]'}), True, 'import tensorflow as tf\n'), (281, 'tensorflow.nn.moments', 'tf.nn.moments', (['(q - qpred)'], {'axes': '[0, 1]'}), True, 'import tensorflow as tf\n'), (7, 'tensorflow.shape', 'tf.shape', (['logits'], {}), True, 'import tensorflow as tf\n'), (11, 'tensorflow.reduce_max', 'tf.reduce_max', (['logits', '(1)'], {'keepdims': '(True)'}), True, 'import tensorflow as tf\n'), (30, 'numpy.random.normal', 'np.random.normal', (['(0.0)', '(1.0)', 'flat_shape'], {}), True, 'import numpy as np\n'), (31, 'numpy.linalg.svd', 'np.linalg.svd', (['a'], {'full_matrices': '(False)'}), True, 'import numpy as np\n'), (51, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (59, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (68, 'tensorflow.reshape', 'tf.reshape', (['h', '[nbatch, nsteps]'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.reshape', 'tf.reshape', (['h', '[nbatch, nsteps, -1]'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.squeeze', 'tf.squeeze', (['v', '[1]'], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (94, 'tensorflow.split', 'tf.split', ([], {'axis': '(1)', 'num_or_size_splits': '(4)', 'value': 'z'}), True, 'import tensorflow as tf\n'), (95, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['i'], {}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['f'], {}), True, 'import tensorflow as tf\n'), (97, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['o'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.tanh', 'tf.tanh', (['u'], {}), True, 'import tensorflow as tf\n'), (107, 'tensorflow.sqrt', 'tf.sqrt', (['(s + e)'], {}), True, 'import tensorflow as tf\n'), (113, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.split', 'tf.split', ([], {'axis': '(1)', 'num_or_size_splits': '(4)', 'value': 'z'}), True, 'import tensorflow as tf\n'), (133, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['i'], {}), True, 'import tensorflow as tf\n'), (134, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['f'], {}), True, 'import tensorflow as tf\n'), (135, 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['o'], {}), True, 'import tensorflow as tf\n'), (136, 'tensorflow.tanh', 'tf.tanh', (['u'], {}), True, 'import tensorflow as tf\n'), (220, 'collections.deque', 'deque', ([], {'maxlen': '(40)'}), False, 'from collections import deque\n'), (221, 'collections.deque', 'deque', ([], {'maxlen': '(40)'}), False, 'from collections import deque\n'), (226, 'numpy.reshape', 'np.reshape', (['rewards', '[self.nenvs, self.nsteps]'], {}), True, 'import numpy as np\n'), (227, 'numpy.reshape', 'np.reshape', (['masks', '[self.nenvs, self.nsteps]'], {}), True, 'import numpy as np\n'), (256, 'tensorflow.reshape', 'tf.reshape', (['x', '[-1]'], {}), True, 'import tensorflow as tf\n'), (55, 'tensorflow.reshape', 'tf.reshape', (['b', 'bshape'], {}), True, 'import tensorflow as tf\n'), (56, 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'w'], {'strides': 'strides', 'padding': 'pad', 'data_format': 'data_format'}), True, 'import tensorflow as tf\n'), (64, 'tensorflow.matmul', 'tf.matmul', (['x', 'w'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.split', 'tf.split', ([], {'axis': '(1)', 'num_or_size_splits': 'nsteps', 'value': 'h'}), True, 'import tensorflow as tf\n'), (78, 'tensorflow.concat', 'tf.concat', ([], {'axis': '(1)', 'values': 'h'}), True, 'import tensorflow as tf\n'), (80, 'tensorflow.stack', 'tf.stack', ([], {'values': 'h', 'axis': '(1)'}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.tanh', 'tf.tanh', (['c'], {}), True, 'import tensorflow as tf\n'), (240, 'numpy.mean', 'np.mean', (['self.lenbuffer'], {}), True, 'import numpy as np\n'), (246, 'numpy.mean', 'np.mean', (['self.rewbuffer'], {}), True, 'import numpy as np\n'), (255, 'tensorflow.range', 'tf.range', (['(0)', 'x.shape[0]'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.log', 'tf.log', (['z0'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.log', 'tf.log', (['(p0 + 1e-06)'], {}), True, 'import tensorflow as tf\n'), (53, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (63, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['init_bias'], {}), True, 'import tensorflow as tf\n'), (87, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.matmul', 'tf.matmul', (['x', 'wx'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.matmul', 'tf.matmul', (['h', 'wh'], {}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (116, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (120, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (122, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.square', 'tf.square', (['t'], {}), True, 'import tensorflow as tf\n'), (8, 'tensorflow.log', 'tf.log', (['noise'], {}), True, 'import tensorflow as tf\n'), (27, 'numpy.prod', 'np.prod', (['shape[:-1]'], {}), True, 'import numpy as np\n'), (131, 'tensorflow.matmul', 'tf.matmul', (['x', 'wx'], {}), True, 'import tensorflow as tf\n'), (131, 'tensorflow.matmul', 'tf.matmul', (['h', 'wh'], {}), True, 'import tensorflow as tf\n')]
Shyonokaze/FCN_STEM
5ffb4f4bcea12646694e48246b7c2b0566cc120a
from __future__ import print_function import tensorflow as tf import numpy as np import TensorflowUtils as utils import read_MITSceneParsingData as scene_parsing import datetime import BatchDatsetReader as dataset from six.moves import xrange import os.path as osp FLAGS = tf.flags.FLAGS tf.flags.DEFINE_integer("batch_size", "2", "batch size for training") tf.flags.DEFINE_string("logs_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\logs", "path to logs directory") tf.flags.DEFINE_string("data_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Data_zoo\STEM", "path to dataset") tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer") tf.flags.DEFINE_string("model_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\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 = 100 #最大步数 NUM_OF_CLASSESS = 3 #分类数目 IMAGE_SIZE = 2048 #图像大小 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 inference(image, keep_prob): """ 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, NUM_OF_CLASSESS], name="W8") b8 = utils.bias_variable([NUM_OF_CLASSESS], name="b8") conv8 = utils.conv2d_basic(relu_dropout7, W8, b8) # annotation_pred1 = tf.argmax(conv8, dimension=3, name="prediction1") # 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, NUM_OF_CLASSESS], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") conv_t1 = utils.conv2d_transpose_strided(conv8, 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], NUM_OF_CLASSESS]) W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3") conv_t3 = 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 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") #debug annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 1], name="annotation") # annotation = tf.placeholder(tf.int32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation") pred_annotation, logits = inference(image, keep_probability) 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) #debug loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=tf.squeeze(annotation, squeeze_dims=[3]), name="entropy"))) # loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, # labels=annotation, # name="entropy"))) loss_summary = tf.summary.scalar("entropy", loss) 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': False, 'resize_size': IMAGE_SIZE} #不要resize,否则label.png会变成图片形式 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(osp.join(FLAGS.logs_dir , 'train'), sess.graph) validation_writer = tf.summary.FileWriter(osp.join(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) feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85} 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}) 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.ckpt", itr) elif FLAGS.mode == "visualize": valid_images, valid_annotations = validation_dataset_reader.get_random_batch(FLAGS.batch_size) pred = sess.run(pred_annotation, feed_dict={image: valid_images, annotation: valid_annotations, keep_probability: 1.0}) valid_annotations = np.squeeze(valid_annotations, axis=3) pred = np.squeeze(pred, axis=3) for itr in range(FLAGS.batch_size): utils.save_image(valid_images[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="pred_" + str(5+itr)) print("Saved image: %d" % itr) if __name__ == "__main__": tf.app.run()
[ "tensorflow.stack", "numpy.squeeze", "tensorflow.cast", "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.flags.DEFINE_float", "tensorflow.summary.scalar", "tensorflow.summary.image", "tensorflow.squeeze", "tensorflow.add", "tensorflow.Session", "tensorflow.trainable_variables", "tensorflow.train.Saver", "tensorflow.argmax", "tensorflow.nn.dropout", "tensorflow.app.run", "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.flags.DEFINE_string", "tensorflow.expand_dims", "tensorflow.variable_scope" ]
FCN.py
[(14, 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""batch_size"""', '"""2"""', '"""batch size for training"""'], {}), True, 'import tensorflow as tf\n'), (15, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""logs_dir"""', '"""E:\\\\work\\\\01-Myproject\\\\imag_division\\\\FCN.tensorflow-master\\\\logs"""', '"""path to logs directory"""'], {}), True, 'import tensorflow as tf\n'), (16, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""data_dir"""', '"""E:\\\\work\\\\01-Myproject\\\\imag_division\\\\FCN.tensorflow-master\\\\Data_zoo\\\\STEM"""', '"""path to dataset"""'], {}), True, 'import tensorflow as tf\n'), (17, 'tensorflow.flags.DEFINE_float', 'tf.flags.DEFINE_float', (['"""learning_rate"""', '"""1e-4"""', '"""Learning rate for Adam Optimizer"""'], {}), True, 'import tensorflow as tf\n'), (18, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""model_dir"""', '"""E:\\\\work\\\\01-Myproject\\\\imag_division\\\\FCN.tensorflow-master\\\\Model_zoo"""', '"""Path to vgg model mat"""'], {}), True, 'import tensorflow as tf\n'), (19, 'tensorflow.flags.DEFINE_bool', 'tf.flags.DEFINE_bool', (['"""debug"""', '"""False"""', '"""Debug mode: True/ False"""'], {}), True, 'import tensorflow as tf\n'), (20, 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""mode"""', '"""train"""', '"""Mode train/ test/ visualize"""'], {}), True, 'import tensorflow as tf\n'), (75, 'TensorflowUtils.get_model_data', 'utils.get_model_data', (['FLAGS.model_dir', 'MODEL_URL'], {}), True, 'import TensorflowUtils as utils\n'), (78, 'numpy.mean', 'np.mean', (['mean'], {'axis': '(0, 1)'}), True, 'import numpy as np\n'), (80, 'numpy.squeeze', 'np.squeeze', (["model_data['layers']"], {}), True, 'import numpy as np\n'), (82, 'TensorflowUtils.process_image', 'utils.process_image', (['image', 'mean_pixel'], {}), True, 'import TensorflowUtils as utils\n'), (136, 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['FLAGS.learning_rate'], {}), True, 'import tensorflow as tf\n'), (146, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""keep_probabilty"""'}), True, 'import tensorflow as tf\n'), (147, 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, IMAGE_SIZE, IMAGE_SIZE, 3]', 'name': '"""input_image"""'}), True, 'import tensorflow as tf\n'), (150, 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None, IMAGE_SIZE, IMAGE_SIZE, 1]', 'name': '"""annotation"""'}), True, 'import tensorflow as tf\n'), (154, 'tensorflow.summary.image', 'tf.summary.image', (['"""input_image"""', 'image'], {'max_outputs': '(2)'}), True, 'import tensorflow as tf\n'), (167, 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""entropy"""', 'loss'], {}), True, 'import tensorflow as tf\n'), (169, 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), True, 'import tensorflow as tf\n'), (175, 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), True, 'import tensorflow as tf\n'), (178, 'read_MITSceneParsingData.read_dataset', 'scene_parsing.read_dataset', (['FLAGS.data_dir'], {}), True, 'import read_MITSceneParsingData as scene_parsing\n'), (186, 'BatchDatsetReader.BatchDatset', 'dataset.BatchDatset', (['valid_records', 'image_options'], {}), True, 'import BatchDatsetReader as dataset\n'), (188, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (191, 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['FLAGS.logs_dir'], {}), True, 'import tensorflow as tf\n'), (242, 'tensorflow.app.run', 'tf.app.run', ([], {}), True, 'import tensorflow as tf\n'), (84, 'tensorflow.variable_scope', 'tf.variable_scope', (['"""inference"""'], {}), True, 'import tensorflow as tf\n'), (88, 'TensorflowUtils.max_pool_2x2', 'utils.max_pool_2x2', (['conv_final_layer'], {}), True, 'import TensorflowUtils as utils\n'), (90, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[7, 7, 512, 4096]'], {'name': '"""W6"""'}), True, 'import TensorflowUtils as utils\n'), (91, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[4096]'], {'name': '"""b6"""'}), True, 'import TensorflowUtils as utils\n'), (92, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['pool5', 'W6', 'b6'], {}), True, 'import TensorflowUtils as utils\n'), (93, 'tensorflow.nn.relu', 'tf.nn.relu', (['conv6'], {'name': '"""relu6"""'}), True, 'import tensorflow as tf\n'), (96, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['relu6'], {'keep_prob': 'keep_prob'}), True, 'import tensorflow as tf\n'), (98, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[1, 1, 4096, 4096]'], {'name': '"""W7"""'}), True, 'import TensorflowUtils as utils\n'), (99, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[4096]'], {'name': '"""b7"""'}), True, 'import TensorflowUtils as utils\n'), (100, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['relu_dropout6', 'W7', 'b7'], {}), True, 'import TensorflowUtils as utils\n'), (101, 'tensorflow.nn.relu', 'tf.nn.relu', (['conv7'], {'name': '"""relu7"""'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.nn.dropout', 'tf.nn.dropout', (['relu7'], {'keep_prob': 'keep_prob'}), True, 'import tensorflow as tf\n'), (106, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[1, 1, 4096, NUM_OF_CLASSESS]'], {'name': '"""W8"""'}), True, 'import TensorflowUtils as utils\n'), (107, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[NUM_OF_CLASSESS]'], {'name': '"""b8"""'}), True, 'import TensorflowUtils as utils\n'), (108, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['relu_dropout7', 'W8', 'b8'], {}), True, 'import TensorflowUtils as utils\n'), (113, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[4, 4, deconv_shape1[3].value, NUM_OF_CLASSESS]'], {'name': '"""W_t1"""'}), True, 'import TensorflowUtils as utils\n'), (114, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[deconv_shape1[3].value]'], {'name': '"""b_t1"""'}), True, 'import TensorflowUtils as utils\n'), (116, 'tensorflow.add', 'tf.add', (['conv_t1', "image_net['pool4']"], {'name': '"""fuse_1"""'}), True, 'import tensorflow as tf\n'), (119, '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'), (120, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[deconv_shape2[3].value]'], {'name': '"""b_t2"""'}), True, 'import TensorflowUtils as utils\n'), (122, 'tensorflow.add', 'tf.add', (['conv_t2', "image_net['pool3']"], {'name': '"""fuse_2"""'}), True, 'import tensorflow as tf\n'), (124, 'tensorflow.shape', 'tf.shape', (['image'], {}), True, 'import tensorflow as tf\n'), (125, 'tensorflow.stack', 'tf.stack', (['[shape[0], shape[1], shape[2], NUM_OF_CLASSESS]'], {}), True, 'import tensorflow as tf\n'), (126, 'TensorflowUtils.weight_variable', 'utils.weight_variable', (['[16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value]'], {'name': '"""W_t3"""'}), True, 'import TensorflowUtils as utils\n'), (127, 'TensorflowUtils.bias_variable', 'utils.bias_variable', (['[NUM_OF_CLASSESS]'], {'name': '"""b_t3"""'}), True, 'import TensorflowUtils as utils\n'), (128, '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'), (130, 'tensorflow.argmax', 'tf.argmax', (['conv_t3'], {'dimension': '(3)', 'name': '"""prediction"""'}), True, 'import tensorflow as tf\n'), (132, 'tensorflow.expand_dims', 'tf.expand_dims', (['annotation_pred'], {'dim': '(3)'}), True, 'import tensorflow as tf\n'), (155, 'tensorflow.cast', 'tf.cast', (['annotation', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (156, 'tensorflow.cast', 'tf.cast', (['pred_annotation', 'tf.uint8'], {}), True, 'import tensorflow as tf\n'), (185, 'BatchDatsetReader.BatchDatset', 'dataset.BatchDatset', (['train_records', 'image_options'], {}), True, 'import BatchDatsetReader as dataset\n'), (195, 'os.path.join', 'osp.join', (['FLAGS.logs_dir', '"""train"""'], {}), True, 'import os.path as osp\n'), (196, 'os.path.join', 'osp.join', (['FLAGS.logs_dir', '"""validation"""'], {}), True, 'import os.path as osp\n'), (198, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (205, 'six.moves.xrange', 'xrange', (['MAX_ITERATION'], {}), False, 'from six.moves import xrange\n'), (55, 'TensorflowUtils.conv2d_basic', 'utils.conv2d_basic', (['current', 'kernels', 'bias'], {}), True, 'import TensorflowUtils as utils\n'), (95, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['relu6'], {}), True, 'import TensorflowUtils as utils\n'), (103, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['relu7'], {}), True, 'import TensorflowUtils as utils\n'), (141, 'TensorflowUtils.add_gradient_summary', 'utils.add_gradient_summary', (['grad', 'var'], {}), True, 'import TensorflowUtils as utils\n'), (171, 'TensorflowUtils.add_to_regularization_and_summary', 'utils.add_to_regularization_and_summary', (['var'], {}), True, 'import TensorflowUtils as utils\n'), (231, 'numpy.squeeze', 'np.squeeze', (['valid_annotations'], {'axis': '(3)'}), True, 'import numpy as np\n'), (232, 'numpy.squeeze', 'np.squeeze', (['pred'], {'axis': '(3)'}), True, 'import numpy as np\n'), (53, 'numpy.transpose', 'np.transpose', (['kernels', '(1, 0, 2, 3)'], {}), True, 'import numpy as np\n'), (57, 'tensorflow.nn.relu', 'tf.nn.relu', (['current'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (115, 'tensorflow.shape', 'tf.shape', (["image_net['pool4']"], {}), True, 'import tensorflow as tf\n'), (121, 'tensorflow.shape', 'tf.shape', (["image_net['pool3']"], {}), True, 'import tensorflow as tf\n'), (160, 'tensorflow.squeeze', 'tf.squeeze', (['annotation'], {'squeeze_dims': '[3]'}), True, 'import tensorflow as tf\n'), (59, 'TensorflowUtils.add_activation_summary', 'utils.add_activation_summary', (['current'], {}), True, 'import TensorflowUtils as utils\n'), (61, 'TensorflowUtils.avg_pool_2x2', 'utils.avg_pool_2x2', (['current'], {}), True, 'import TensorflowUtils as utils\n'), (220, 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), False, 'import datetime\n')]
larsmaaloee/BIVA
e47201113d779c6ea1245875714101b2bbfcbdae
import tensorflow as tf import warnings def conv2d(x, dim=(32, [3, 3], [1, 1]), pad='SAME', scope="conv2d", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): num_filters, filter_size, stride = dim with tf.variable_scope(scope): V = tf.get_variable('V', shape=list(filter_size) + [int(x.get_shape()[-1]), num_filters], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable('g', shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable('b', shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.nn.conv2d(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 2]), [1] + list(stride) + [1], pad) init_scale=.01 m_init, v_init = tf.nn.moments(x, [0,1,2]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]): x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters])) else: V = maybe_avg(V) g = maybe_avg(g) b = maybe_avg(b) # use weight normalization (Salimans & Kingma, 2016) W = tf.reshape(g, [1, 1, 1, num_filters]) * tf.nn.l2_normalize(V, [0, 1, 2]) # calculate convolutional layer output x = tf.nn.bias_add(tf.nn.conv2d(x, W, [1] + list(stride) + [1], pad), b) return x def gated_resnet(x, aux, dim=(32, [3, 3], [1, 1]), activation=tf.nn.elu, scope="gated_resnet", residual=True, dropout=.0, conv=conv2d, training=True, ema=None, init=False): out = conv(activation(x), [dim[0], dim[1], [1, 1]], scope="%s_conv_in"%scope, training=training, ema=ema, init=init) in_shp = x.get_shape().as_list() assert in_shp[1] == in_shp[2] if aux is not None: aux_shp = aux.get_shape().as_list() assert aux_shp[1] == aux_shp[2] if aux_shp[1:-1] > in_shp[1:-1]: aux = conv(activation(aux), [dim[0], dim[1], [aux_shp[1] // in_shp[1], aux_shp[2] // in_shp[2]]], scope="%s_conv_downsample_aux" % scope, training=training, ema=ema, init=init) elif aux_shp[1:-1] < in_shp[1:-1]: aux = deconv2d(activation(aux), [dim[0], dim[1], [in_shp[1] // aux_shp[1], in_shp[2] // aux_shp[2]]], scope="%s_conv_upsample_aux" % scope, training=training, ema=ema, init=init) else: aux = nin(activation(aux), dim[0], training=training, ema=ema, init=init, scope="%s_conv_aux" % scope) out += aux out = activation(out) if dropout > 0: out = tf.layers.dropout(out, rate=dropout, training=training) out = conv(out, [2*dim[0], dim[1], dim[2]], scope="%s_conv_out"%scope, training=training, ema=ema, init=init) h_stack1, h_stack2 = tf.split(out, 2, 3) sigmoid_out = tf.sigmoid(h_stack2) out = (h_stack1 * sigmoid_out) out_shp = out.get_shape().as_list() if out_shp[1:-1] < in_shp[1:-1]: x = tf.nn.avg_pool(x, [1, dim[2][0], dim[2][1], 1], strides=[1, dim[2][0], dim[2][1], 1], padding='SAME') elif out_shp[1:-1] > in_shp[1:-1]: warnings.warn("The height and width of the output are larger than the input. There will be no residual connection.") residual = False if out_shp[-1] > in_shp[-1]: x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [0, int(dim[0] - in_shp[-1])]]) elif out_shp[-1] < in_shp[-1]: warnings.warn("The input has more feature maps than the output. There will be no residual connection.") residual = False if residual: out += x return out def deconv2d(x, dim=(32, [3, 3], [1, 1]), pad='SAME', scope="deconv2d", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): num_filters, filter_size, stride = dim xs = x.get_shape().as_list() if pad=='SAME': target_shape = [tf.shape(x)[0], xs[1]*stride[0], xs[2]*stride[1], num_filters] else: target_shape = [tf.shape(x)[0], xs[1]*stride[0] + filter_size[0]-1, xs[2]*stride[1] + filter_size[1]-1, num_filters] with tf.variable_scope(scope): V = tf.get_variable("V", shape=list(filter_size) + [num_filters, int(x.get_shape()[-1])], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable("g", shape=[num_filters], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable("b", shape=[num_filters], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.nn.conv2d_transpose(x, tf.nn.l2_normalize(V.initialized_value(), [0, 1, 3]), target_shape, [1] + list(stride) + [1], padding=pad) init_scale = .01 m_init, v_init = tf.nn.moments(x, [0, 1, 2]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]): x = tf.reshape(scale_init, [1, 1, 1, num_filters]) * (x - tf.reshape(m_init, [1, 1, 1, num_filters])) else: V = maybe_avg(V) g = maybe_avg(g) b = maybe_avg(b) W = tf.reshape(g, [1, 1, num_filters, 1]) * tf.nn.l2_normalize(V, [0, 1, 3]) # calculate convolutional layer output x = tf.nn.conv2d_transpose(x, W, target_shape, [1] + list(stride) + [1], padding=pad) x = tf.nn.bias_add(x, b) return x def transposed_gated_resnet(x, aux, dim=(32, [3, 3], [1, 1]), activation=tf.nn.elu, scope="transposed_gated_resnet", residual=True, dropout=.0, conv=conv2d, training=True, ema=None, init=False): out = conv(activation(x), [dim[0], dim[1], [1, 1]], scope="%s_conv_in" % scope, training=training, ema=ema, init=init) in_shp = x.get_shape().as_list() assert in_shp[1] == in_shp[2] if aux is not None: aux_shp = aux.get_shape().as_list() assert aux_shp[1] == aux_shp[2] if aux_shp[1:-1] > in_shp[1:-1]: aux = conv(activation(aux), [dim[0], dim[1], [aux_shp[1] // in_shp[1], aux_shp[2] // in_shp[2]]], scope="%s_conv_downsample_aux" % scope, training=training, ema=ema, init=init) elif aux_shp[1:-1] < in_shp[1:-1]: aux = deconv2d(activation(aux), [dim[0], dim[1], [in_shp[1] // aux_shp[1], in_shp[2] // aux_shp[2]]], scope="%s_conv_upsample_aux" % scope, training=training, ema=ema, init=init) else: aux = nin(activation(aux), dim[0], training=training, ema=ema, init=init, scope="%s_conv_aux" % scope) out += aux out = activation(out) if dropout > 0: out = tf.layers.dropout(out, rate=dropout, training=training) if sum(dim[2]) > 2: out = deconv2d(out, [2*dim[0], dim[1], dim[2]], scope="%s_conv_out"%scope, training=training, ema=ema, init=init) else: out = conv2d(out, [2*dim[0], dim[1], dim[2]], scope="%s_conv_out"%scope, training=training, ema=ema, init=init) h_stack1, h_stack2 = tf.split(out, 2, 3) sigmoid_out = tf.sigmoid(h_stack2) out = (h_stack1 * sigmoid_out) out_shp = out.get_shape().as_list() if out_shp[1:-1] < in_shp[1:-1]: x = tf.nn.avg_pool(x, [1, dim[2][0], dim[2][1], 1], strides=[1, dim[2][0], dim[2][1], 1], padding='SAME') elif out_shp[1:-1] > in_shp[1:-1]: warnings.warn( "The height and width of the output are larger than the input. There will be no residual connection.") residual = False if out_shp[-1] > in_shp[-1]: x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [0, int(dim[0] - in_shp[-1])]]) elif out_shp[-1] < in_shp[-1]: warnings.warn("The input has more feature maps than the output. There will be no residual connection.") residual = False if residual: out += x return out def nin(x, num_units, **kwargs): s = tf.shape(x) sh = x.get_shape().as_list() x = tf.reshape(x, [tf.reduce_prod(s[:-1]), sh[-1]]) x = dense(x, num_units, **kwargs) return tf.reshape(x, [-1] + sh[1:-1] + [num_units]) def dense(x, num_units, scope="dense", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): with tf.variable_scope(scope): V = tf.get_variable('V', shape=[int(x.get_shape()[1]), num_units], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.05), trainable=True) g = tf.get_variable('g', shape=[num_units], dtype=tf.float32, initializer=tf.constant_initializer(1.), trainable=True) b = tf.get_variable('b', shape=[num_units], dtype=tf.float32, initializer=bias_initializer, trainable=True) def maybe_avg(v): if ema is not None and not init: v = tf.cond(training, lambda: v, lambda: ema.average(v)) return v if init: x = tf.matmul(x, tf.nn.l2_normalize(V.initialized_value(), 0)) init_scale = .01 m_init, v_init = tf.nn.moments(x, [0]) scale_init = init_scale / tf.sqrt(v_init + 1e-10) with tf.control_dependencies([g.assign(g * scale_init), b.assign_add(-m_init * scale_init)]): x = tf.reshape(scale_init, [1, num_units]) * (x - tf.reshape(m_init, [1, num_units])) else: V = maybe_avg(V) g = maybe_avg(g) b = maybe_avg(b) x = tf.matmul(x, V) scaler = g / tf.sqrt(tf.reduce_sum(tf.square(V), [0])) x = tf.reshape(scaler, [1, num_units]) * x + tf.reshape(b, [1, num_units]) return x def sample_from_discretized_mix_logistic(l, nr_mix): """ This function is copied from https://github.com/openai/pixel-cnn/blob/master/pixel_cnn_pp/nn.py in reference to: See [Salimans et. al., 2017](https://arxiv.org/pdf/1701.05517) ([pdf](https://arxiv.org/pdf/1701.05517.pdf)) log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to [-1,1] interval """ ls = [-1] + l.get_shape().as_list()[1:] xs = ls[:-1] + [3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = tf.reshape(l[:, :, :, nr_mix:], xs + [nr_mix * 3]) # sample mixture indicator from softmax sel = tf.one_hot(tf.argmax(logit_probs - tf.log(-tf.log(tf.random_uniform( tf.shape(logit_probs), minval=1e-5, maxval=1. - 1e-5))), 3), depth=nr_mix, dtype=tf.float32) sel = tf.reshape(sel, xs[:-1] + [1, nr_mix]) # select logistic parameters means = tf.reduce_sum(l[:, :, :, :, :nr_mix] * sel, 4) log_scales = tf.maximum(tf.reduce_sum( l[:, :, :, :, nr_mix:2 * nr_mix] * sel, 4), -7.) coeffs = tf.reduce_sum(tf.nn.tanh( l[:, :, :, :, 2 * nr_mix:3 * nr_mix]) * sel, 4) # sample from logistic & clip to interval # we don't actually round to the nearest 8bit value when sampling u = tf.random_uniform(tf.shape(means), minval=1e-5, maxval=1. - 1e-5) x = means + tf.exp(log_scales) * (tf.log(u) - tf.log(1. - u)) x0 = tf.minimum(tf.maximum(x[:, :, :, 0], -1.), 1.) x1 = tf.minimum(tf.maximum( x[:, :, :, 1] + coeffs[:, :, :, 0] * x0, -1.), 1.) x2 = tf.minimum(tf.maximum( x[:, :, :, 2] + coeffs[:, :, :, 1] * x0 + coeffs[:, :, :, 2] * x1, -1.), 1.) return tf.concat([tf.reshape(x0, xs[:-1] + [1]), tf.reshape(x1, xs[:-1] + [1]), tf.reshape(x2, xs[:-1] + [1])], 3)
[ "tensorflow.get_variable", "tensorflow.reduce_sum", "tensorflow.layers.dropout", "tensorflow.nn.moments", "tensorflow.square", "tensorflow.random_normal_initializer", "tensorflow.nn.l2_normalize", "tensorflow.matmul", "tensorflow.shape", "tensorflow.exp", "tensorflow.nn.tanh", "tensorflow.reduce_prod", "tensorflow.nn.avg_pool", "tensorflow.split", "tensorflow.nn.bias_add", "tensorflow.maximum", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.constant_initializer", "tensorflow.log", "tensorflow.variable_scope", "tensorflow.sqrt" ]
layers/_neural.py
[(6, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (70, 'tensorflow.split', 'tf.split', (['out', '(2)', '(3)'], {}), True, 'import tensorflow as tf\n'), (71, 'tensorflow.sigmoid', 'tf.sigmoid', (['h_stack2'], {}), True, 'import tensorflow as tf\n'), (93, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (165, 'tensorflow.split', 'tf.split', (['out', '(2)', '(3)'], {}), True, 'import tensorflow as tf\n'), (166, 'tensorflow.sigmoid', 'tf.sigmoid', (['h_stack2'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.reshape', 'tf.reshape', (['x', '([-1] + sh[1:-1] + [num_units])'], {}), True, 'import tensorflow as tf\n'), (199, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(0.0)'], {}), True, 'import tensorflow as tf\n'), (247, 'tensorflow.reshape', 'tf.reshape', (['l[:, :, :, nr_mix:]', '(xs + [nr_mix * 3])'], {}), True, 'import tensorflow as tf\n'), (251, 'tensorflow.reshape', 'tf.reshape', (['sel', '(xs[:-1] + [1, nr_mix])'], {}), True, 'import tensorflow as tf\n'), (253, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(l[:, :, :, :, :nr_mix] * sel)', '(4)'], {}), True, 'import tensorflow as tf\n'), (8, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (14, 'tensorflow.get_variable', 'tf.get_variable', (['"""b"""'], {'shape': '[num_filters]', 'dtype': 'tf.float32', 'initializer': 'bias_initializer', 'trainable': '(True)'}), True, 'import tensorflow as tf\n'), (67, 'tensorflow.layers.dropout', 'tf.layers.dropout', (['out'], {'rate': 'dropout', 'training': 'training'}), True, 'import tensorflow as tf\n'), (76, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['x', '[1, dim[2][0], dim[2][1], 1]'], {'strides': '[1, dim[2][0], dim[2][1], 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (102, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (105, 'tensorflow.get_variable', 'tf.get_variable', (['"""b"""'], {'shape': '[num_filters]', 'dtype': 'tf.float32', 'initializer': 'bias_initializer', 'trainable': '(True)'}), True, 'import tensorflow as tf\n'), (158, 'tensorflow.layers.dropout', 'tf.layers.dropout', (['out'], {'rate': 'dropout', 'training': 'training'}), True, 'import tensorflow as tf\n'), (171, 'tensorflow.nn.avg_pool', 'tf.nn.avg_pool', (['x', '[1, dim[2][0], dim[2][1], 1]'], {'strides': '[1, dim[2][0], dim[2][1], 1]', 'padding': '"""SAME"""'}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.variable_scope', 'tf.variable_scope', (['scope'], {}), True, 'import tensorflow as tf\n'), (205, 'tensorflow.get_variable', 'tf.get_variable', (['"""b"""'], {'shape': '[num_units]', 'dtype': 'tf.float32', 'initializer': 'bias_initializer', 'trainable': '(True)'}), True, 'import tensorflow as tf\n'), (254, 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(l[:, :, :, :, nr_mix:2 * nr_mix] * sel)', '(4)'], {}), True, 'import tensorflow as tf\n'), (260, 'tensorflow.shape', 'tf.shape', (['means'], {}), True, 'import tensorflow as tf\n'), (262, 'tensorflow.maximum', 'tf.maximum', (['x[:, :, :, (0)]', '(-1.0)'], {}), True, 'import tensorflow as tf\n'), (263, 'tensorflow.maximum', 'tf.maximum', (['(x[:, :, :, (1)] + coeffs[:, :, :, (0)] * x0)', '(-1.0)'], {}), True, 'import tensorflow as tf\n'), (265, 'tensorflow.maximum', 'tf.maximum', (['(x[:, :, :, (2)] + coeffs[:, :, :, (1)] * x0 + coeffs[:, :, :, (2)] * x1)', '(-1.0)'], {}), True, 'import tensorflow as tf\n'), (26, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[0, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (78, 'warnings.warn', 'warnings.warn', (['"""The height and width of the output are larger than the input. There will be no residual connection."""'], {}), False, 'import warnings\n'), (84, 'warnings.warn', 'warnings.warn', (['"""The input has more feature maps than the output. There will be no residual connection."""'], {}), False, 'import warnings\n'), (116, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[0, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (129, 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['x', 'b'], {}), True, 'import tensorflow as tf\n'), (173, 'warnings.warn', 'warnings.warn', (['"""The height and width of the output are larger than the input. There will be no residual connection."""'], {}), False, 'import warnings\n'), (182, 'warnings.warn', 'warnings.warn', (['"""The input has more feature maps than the output. There will be no residual connection."""'], {}), False, 'import warnings\n'), (194, 'tensorflow.reduce_prod', 'tf.reduce_prod', (['s[:-1]'], {}), True, 'import tensorflow as tf\n'), (217, 'tensorflow.nn.moments', 'tf.nn.moments', (['x', '[0]'], {}), True, 'import tensorflow as tf\n'), (227, 'tensorflow.matmul', 'tf.matmul', (['x', 'V'], {}), True, 'import tensorflow as tf\n'), (256, 'tensorflow.nn.tanh', 'tf.nn.tanh', (['l[:, :, :, :, 2 * nr_mix:3 * nr_mix]'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.exp', 'tf.exp', (['log_scales'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['x0', '(xs[:-1] + [1])'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['x1', '(xs[:-1] + [1])'], {}), True, 'import tensorflow as tf\n'), (267, 'tensorflow.reshape', 'tf.reshape', (['x2', '(xs[:-1] + [1])'], {}), True, 'import tensorflow as tf\n'), (10, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0)', '(0.05)'], {}), True, 'import tensorflow as tf\n'), (13, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (27, 'tensorflow.sqrt', 'tf.sqrt', (['(v_init + 1e-10)'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.reshape', 'tf.reshape', (['g', '[1, 1, 1, num_filters]'], {}), True, 'import tensorflow as tf\n'), (36, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['V', '[0, 1, 2]'], {}), True, 'import tensorflow as tf\n'), (98, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (100, 'tensorflow.shape', 'tf.shape', (['x'], {}), True, 'import tensorflow as tf\n'), (103, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0)', '(0.05)'], {}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (117, 'tensorflow.sqrt', 'tf.sqrt', (['(v_init + 1e-10)'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.reshape', 'tf.reshape', (['g', '[1, 1, num_filters, 1]'], {}), True, 'import tensorflow as tf\n'), (126, 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['V', '[0, 1, 3]'], {}), True, 'import tensorflow as tf\n'), (202, 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', (['(0)', '(0.05)'], {}), True, 'import tensorflow as tf\n'), (204, 'tensorflow.constant_initializer', 'tf.constant_initializer', (['(1.0)'], {}), True, 'import tensorflow as tf\n'), (218, 'tensorflow.sqrt', 'tf.sqrt', (['(v_init + 1e-10)'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.reshape', 'tf.reshape', (['b', '[1, num_units]'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.log', 'tf.log', (['u'], {}), True, 'import tensorflow as tf\n'), (261, 'tensorflow.log', 'tf.log', (['(1.0 - u)'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.reshape', 'tf.reshape', (['scale_init', '[1, 1, 1, num_filters]'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.reshape', 'tf.reshape', (['scale_init', '[1, 1, 1, num_filters]'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.reshape', 'tf.reshape', (['scale_init', '[1, num_units]'], {}), True, 'import tensorflow as tf\n'), (229, 'tensorflow.reshape', 'tf.reshape', (['scaler', '[1, num_units]'], {}), True, 'import tensorflow as tf\n'), (29, 'tensorflow.reshape', 'tf.reshape', (['m_init', '[1, 1, 1, num_filters]'], {}), True, 'import tensorflow as tf\n'), (119, 'tensorflow.reshape', 'tf.reshape', (['m_init', '[1, 1, 1, num_filters]'], {}), True, 'import tensorflow as tf\n'), (220, 'tensorflow.reshape', 'tf.reshape', (['m_init', '[1, num_units]'], {}), True, 'import tensorflow as tf\n'), (228, 'tensorflow.square', 'tf.square', (['V'], {}), True, 'import tensorflow as tf\n'), (250, 'tensorflow.shape', 'tf.shape', (['logit_probs'], {}), True, 'import tensorflow as tf\n')]
zhengknight/tensorpack
726747313fb2f189dd195d32087897b16a23be0a
# -*- coding: utf-8 -*- # File: optimizer.py import tensorflow as tf from contextlib import contextmanager from .gradproc import FilterNoneGrad, GradientProcessor __all__ = ['apply_grad_processors', 'ProxyOptimizer', 'PostProcessOptimizer', 'VariableAssignmentOptimizer', 'AccumGradOptimizer'] class ProxyOptimizer(tf.train.Optimizer): """ A transparent proxy which delegates all methods of :class:`tf.train.Optimizer` """ def __init__(self, opt, name='ProxyOptimizer'): assert isinstance(opt, tf.train.Optimizer), opt super(ProxyOptimizer, self).__init__(False, name) self._opt = opt def compute_gradients(self, *args, **kwargs): return self._opt.compute_gradients(*args, **kwargs) def get_slot(self, *args, **kwargs): return self._opt.get_slot(*args, **kwargs) def get_slot_names(self, *args, **kwargs): return self._opt.get_slot_names(*args, **kwargs) def apply_gradients(self, *args, **kwargs): return self._opt.apply_gradients(*args, **kwargs) def apply_grad_processors(opt, gradprocs): """ Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables. """ assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs) class PostProcessOptimizer(ProxyOptimizer): """ An optimizer which applies some "post-processing operation" per variable (e.g. clipping, quantization) after the gradient update. """ def __init__(self, opt, func, colocate=True): """ Args: opt (tf.train.Optimizer): func (tf.Variable -> tf.Operation or None): the operation needed to perform for this variable after the gradient update. colocate (boolean): colocate the function with the variable. """ super(PostProcessOptimizer, self).__init__(opt) self._func = func self._colocate = colocate def apply_gradients(self, grads_and_vars, global_step=None, name=None): update_op = super(PostProcessOptimizer, self).apply_gradients( grads_and_vars, global_step) ops = [] with tf.control_dependencies([update_op]): for _, var in grads_and_vars: with self._maybe_colocate(var): op = self._func(var) if op is not None: assert isinstance(op, tf.Operation), op ops.append(op) update_op = tf.group(update_op, *ops, name=name) return update_op @contextmanager def _maybe_colocate(self, var): G = tf.get_default_graph() if self._colocate: with G.colocate_with(var): yield else: yield class VariableAssignmentOptimizer(PostProcessOptimizer): """ An optimizer which assigns each variable a new value (e.g. clipping, quantization) after the gradient update. """ def __init__(self, opt, func): """ Args: opt (tf.train.Optimizer): func (tf.Variable -> tf.Tensor or None): the new value to be assigned to this variable after the gradient update. """ def f(v): t = func(v) if t is None: return t return tf.assign(v, t, use_locking=False).op super(VariableAssignmentOptimizer, self).__init__(opt, f) class AccumGradOptimizer(ProxyOptimizer): """ An optimizer which accumulates gradients across :math:`k` :meth:`minimize` calls, and apply them together in every :math:`k`th :meth:`minimize` call. This is roughly the same as using a :math:`k` times larger batch size plus a :math:`k` times larger learning rate, but uses much less memory. Note that this implementation may not support all models. E.g., it doesn't support sparse gradient update. """ def __init__(self, opt, niter): """ Args: opt (tf.train.Optimizer): the underlying sub-optimizer. niter (int): number of iterations to accumulate gradients. """ super(AccumGradOptimizer, self).__init__(opt, 'AccumGrad') self._niter = int(niter) def _create_accum_slots(self, var_list): slots = [] for v in var_list: # TODO an option to not colocate the accumulators with variables (to save more memory) s = self._zeros_slot(v, "accum", self._name) slots.append(s) return slots def apply_gradients(self, grads_and_vars, global_step=None, name=None): assert global_step is None, \ "AccumGradOptimizer doesn't support the option global_step! " \ "Please maintain it yourself." grads_and_vars = FilterNoneGrad().process(grads_and_vars) vs = [] for g, v in grads_and_vars: assert isinstance(g, tf.Tensor) and isinstance(v, tf.Variable), \ "AccumGradOptimizer only works for dense update! " \ "Types of v and g are {} and {}".format(type(v), type(g)) vs.append(v) with tf.control_dependencies(None): slots = self._create_accum_slots(vs) slots_and_vars = [(s, gv[1]) for s, gv in zip(slots, grads_and_vars)] # Create the counter on the same device as the first variable. with tf.variable_scope(self._name), \ vs[0].graph.colocate_with(vs[0]): counter = tf.Variable( 0, name="counter", trainable=False, dtype=tf.int32) with tf.name_scope('AccumGradOptimizer'): ops = [] for s, gv in zip(slots, grads_and_vars): g, v = gv ops.append(s.assign_add(g)) update_counter = tf.assign_add(counter, 1, name='update_counter') update_slot_op = tf.group(update_counter, *ops, name='update_slot') def update_grad(): update_op = self._opt.apply_gradients(slots_and_vars) with tf.control_dependencies([update_op]): clear_ops = [tf.assign(s, tf.zeros_like(s)) for s in slots] return tf.group(*clear_ops, name='update_grad') pred = tf.equal(tf.mod(counter, self._niter), 0) with tf.control_dependencies([update_slot_op]): if name is None: name = 'cond_update_grad' op = tf.cond(pred, update_grad, tf.no_op, name=name).op return op if __name__ == '__main__': # run it with "python -m tensorpack.tfutils.optimizer" x = tf.get_variable('x', shape=[6]) cost = tf.reduce_sum(tf.abs(x), name='cost') opt = tf.train.GradientDescentOptimizer(0.01) opt = AccumGradOptimizer(opt, 5) min_op = opt.minimize(cost) sess = tf.Session() sess.run(tf.global_variables_initializer()) with sess.as_default(): for k in range(20): min_op.run() print(x.eval())
[ "tensorflow.cond", "tensorflow.get_variable", "tensorflow.assign_add", "tensorflow.control_dependencies", "tensorflow.Variable", "tensorflow.assign", "tensorflow.mod", "tensorflow.global_variables_initializer", "tensorflow.zeros_like", "tensorflow.train.GradientDescentOptimizer", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.variable_scope", "tensorflow.get_default_graph", "tensorflow.group", "tensorflow.abs" ]
tensorpack/tfutils/optimizer.py
[(207, 'tensorflow.get_variable', 'tf.get_variable', (['"""x"""'], {'shape': '[6]'}), True, 'import tensorflow as tf\n'), (209, 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['(0.01)'], {}), True, 'import tensorflow as tf\n'), (213, 'tensorflow.Session', 'tf.Session', ([], {}), True, 'import tensorflow as tf\n'), (99, 'tensorflow.group', 'tf.group', (['update_op', '*ops'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (104, 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), True, 'import tensorflow as tf\n'), (208, 'tensorflow.abs', 'tf.abs', (['x'], {}), True, 'import tensorflow as tf\n'), (214, 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), True, 'import tensorflow as tf\n'), (92, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_op]'], {}), True, 'import tensorflow as tf\n'), (172, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['None'], {}), True, 'import tensorflow as tf\n'), (182, 'tensorflow.name_scope', 'tf.name_scope', (['"""AccumGradOptimizer"""'], {}), True, 'import tensorflow as tf\n'), (187, 'tensorflow.assign_add', 'tf.assign_add', (['counter', '(1)'], {'name': '"""update_counter"""'}), True, 'import tensorflow as tf\n'), (188, 'tensorflow.group', 'tf.group', (['update_counter', '*ops'], {'name': '"""update_slot"""'}), True, 'import tensorflow as tf\n'), (128, 'tensorflow.assign', 'tf.assign', (['v', 't'], {'use_locking': '(False)'}), True, 'import tensorflow as tf\n'), (177, 'tensorflow.variable_scope', 'tf.variable_scope', (['self._name'], {}), True, 'import tensorflow as tf\n'), (179, 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""counter"""', 'trainable': '(False)', 'dtype': 'tf.int32'}), True, 'import tensorflow as tf\n'), (194, 'tensorflow.group', 'tf.group', (['*clear_ops'], {'name': '"""update_grad"""'}), True, 'import tensorflow as tf\n'), (196, 'tensorflow.mod', 'tf.mod', (['counter', 'self._niter'], {}), True, 'import tensorflow as tf\n'), (197, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_slot_op]'], {}), True, 'import tensorflow as tf\n'), (192, 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[update_op]'], {}), True, 'import tensorflow as tf\n'), (200, 'tensorflow.cond', 'tf.cond', (['pred', 'update_grad', 'tf.no_op'], {'name': 'name'}), True, 'import tensorflow as tf\n'), (193, 'tensorflow.zeros_like', 'tf.zeros_like', (['s'], {}), True, 'import tensorflow as tf\n')]