repo
stringlengths 8
116
| tasks
stringlengths 8
117
| titles
stringlengths 17
302
| dependencies
stringlengths 5
372k
| readme
stringlengths 5
4.26k
| __index_level_0__
int64 0
4.36k
|
---|---|---|---|---|---|
inouetaka/CRAFT | ['scene text detection'] | ['Character Region Awareness for Text Detection'] | file_utils.py imgproc.py test.py craft.py basenet/vgg16_bn.py craft_utils.py basenet/__init__.py CRAFT double_conv warpCoord getDetBoxes_core getPoly_core adjustResultCoordinates getDetBoxes get_files list_files saveResult normalizeMeanVariance cvt2HeatmapImg resize_aspect_ratio loadImage denormalizeMeanVariance copyStateDict str2bool test_net init_weights vgg16_bn matmul threshold roll max clip connectedComponentsWithStats argmin MORPH_RECT shape append minAreaRect range astype copy sqrt dilate int uint8 getStructuringElement reshape boxPoints min zeros array warpCoord line arange zeros inv float32 reversed shape array getPerspectiveTransform append median warpPerspective range enumerate len getPoly_core getDetBoxes_core len array range len list_files join lower splitext append walk basename imwrite mkdir splitext array COLOR_GRAY2RGB imread array cvtColor astype float32 uint8 astype copy shape max zeros resize applyColorMap uint8 astype COLORMAP_JET OrderedDict join items startswith unsqueeze numpy getDetBoxes cuda show_time normalizeMeanVariance cvt2HeatmapImg permute range format resize_aspect_ratio hstack copy canvas_size net time Variable print adjustResultCoordinates len data isinstance fill_ Conv2d xavier_uniform_ normal_ zero_ BatchNorm2d Linear | # 論文 Englesh -> [Paper](https://arxiv.org/abs/1904.01941) 日本語 -> [CRAFT論文の日本語訳](https://github.com/inouetaka/CRAFT/wiki/論文-日本語訳) # 依存関係のインストール requirements * PyTorch>=0.4.1 * torchvision>=0.2.1 * opencv-python>=3.4.2 詳しい依存関係はrequirements.txtを確認 `pip install -r requirements.txt` | 2,400 |
insikk/delf_enhanced | ['image retrieval'] | ['Large-Scale Image Retrieval with Attentive Deep Local Features'] | object_detection/utils/test_utils_test.py object_detection/evaluator.py slim/preprocessing/cifarnet_preprocessing.py object_detection/box_coders/keypoint_box_coder_test.py object_detection/utils/variables_helper.py slim/datasets/dataset_utils.py slim/nets/inception_v1.py object_detection/box_coders/mean_stddev_box_coder_test.py slim/nets/inception_v4.py delf/python/feature_extractor_test.py object_detection/builders/matcher_builder.py object_detection/core/box_predictor_test.py object_detection/anchor_generators/grid_anchor_generator_test.py object_detection/core/minibatch_sampler_test.py slim/preprocessing/inception_preprocessing.py object_detection/utils/metrics.py object_detection/core/standard_fields.py object_detection/models/faster_rcnn_nas_feature_extractor_test.py slim/export_inference_graph.py object_detection/utils/np_box_ops_test.py object_detection/box_coders/mean_stddev_box_coder.py object_detection/exporter_test.py slim/nets/nasnet/nasnet_utils.py object_detection/builders/box_coder_builder_test.py object_detection/builders/region_similarity_calculator_builder_test.py delf/python/feature_extractor.py slim/nets/inception_utils.py object_detection/models/embedded_ssd_mobilenet_v1_feature_extractor_test.py slim/nets/nasnet/nasnet_utils_test.py object_detection/core/anchor_generator.py slim/nets/overfeat.py object_detection/meta_architectures/ssd_meta_arch.py object_detection/builders/model_builder_test.py object_detection/models/ssd_inception_v2_feature_extractor_test.py slim/nets/alexnet.py slim/nets/mobilenet_v1.py object_detection/trainer.py object_detection/builders/box_coder_builder.py object_detection/builders/anchor_generator_builder_test.py object_detection/core/region_similarity_calculator_test.py object_detection/utils/shape_utils.py delf/python/feature_io_test.py slim/download_and_convert_data.py object_detection/models/faster_rcnn_inception_v2_feature_extractor.py slim/nets/inception_v3_test.py object_detection/core/box_list_ops_test.py object_detection/core/balanced_positive_negative_sampler_test.py object_detection/models/faster_rcnn_resnet_v1_feature_extractor.py object_detection/create_pascal_tf_record_test.py object_detection/meta_architectures/faster_rcnn_meta_arch.py object_detection/core/data_decoder.py slim/nets/nets_factory.py object_detection/builders/hyperparams_builder.py setup.py slim/datasets/dataset_factory.py object_detection/builders/optimizer_builder_test.py slim/nets/cyclegan_test.py object_detection/builders/hyperparams_builder_test.py object_detection/builders/model_builder.py slim/deployment/model_deploy_test.py slim/nets/inception.py object_detection/models/embedded_ssd_mobilenet_v1_feature_extractor.py delf/python/delf_v1.py object_detection/models/faster_rcnn_inception_resnet_v2_feature_extractor.py slim/nets/lenet.py object_detection/utils/variables_helper_test.py slim/nets/inception_v3.py slim/nets/inception_v4_test.py object_detection/models/faster_rcnn_nas_feature_extractor.py slim/datasets/mnist.py object_detection/box_coders/faster_rcnn_box_coder_test.py object_detection/core/box_list.py object_detection/meta_architectures/rfcn_meta_arch.py slim/preprocessing/preprocessing_factory.py delf/python/datum_io_test.py object_detection/builders/anchor_generator_builder.py object_detection/models/ssd_inception_v3_feature_extractor.py object_detection/builders/preprocessor_builder.py delf/python/datum_io.py object_detection/core/prefetcher.py object_detection/eval_util.py object_detection/box_coders/faster_rcnn_box_coder.py slim/nets/pix2pix_test.py slim/nets/nasnet/nasnet_test.py object_detection/builders/optimizer_builder.py object_detection/builders/post_processing_builder.py object_detection/exporter.py slim/nets/inception_resnet_v2.py object_detection/utils/label_map_util.py slim/nets/inception_resnet_v2_test.py object_detection/meta_architectures/faster_rcnn_meta_arch_test.py slim/datasets/download_and_convert_cifar10.py object_detection/matchers/bipartite_matcher_test.py object_detection/utils/visualization_utils.py object_detection/builders/losses_builder.py object_detection/utils/learning_schedules_test.py object_detection/models/feature_map_generators_test.py slim/nets/nets_factory_test.py slim/nets/alexnet_test.py object_detection/core/balanced_positive_negative_sampler.py object_detection/models/ssd_feature_extractor_test.py object_detection/utils/dataset_util_test.py object_detection/utils/static_shape.py object_detection/utils/visualization_utils_test.py slim/preprocessing/lenet_preprocessing.py slim/nets/nasnet/nasnet.py slim/nets/resnet_v2.py slim/datasets/cifar10.py slim/datasets/build_imagenet_data.py object_detection/models/ssd_mobilenet_v1_feature_extractor.py object_detection/core/losses_test.py slim/train_image_classifier.py object_detection/core/keypoint_ops_test.py object_detection/meta_architectures/faster_rcnn_meta_arch_test_lib.py slim/export_inference_graph_test.py object_detection/anchor_generators/multiple_grid_anchor_generator_test.py slim/nets/resnet_v1.py object_detection/utils/test_utils.py object_detection/core/keypoint_ops.py slim/nets/resnet_utils.py object_detection/utils/np_box_list_test.py object_detection/core/data_parser.py object_detection/utils/object_detection_evaluation_test.py object_detection/core/preprocessor.py object_detection/builders/matcher_builder_test.py delf/examples/extract_features.py object_detection/utils/ops.py object_detection/models/faster_rcnn_inception_resnet_v2_feature_extractor_test.py slim/datasets/process_bounding_boxes.py slim/nets/inception_v2.py object_detection/core/model.py object_detection/train.py object_detection/utils/config_util_test.py object_detection/utils/np_box_list.py object_detection/core/matcher_test.py object_detection/core/region_similarity_calculator.py object_detection/box_coders/square_box_coder.py object_detection/builders/preprocessor_builder_test.py object_detection/anchor_generators/grid_anchor_generator.py slim/setup.py slim/datasets/imagenet.py object_detection/core/batcher_test.py slim/eval_image_classifier.py object_detection/core/box_coder_test.py object_detection/core/matcher.py object_detection/core/target_assigner.py slim/deployment/model_deploy.py object_detection/matchers/bipartite_matcher.py slim/nets/resnet_v1_test.py object_detection/utils/ops_test.py object_detection/utils/config_util.py object_detection/utils/per_image_evaluation.py object_detection/box_coders/square_box_coder_test.py slim/nets/overfeat_test.py slim/nets/cifarnet.py slim/nets/dcgan_test.py slim/datasets/download_and_convert_mnist.py object_detection/anchor_generators/multiple_grid_anchor_generator.py object_detection/utils/category_util.py object_detection/create_pet_tf_record.py object_detection/utils/category_util_test.py object_detection/data_decoders/tf_example_decoder.py object_detection/models/ssd_inception_v3_feature_extractor_test.py object_detection/models/feature_map_generators.py object_detection/builders/box_predictor_builder_test.py object_detection/create_pascal_tf_record.py object_detection/builders/box_predictor_builder.py object_detection/core/box_list_ops.py object_detection/models/faster_rcnn_inception_v2_feature_extractor_test.py object_detection/utils/static_shape_test.py object_detection/utils/shape_utils_test.py object_detection/eval.py object_detection/utils/per_image_evaluation_test.py object_detection/meta_architectures/rfcn_meta_arch_test.py object_detection/matchers/argmax_matcher_test.py object_detection/utils/np_box_ops.py object_detection/builders/region_similarity_calculator_builder.py object_detection/core/losses.py object_detection/builders/input_reader_builder_test.py object_detection/core/post_processing_test.py object_detection/core/target_assigner_test.py object_detection/matchers/argmax_matcher.py slim/nets/cyclegan.py slim/nets/inception_v1_test.py object_detection/utils/metrics_test.py slim/nets/dcgan.py object_detection/utils/learning_schedules.py object_detection/utils/np_box_list_ops.py object_detection/builders/post_processing_builder_test.py delf/examples/match_images.py slim/datasets/flowers.py object_detection/core/box_coder.py object_detection/models/ssd_mobilenet_v1_feature_extractor_test.py object_detection/utils/object_detection_evaluation.py object_detection/data_decoders/tf_example_decoder_test.py object_detection/core/prefetcher_test.py object_detection/core/box_list_test.py object_detection/utils/np_box_list_ops_test.py object_detection/meta_architectures/ssd_meta_arch_test.py object_detection/core/preprocessor_test.py slim/nets/mobilenet_v1_test.py object_detection/utils/dataset_util.py slim/nets/inception_v2_test.py slim/preprocessing/vgg_preprocessing.py object_detection/builders/losses_builder_test.py slim/datasets/preprocess_imagenet_validation_data.py object_detection/builders/image_resizer_builder.py object_detection/trainer_test.py object_detection/utils/label_map_util_test.py object_detection/core/minibatch_sampler.py delf/python/feature_io.py object_detection/export_inference_graph.py slim/nets/pix2pix.py slim/nets/vgg_test.py object_detection/core/post_processing.py object_detection/box_coders/keypoint_box_coder.py object_detection/builders/input_reader_builder.py object_detection/core/box_predictor.py object_detection/models/faster_rcnn_resnet_v1_feature_extractor_test.py object_detection/models/ssd_inception_v2_feature_extractor.py slim/datasets/download_and_convert_flowers.py slim/nets/resnet_v2_test.py slim/nets/vgg.py object_detection/core/batcher.py delf/__init__.py object_detection/builders/image_resizer_builder_test.py get_feature_from_path InferenceHelper batch_get_feature main _ReadImageList get_ransac_image_byte read_image get_inliers main load_image_into_numpy_array get_attention_image_byte SerializeToString ParseFromString ArrayToDatum WriteToFile ReadFromFile DatumToArray DatumIoTest DelfV1 CalculateKeypointCenters NormalizePixelValues ExtractKeypointDescriptor DelfFeaturePostProcessing CalculateReceptiveBoxes ApplyPcaAndWhitening BuildModel FeatureExtractorTest ArraysToDelfFeatures SerializeToString ParseFromString WriteToFile DelfFeaturesToArrays ReadFromFile create_data DelfFeaturesIoTest main dict_to_tf_example DictToTFExampleTest main create_tf_record dict_to_tf_example get_class_name_from_filename main _extract_prediction_tensors get_evaluators evaluate visualize_detection_results repeated_checkpoint_run result_dict_for_single_example _run_checkpoint_once write_metrics _image_tensor_input_placeholder _encoded_image_string_tensor_input_placeholder _add_output_tensor_nodes _tf_example_input_placeholder _write_saved_model _write_graph_and_checkpoint freeze_graph_with_def_protos replace_variable_values_with_moving_averages _write_frozen_graph _export_inference_graph export_inference_graph ExportInferenceGraphTest FakeModel main main create_input_queue get_inputs train _create_losses TrainerTest FakeDetectionModel get_input_function GridAnchorGenerator tile_anchors _center_size_bbox_to_corners_bbox GridAnchorGeneratorTest create_ssd_anchors MultipleGridAnchorGenerator MultipleGridAnchorGeneratorTest CreateSSDAnchorsTest FasterRcnnBoxCoder FasterRcnnBoxCoderTest KeypointBoxCoder KeypointBoxCoderTest MeanStddevBoxCoder MeanStddevBoxCoderTest SquareBoxCoder SquareBoxCoderTest build AnchorGeneratorBuilderTest build BoxCoderBuilderTest build MaskRCNNBoxPredictorBuilderTest ConvolutionalBoxPredictorBuilderTest RfcnBoxPredictorBuilderTest _build_batch_norm_params _build_regularizer build _build_initializer _build_activation_fn HyperparamsBuilderTest build _tf_resize_method ImageResizerBuilderTest build InputReaderBuilderTest _build_localization_loss build_faster_rcnn_classification_loss _build_classification_loss build build_hard_example_miner FasterRcnnClassificationLossBuilderTest LocalizationLossBuilderTest HardExampleMinerBuilderTest LossBuilderTest ClassificationLossBuilderTest build MatcherBuilderTest _build_faster_rcnn_model build _build_ssd_model _build_ssd_feature_extractor _build_faster_rcnn_feature_extractor ModelBuilderTest _create_learning_rate build OptimizerBuilderTest LearningRateBuilderTest _score_converter_fn_with_logit_scale _build_non_max_suppressor _build_score_converter build PostProcessingBuilderTest _get_dict_from_proto build _get_step_config_from_proto PreprocessorBuilderTest build RegionSimilarityCalculatorBuilderTest clip_to_window flip_vertical flip_horizontal change_coordinate_frame prune_outside_window scale to_normalized_coordinates rot90 to_absolute_coordinates AnchorGenerator BalancedPositiveNegativeSampler BalancedPositiveNegativeSamplerTest BatchQueue BatcherTest BoxCoder batch_decode MockBoxCoder BoxCoderTest BoxList pad_or_clip_box_list refine_boxes_multi_class area boolean_mask prune_outside_window prune_non_overlapping_boxes visualize_boxes_in_image gather box_voting sq_dist sort_by_field _copy_extra_fields intersection to_normalized_coordinates non_max_suppression concatenate matched_intersection SortOrder ioa scale height_width prune_small_boxes filter_field_value_equals to_absolute_coordinates clip_to_window iou refine_boxes matched_iou prune_completely_outside_window filter_greater_than change_coordinate_frame BoxRefinementTest ConcatenateTest BoxListOpsTest CoordinatesConversionTest NonMaxSuppressionTest BoxListTest ConvolutionalBoxPredictor MaskRCNNBoxPredictor RfcnBoxPredictor BoxPredictor RfcnBoxPredictorTest ConvolutionalBoxPredictorTest MaskRCNNBoxPredictorTest DataDecoder DataToNumpyParser KeypointOpsTest SigmoidFocalClassificationLoss BootstrappedSigmoidClassificationLoss WeightedSoftmaxClassificationLoss WeightedSigmoidClassificationLoss Loss HardExampleMiner WeightedIOULocalizationLoss WeightedSmoothL1LocalizationLoss WeightedL2LocalizationLoss SigmoidFocalClassificationLossTest BootstrappedSigmoidClassificationLossTest WeightedL2LocalizationLossTest WeightedIOULocalizationLossTest _logit WeightedSigmoidClassificationLossTest WeightedSoftmaxClassificationLossTest WeightedSmoothL1LocalizationLossTest HardExampleMinerTest Match Matcher AnchorMatcherTest MinibatchSampler MinibatchSamplerTest DetectionModel batch_multiclass_non_max_suppression multiclass_non_max_suppression MulticlassNonMaxSuppressionTest prefetch PrefetcherTest one_hot_encoding random_rotation90 get_default_func_arg_map random_black_patches image_to_float ssd_random_crop_fixed_aspect_ratio random_adjust_brightness resize_image _random_integer random_vertical_flip _rot90_masks scale_boxes_to_pixel_coordinates _apply_with_random_selector normalize_image _flip_masks_left_right subtract_channel_mean rgb_to_gray resize_to_min_dimension random_crop_image random_rgb_to_gray random_adjust_hue retain_boxes_above_threshold random_horizontal_flip random_resize_method _flip_boxes_up_down _flip_boxes_left_right _strict_random_crop_image random_adjust_saturation resize_to_range random_image_scale random_distort_color preprocess random_pixel_value_scale random_crop_to_aspect_ratio _compute_new_dynamic_size ssd_random_crop ssd_random_crop_pad random_pad_to_aspect_ratio _compute_new_static_size _rot90_boxes random_adjust_contrast ssd_random_crop_pad_fixed_aspect_ratio random_pad_image _flip_masks_up_down random_crop_pad_image random_jitter_boxes _apply_with_random_selector_tuples PreprocessorTest NegSqDistSimilarity RegionSimilarityCalculator IoaSimilarity IouSimilarity RegionSimilarityCalculatorTest DetectionResultFields BoxListFields InputDataFields TfExampleFields TargetAssigner batch_assign_targets create_target_assigner BatchTargetAssignerTest TargetAssignerTest CreateTargetAssignerTest TfExampleDecoder TfExampleDecoderTest ArgMaxMatcher ArgMaxMatcherTest GreedyBipartiteMatcher GreedyBipartiteMatcherTest FasterRCNNMetaArch FasterRCNNFeatureExtractor FasterRCNNMetaArchTest FasterRCNNMetaArchTestBase FakeFasterRCNNFeatureExtractor RFCNMetaArch RFCNMetaArchTest SSDFeatureExtractor SSDMetaArch MockAnchorGenerator2x2 FakeSSDFeatureExtractor SsdMetaArchTest EmbeddedSSDMobileNetV1FeatureExtractor EmbeddedSSDMobileNetV1FeatureExtractorTest FasterRCNNInceptionResnetV2FeatureExtractor FasterRcnnInceptionResnetV2FeatureExtractorTest _batch_norm_arg_scope FasterRCNNInceptionV2FeatureExtractor FasterRcnnInceptionV2FeatureExtractorTest nasnet_large_arg_scope_for_detection FasterRCNNNASFeatureExtractor _build_nasnet_base FasterRcnnNASFeatureExtractorTest FasterRCNNResnet50FeatureExtractor FasterRCNNResnet152FeatureExtractor FasterRCNNResnetV1FeatureExtractor FasterRCNNResnet101FeatureExtractor FasterRcnnResnetV1FeatureExtractorTest multi_resolution_feature_maps get_depth_fn GetDepthFunctionTest MultiResolutionFeatureMapGeneratorTest SsdFeatureExtractorTestBase SSDInceptionV2FeatureExtractor SsdInceptionV2FeatureExtractorTest SSDInceptionV3FeatureExtractor SsdInceptionV3FeatureExtractorTest SSDMobileNetV1FeatureExtractor SsdMobilenetV1FeatureExtractorTest AddExtraFieldTest BoxListTest load_categories_from_csv_file save_categories_to_csv_file EvalUtilTest _update_initial_learning_rate _update_label_map_path get_number_of_classes get_configs_from_multiple_files create_pipeline_proto_from_configs get_configs_from_pipeline_file _update_batch_size _update_focal_loss_gamma _update_eval_steps _update_focal_loss_alpha get_optimizer_type _update_input_path _update_classification_localization_weight_ratio _update_train_steps merge_external_params_with_configs _update_momentum_optimizer_value get_learning_rate_type _get_classification_loss ConfigUtilTest _update_optimizer_with_constant_learning_rate _update_optimizer_with_exponential_decay_learning_rate _update_optimizer_with_manual_step_learning_rate _write_config recursive_parse_xml_to_dict int64_list_feature read_examples_list float_list_feature int64_feature bytes_feature bytes_list_feature DatasetUtilTest create_category_index_from_labelmap create_category_index create_class_agnostic_category_index _validate_label_map get_label_map_dict convert_label_map_to_categories load_labelmap LabelMapUtilTest manual_stepping cosine_decay_with_warmup exponential_decay_with_burnin LearningSchedulesTest compute_average_precision compute_cor_loc compute_precision_recall MetricsTest BoxList multi_class_non_max_suppression sort_by_field iou clip_to_window _update_valid_indices_by_removing_high_iou_boxes concatenate filter_scores_greater_than _copy_extra_fields area SortOrder ioa change_coordinate_frame prune_non_overlapping_boxes prune_outside_window scale intersection gather non_max_suppression GatherOpsTest AreaRelatedTest NonMaximumSuppressionTest SortByFieldTest iou area ioa intersection BoxOpsTests OpenImagesDetectionEvaluator WeightedPascalDetectionEvaluator DetectionEvaluator ObjectDetectionEvaluator ObjectDetectionEvaluation PascalDetectionEvaluator ObjectDetectionEvaluationTest OpenImagesV2EvaluationTest PascalEvaluationTest WeightedPascalEvaluationTest reframe_box_masks_to_image_masks pad_to_multiple expanded_shape normalized_to_image_coordinates retain_groundtruth_with_positive_classes filter_groundtruth_with_nan_box_coordinates position_sensitive_crop_regions padded_one_hot_encoding filter_groundtruth_with_crowd_boxes normalize_to_target retain_groundtruth replace_nan_groundtruth_label_scores_with_ones merge_boxes_with_multiple_labels indices_to_dense_vector meshgrid dense_to_sparse_boxes GroundtruthFilterTest NormalizedToImageCoordinatesTest OpsTestPaddedOneHotEncoding GroundtruthFilterWithNanBoxTest MeshgridTest RetainGroundTruthWithPositiveClasses ReframeBoxMasksToImageMasksTest OpsTestPositionSensitiveCropRegions ReplaceNaNGroundtruthLabelScoresWithOnes OpsTestIndicesToDenseVector OpsDenseToSparseBoxesTest GroundtruthFilterWithCrowdBoxesTest OpsTestNormalizeToTarget MergeBoxesWithMultipleLabelsTest OpsTestPadToMultiple PerImageEvaluation SingleClassTpFpWithGroupOfBoxesTest SingleClassTpFpNoDifficultBoxesTest CorLocTest SingleClassTpFpWithDifficultBoxesTest MultiClassesTpFpTest combined_static_and_dynamic_shape pad_or_clip_tensor _set_dim_0 clip_tensor _is_tensor pad_tensor UtilTest get_batch_size get_height get_width get_depth StaticShapeTest MockBoxCoder create_random_boxes MockMatcher MockAnchorGenerator create_diagonal_gradient_image MockBoxPredictor TestUtilsTest filter_variables freeze_gradients_matching_regex get_variables_available_in_checkpoint multiply_gradients_matching_regex GetVariablesAvailableInCheckpointTest FilterVariablesTest MultiplyGradientsMatchingRegexTest FreezeGradientsMatchingRegexTest draw_bounding_boxes_on_image_array add_cdf_image_summary draw_bounding_boxes_on_image_tensors save_image_array_as_png encode_image_array_as_png_str draw_mask_on_image_array draw_bounding_box_on_image_array draw_bounding_box_on_image draw_bounding_boxes_on_image draw_keypoints_on_image draw_keypoints_on_image_array visualize_boxes_and_labels_on_image_array VisualizationUtilsTest main main main ExportInferenceGraphTest _configure_learning_rate _configure_optimizer _get_init_fn main _get_variables_to_train ImageCoder _convert_to_example _process_image_files _process_image _int64_feature _process_dataset _is_cmyk _find_image_files _build_bounding_box_lookup _find_human_readable_labels _build_synset_lookup _find_image_bounding_boxes _bytes_feature _float_feature main _process_image_files_batch _is_png get_split get_dataset download_and_uncompress_tarball image_to_tfexample write_label_file int64_feature bytes_feature float_feature read_label_file has_labels _add_to_tfrecord _download_and_uncompress_dataset _get_output_filename _clean_up_temporary_files run _dataset_exists _convert_dataset run _clean_up_temporary_files _get_filenames_and_classes _get_dataset_filename ImageReader _add_to_tfrecord _extract_labels _get_output_filename _download_dataset _extract_images _clean_up_temporary_files run get_split get_split create_readable_names_for_imagenet_labels get_split BoundingBox FindNumberBoundingBoxes GetInt ProcessXMLAnnotation GetItem _gather_clone_loss deploy _add_gradients_summaries _optimize_clone create_clones optimize_clones DeploymentConfig _sum_clones_gradients DeploymentConfigTest DeployTest OptimizeclonesTest BatchNormClassifier CreatecloneTest LogisticClassifier InceptionV3Test alexnet_v2 alexnet_v2_arg_scope AlexnetV2Test cifarnet_arg_scope cifarnet cyclegan_upsample cyclegan_arg_scope _dynamic_or_static_shape cyclegan_generator_resnet CycleganTest _validate_image_inputs discriminator generator DCGANTest inception_resnet_v2_arg_scope inception_resnet_v2 inception_resnet_v2_base block8 block35 block17 InceptionTest inception_arg_scope inception_v1_base inception_v1 InceptionV1Test inception_v2_base _reduced_kernel_size_for_small_input inception_v2 InceptionV2Test inception_v3 _reduced_kernel_size_for_small_input inception_v3_base inception_v4 block_reduction_b inception_v4_base block_inception_b block_inception_c block_reduction_a block_inception_a InceptionTest lenet lenet_arg_scope mobilenet_v1_arg_scope mobilenet_v1 _reduced_kernel_size_for_small_input mobilenet_v1_base wrapped_partial MobilenetV1Test get_network_fn NetworksTest overfeat overfeat_arg_scope OverFeatTest Block pix2pix_generator upsample pix2pix_discriminator pix2pix_arg_scope _default_generator_blocks DiscriminatorTest GeneratorTest Block conv2d_same subsample resnet_arg_scope stack_blocks_dense resnet_v1_152 resnet_v1_101 bottleneck resnet_v1_200 resnet_v1_50 resnet_v1 resnet_v1_block ResnetUtilsTest ResnetCompleteNetworkTest create_test_input resnet_v2_50 resnet_v2_200 resnet_v2_101 resnet_v2_block resnet_v2_152 bottleneck resnet_v2 ResnetUtilsTest ResnetCompleteNetworkTest create_test_input vgg_16 vgg_arg_scope vgg_a vgg_19 VGG16Test VGGATest VGG19Test build_nasnet_cifar nasnet_mobile_arg_scope _mobile_imagenet_config _build_aux_head build_nasnet_mobile nasnet_large_arg_scope _large_imagenet_config _imagenet_stem build_nasnet_large _cifar_stem nasnet_cifar_arg_scope _build_nasnet_base _cifar_config NASNetTest _operation_to_num_layers _operation_to_info _pooling global_avg_pool _operation_to_filter_shape _operation_to_pooling_shape calc_reduction_layers drop_path NasNetABaseCell _operation_to_pooling_type _operation_to_pooling_info get_channel_dim NasNetANormalCell factorized_reduction NasNetAReductionCell _stacked_separable_conv get_channel_index NasnetUtilsTest preprocess_image preprocess_for_train preprocess_for_eval distorted_bounding_box_crop preprocess_for_train preprocess_for_eval preprocess_image distort_color apply_with_random_selector preprocess_image get_preprocessing _aspect_preserving_resize preprocess_for_train _crop _central_crop _smallest_size_at_least _mean_image_subtraction preprocess_for_eval preprocess_image _random_crop DelfConfig set_verbosity info INFO len DelfConfig makedirs set_verbosity info INFO len list_images_path batch_get_feature output_dir info _ReadImageList config_path size convert astype uint8 cKDTree query array ransac fromarray uint8 BytesIO astype dstack save subplots plot_matches axis DMatch column_stack COLOR_BGR2RGB transformed getvalue KeyPoint savefig get_inliers append sum inverted close BytesIO drawMatches tostring cvtColor get_ransac_image_byte image_1_path features_2_path features_1_path set_verbosity image_2_path imread output_image ReadFromFile INFO shape flat extend DatumProto ArrayToDatum DatumProto SerializeToString to_float div subtract to_float reshape concat stack meshgrid range to_float minimum constant add_field NormalizePixelValues _ProcessSingleScale while_loop resize_bilinear model_fn BoxList shape num_boxes gather expand_dims zeros non_max_suppression slice subtract divide matmul sqrt CalculateKeypointCenters CopyFrom add ArrayToDatum zeros range DelfFeatures len descriptor y feature len orientation strength scale zeros range x DatumToArray ArraysToDelfFeatures DelfFeatures ones reshape arange zeros join int BytesIO encode float Example append bool hexdigest open join dict_to_tf_example TFRecordWriter data_dir annotations_dir fromstring write read_examples_list SerializeToString set close label_map_path ignore_difficult_instances get_label_map_dict output_path enumerate len match I get_class_name_from_filename join dict_to_tf_example TFRecordWriter fromstring write SerializeToString close warning info enumerate len seed int shuffle create_tf_record checkpoint_dir pipeline_config_path partial get_configs_from_multiple_files get_configs_from_pipeline_file eval_dir evaluate build Copy run_once MakeDirs convert_label_map_to_categories max load_labelmap to_float postprocess dequeue preprocess prefetch expand_dims create_input_dict_fn predict metrics_set get_or_create_global_step global_variables use_moving_averages _extract_prediction_tensors repeated_checkpoint_run Saver fatal ExponentialMovingAverage create_model_fn append variables_to_restore sorted info close FileWriter add_summary Summary get join format Summary save_image_array_as_png create_category_index squeeze close FileWriter int32 info add_summary visualize_boxes_and_labels_on_image_array restore write_graph restore_fn latest_checkpoint graph_def close tables_initializer Saver global_variables_initializer Session local_variables_initializer run time latest_checkpoint strftime gmtime _run_checkpoint_once write_metrics info sleep get reframe_box_masks_to_image_masks ones_like to_float update to_int64 greater BoxList shape InputDataFields scale DetectionResultFields to_absolute_coordinates node placeholder string placeholder placeholder get add_to_collection identity node len info node _add_output_tensor_nodes Saver to_float list name _write_graph_and_checkpoint NamedTemporaryFile _write_saved_model freeze_graph_with_def_protos get_default_graph _write_frozen_graph predict postprocess get_or_create_global_step preprocess MakeDirs keys join as_saver_def replace_variable_values_with_moving_averages use_moving_averages model _export_inference_graph build input_shape trained_checkpoint_prefix output_directory TrainEvalPipelineConfig input_type export_inference_graph Server target loads train_dir get ClusterSpec num_clones type index clone_on_cpu train to_float BatchQueue create_tensor_dict_fn preprocess expand_dims dequeue list num_classes values get_inputs concat merge_multiple_label_boxes any add_loss create_model_fn loss predict provide_groundtruth create_model_fn constant random_uniform to_float reshape sqrt stack meshgrid range _center_size_bbox_to_corners_bbox list constant zip append range ssd_anchor_generator grid_anchor_generator MaskRCNNBoxPredictor RfcnBoxPredictor conv_hyperparams HasField mask_rcnn_box_predictor ConvolutionalBoxPredictor rfcn_box_predictor WhichOneof convolutional_box_predictor argscope_fn fc_hyperparams batch_norm _build_batch_norm_params WhichOneof name WhichOneof keep_aspect_ratio_resizer resize_method fixed_shape_resizer _tf_resize_method tf_record_input_reader TfExampleDecoder parallel_read label_map_path _build_localization_loss _build_classification_loss localization_loss hard_example_miner classification_loss localization_weight build_hard_example_miner classification_weight max_negatives_per_positive num_hard_examples HardExampleMiner WhichOneof weighted_softmax weighted_sigmoid weighted_l2 WhichOneof weighted_smooth_l1 weighted_softmax HasField weighted_sigmoid_focal WhichOneof alpha weighted_sigmoid bootstrapped_sigmoid argmax_matcher unmatched_threshold matched_threshold depth_multiplier pad_to_multiple conv_hyperparams build min_depth batch_norm_trainable type matcher num_classes normalize_loss_by_num_matches build feature_extractor box_coder post_processing _build_ssd_feature_extractor similarity_calculator anchor_generator loss box_predictor image_resizer batch_norm_trainable type first_stage_features_stride build_faster_rcnn_classification_loss first_stage_objectness_loss_weight HasField second_stage_localization_loss_weight second_stage_mask_prediction_loss_weight first_stage_atrous_rate first_stage_minibatch_size second_stage_post_processing first_stage_nms_iou_threshold num_classes first_stage_positive_balance_fraction second_stage_box_predictor first_stage_box_predictor_kernel_size hard_example_miner build second_stage_classification_loss_weight first_stage_only second_stage_batch_size maxpool_kernel_size _build_faster_rcnn_feature_extractor initial_crop_size second_stage_classification_loss first_stage_box_predictor_conv_hyperparams second_stage_balance_fraction build_hard_example_miner RfcnBoxPredictor isinstance maxpool_stride first_stage_box_predictor_depth feature_extractor first_stage_nms_score_threshold first_stage_anchor_generator first_stage_localization_loss_weight first_stage_max_proposals image_resizer learning_rate momentum_optimizer MomentumOptimizer adam_optimizer MovingAverageOptimizer AdamOptimizer _create_learning_rate use_moving_average RMSPropOptimizer rms_prop_optimizer decay_factor total_steps exponential_decay initial_learning_rate manual_stepping cosine_decay_with_warmup decay_steps warmup_learning_rate add get_or_create_global_step WhichOneof exponential_decay_learning_rate constant_learning_rate learning_rate warmup_steps manual_step_learning_rate learning_rate_base cosine_decay_learning_rate scalar score_converter batch_non_max_suppression logit_scale _build_non_max_suppressor _build_score_converter batch_multiclass_non_max_suppression partial __name__ ListFields ListFields ssd_random_crop_fixed_aspect_ratio resize_image random_vertical_flip operations max_padded_size_ratio _get_step_config_from_proto random_crop_image min_padded_size_ratio random_resize_method random_horizontal_flip ssd_random_crop ssd_random_crop_pad ssd_random_crop_pad_fixed_aspect_ratio random_pad_image random_crop_pad_image _get_dict_from_proto pad_color assert_has_rank stack get_field get_extra_fields add_field append range filter_field_value_equals refine_boxes non_max_suppression to_float get add_field iou greater_equal _copy_extra_fields reshape greater reduce_sum Assert matmul BoxList get_field expand_dims reduce_all value to_float list add_queue_runner size PaddingFIFOQueue enqueue QueueRunner keys scalar random_uniform tuple func random_uniform append range len subtract concat split subtract concat split subtract concat split transpose strict_random_crop_image_fn greater random_uniform append cond to_float pad_to_bounding_box ones_like get maximum BoxList shape reduce_mean stack change_coordinate_frame cond to_float random_pad_image to_int32 shape stack random_crop_image _apply_with_random_selector as_list int min float round max to_float minimum constant to_int32 maximum shape stack round cond BoxList get append scale tuple _apply_with_random_selector_tuples random_crop_to_aspect_ratio ssd_random_crop len list insert tuple ssd_random_crop random_pad_to_aspect_ratio groundtruth_keypoints groundtruth_label_scores groundtruth_instance_masks squeeze get_default_func_arg_map func zip expand_dims ArgMaxMatcher NegSqDistSimilarity IouSimilarity GreedyBipartiteMatcher MeanStddevBoxCoder FasterRcnnBoxCoder assign stack zip append len batch_norm nasnet_large_arg_scope num_cells reduction_cell calc_reduction_layers skip_reduction_layer_input normal_cell num_reduction_layers append range format conv2d get_depth_fn append depth_fn enumerate separable_conv2d sort train_config model train_input_reader eval_config eval_input_reader TrainEvalPipelineConfig CopyFrom TrainEvalPipelineConfig TrainConfig EvalConfig InputReader DetectionModel WhichOneof update _update_initial_learning_rate list _update_label_map_path items _update_batch_size _update_focal_loss_gamma _update_focal_loss_alpha _update_input_path _update_classification_localization_weight_ratio info _update_momentum_optimizer_value _update_train_steps _update_eval_steps values momentum_optimizer initial_learning_rate manual_step_learning_rate float adam_optimizer schedule get_optimizer_type get_learning_rate_type exponential_decay_learning_rate constant_learning_rate rms_prop_optimizer int round max momentum_optimizer min get_optimizer_type max rms_prop_optimizer faster_rcnn WhichOneof ssd ssd second_stage_classification_loss classification_loss WhichOneof faster_rcnn WhichOneof _get_classification_loss WhichOneof _get_classification_loss int int ClearField isinstance extend WhichOneof append MessageToString constant_learning_rate exponential_decay_learning_rate manual_step_learning_rate range add append item name id display_name item info append range _validate_label_map item id load_labelmap max convert_label_map_to_categories load_labelmap exponential_decay cos float32 pi cast less float cond constant reshape concat float32 where greater int64 any reduce_min argsort cumsum astype concatenate maximum sum range len get_coordinates add_field get_extra_fields size BoxList get_field get_field argsort get sort_by_field arange iou filter_scores_greater_than squeeze logical_and num_boxes append expand_dims full range get add_field sort_by_field zeros_like filter_scores_greater_than concatenate reshape BoxList num_boxes get_field range append non_max_suppression get add_field array_split get_extra_fields hstack BoxList get_field get array_split _copy_extra_fields hstack area astype BoxList fmax int32 fmin greater_equal ioa gather array amax get array_split reshape hstack where logical_not max add_field get_extra_fields BoxList shape vstack get_field astype int32 BoxList get _copy_extra_fields scale max minimum transpose maximum shape zeros split expand_dims area intersection expand_dims area intersection map_fn to_float get_shape int float to_int32 concat get_depth ceil get_width get_batch_size zeros get_height greater size cond constant slice concat reduce_sum stack set_shape ones to_int32 ones_like as_list reshape maximum gather greater where retain_groundtruth logical_not where is_nan to_int32 greater logical_not reduce_sum where squeeze len stack reduce_mean unstack add_n crop_and_resize zip append batch_to_space_nd range depth_to_space split transform_boxes_relative_to_boxes expand_dims crop_and_resize concat reshape py_func as_list set_shape concat greater shape rank _set_dim_0 expand_dims cond gather _set_dim_0 range greater _set_dim_0 cond as_list shape append enumerate assert_has_rank assert_has_rank assert_has_rank assert_has_rank expand_dims arange range concatenate minimum zeros uniform maximum name match append filter_variables name info filter_variables name info items list NewCheckpointReader sorted isinstance warning keys convert fromarray uint8 BytesIO close getvalue save convert array draw_bounding_box_on_image copyto truetype line Draw text size rectangle ceil getsize sum fromarray array draw_bounding_boxes_on_image copyto shape range draw_bounding_box_on_image partial map_fn draw_keypoints_on_image convert array copyto ellipse Draw tuple size zip fromarray ones_like list getrgb reshape convert logical_and any copyto expand_dims composite array int list defaultdict format items tuple draw_mask_on_image_array tolist min extend draw_bounding_box_on_image_array append draw_keypoints_on_image_array range uint8 image py_func dataset_dir run int sync_replicas num_epochs_per_decay batch_size MomentumOptimizer AdagradOptimizer GradientDescentOptimizer AdamOptimizer RMSPropOptimizer AdadeltaOptimizer FtrlOptimizer checkpoint_path latest_checkpoint get_model_variables checkpoint_exclude_scopes IsDirectory startswith info append train_dir extend get_collection TRAINABLE_VARIABLES Example read print _is_cmyk cmyk_to_rgb png_to_jpeg _is_png decode_jpeg int join _convert_to_example arange _process_image TFRecordWriter print astype write SerializeToString close output_directory range flush len int ImageCoder Thread join print astype Coordinator start append range flush len seed list print Glob extend shuffle range len append append basename print _process_image_files _find_image_files _find_human_readable_labels _find_image_bounding_boxes labels_file readlines split print readlines append float split _process_dataset imagenet_metadata_file print train_directory _build_bounding_box_lookup validation_directory _build_synset_lookup train_shards bounding_box_file validation_shards join TFRecordReader TFExampleDecoder read_label_file has_labels join urlretrieve print extractall stat join join index split reshape join urlretrieve print extractall stat join Remove DeleteRecursively download_and_uncompress_tarball list print _get_output_filename write_label_file dict MakeDirs zip _clean_up_temporary_files range len append join listdir isdir int write ceil float flush len _get_dataset_filename range seed shuffle _dataset_exists _convert_dataset _get_filenames_and_classes print print _extract_images _extract_labels print join urlretrieve _download_dataset format urlretrieve readlines len split create_readable_names_for_imagenet_labels write_label_file iter BoundingBox parse height ymin FindNumberBoundingBoxes min ymax xmin xmax GetInt getroot width append float max range GetItem scope scalar _gather_clone_loss REGULARIZATION_LOSSES get_collection add_n _sum_clones_gradients len SUMMARIES get_collection set scope create_clones UPDATE_OPS append add_n zip global_norm isinstance name IndexedSlices histogram info append values l2_regularizer constant_value shape as_list array assert_is_fully_defined assert_has_rank _validate_image_inputs batch_norm int assert_has_rank log batch_norm batch_norm as_list prediction_fn as_list partial update_wrapper l2_regularizer truncated_normal_initializer hasattr default_image_size shape conv2d_transpose conv2d resize_nearest_neighbor as_list list partial reverse len pad variance_scaling_initializer l2_regularizer variance_scaling_initializer l2_regularizer variance_scaling_initializer l2_regularizer int stem_cell batch_norm conv2d append stem_multiplier range filter_scaling_rate int batch_norm conv2d num_conv_filters stem_multiplier drop_path_keep_prob num_cells total_training_steps transpose NasNetANormalCell NasNetAReductionCell info num_conv_filters _cifar_config drop_path_keep_prob num_cells _mobile_imagenet_config total_training_steps transpose NasNetANormalCell NasNetAReductionCell info num_conv_filters drop_path_keep_prob num_cells total_training_steps transpose _large_imagenet_config NasNetANormalCell NasNetAReductionCell info num_conv_filters format relu _build_aux_head stem add_and_check_endpoint index append int float range int batch_norm concat conv2d avg_pool div floor int split split _operation_to_num_layers _operation_to_filter_shape _operation_to_info batch_norm relu range separable_conv2d split split _operation_to_pooling_type _operation_to_pooling_shape avg_pool2d _operation_to_pooling_info max_pool2d to_float random_crop random_flip_left_right random_brightness pad image random_contrast expand_dims to_float resize_image_with_crop_or_pad expand_dims image random_uniform to_float resize_image_with_crop_or_pad div subtract greater_equal to_int32 logical_and Assert shape stack rank equal greater_equal logical_and extend Assert rank random_uniform append range equal len append _crop range split convert_to_tensor to_float to_int32 greater cond convert_to_tensor resize_bilinear squeeze shape set_shape _smallest_size_at_least expand_dims _aspect_preserving_resize set_shape random_uniform set_shape _aspect_preserving_resize | # DELF: DEep Local Features This project is wrapper of [DELF Tensorflow code](https://github.com/tensorflow/models/tree/master/research/delf) (introduced in the paper ["Large-Scale Image Retrieval with Attentive Deep Local Features"](https://arxiv.org/abs/1612.06321)) which is more easy to use for below reasons: * No bell and whistle for setup. All required packages are prepared. * Modularized code. You can easily import as python package from any of your fantastic project. * Get Local Descriptors from any image * Get Attention Image, so you can see why the DELFs are selected * Get Matching Image, so you can see why the image pair has high score * You also can load weight on a model build with its code. | 2,401 |
inspire-group/compactness-robustness | ['network pruning'] | ['HYDRA: Pruning Adversarially Robust Neural Networks'] | utils/logging.py models/resnet_cifar.py trainer/adv.py trainer/crown-ibp.py utils/eval.py data/svhn.py utils/misc.py models/wrn_cifar.py train.py data/__init__.py args.py utils/schedules.py data/imagenet.py models/__init__.py trainer/mixtrain.py utils/adv.py models/layers.py crown/bound_layers.py trainer/base.py models/basic.py symbolic_interval/interval.py locuslab_smoothing/analyze.py crown/eps_scheduler.py utils/semisup.py utils/smoothing.py utils/model.py models/vgg_cifar.py trainer/freeadv.py trainer/smooth.py symbolic_interval/symbolic_network.py train_imagenet.py crown/converter.py data/cifar.py eval_smoothing.py symbolic_interval/__init__.py models/resnet.py parse_args main main BoundSequential BoundDataParallel BoundFlatten BoundReLU BoundConv2d BoundLinear main EpsilonScheduler CIFAR100 CIFAR10 imagenet SVHN markdown_table_certified_accuracy ApproximateAccuracy HighProbAccuracy smallplot_certified_accuracy latex_table_certified_accuracy Accuracy Line plot_certified_accuracy lin_3 cifar_model_large lin_2 vgg4_without_maxpool DenseSequential cifar_model_resnet cifar_model Dense mnist_model lin_1 mnist_model_large lin_4 Flatten GetSubnet SubnetLinear SubnetConv conv1x1 ResNet ResNet18 Bottleneck ResNet34 conv3x3 ResNet50 BasicBlock ResNet resnet50 Bottleneck resnet152 test resnet34 resnet18 BasicBlock resnet101 initialize_weights vgg2 vgg6_bn vgg8 vgg11_bn vgg4 vgg4_bn VGG vgg13 vgg16_bn vgg6 vgg2_bn vgg8_bn vgg11 make_layers vgg13_bn vgg16 wrn_28_10 wrn_28_1 wrn_28_4 WideResNet wrn_40_2 wrn_34_10 NetworkBlock BasicBlock Center_symbolic_interval Symbolic_interval_proj1 gen_sym Inverse_interval Symbolic_interval_proj2 Symbolic_interval Interval mix_interval Interval_Conv2d Interval_BN Interval_ReLU inverse_interval_analyze gen_interval_analyze Interval_network Interval_Bound mix_interval_analyze center_symbolic_interval_analyze sym_interval_analyze naive_interval_analyze Interval_Dense Interval_SubConv Interval_Flatten Interval_SubLinear train train train train train set_interval_weight set_epsilon train pgd_whitebox l2_norm trades_loss trades_loss_hot_vector fgsm squared_l2_norm mixtrain accuracy smooth freeadv base get_output_for_batch ibp adv trim_preceding_hyphens create_subdirs AverageMeter argv_to_vars save_checkpoint ProgressMeter parse_configs_file write_to_file arg_to_varname clone_results_to_latest_subdir xe_with_one_hot CustomDatasetFromNumpy initialize_scaled_score scale_rand_init subnet_to_dense snip_init initialize_scores dense_to_subnet freeze_vars prepare_model show_gradients get_layers current_model_pruned_fraction unfreeze_vars sanity_check_paramter_updates set_prune_rate_model step_schedule new_lr get_lr_policy cosine_schedule get_optimizer constant_schedule get_semisup_dataloader Smooth eval_quick_smoothing quick_smoothing add_argument ArgumentParser getLogger exp_mode save_checkpoint Path device parse_configs_file dataset tr_train max exists exp_name get_optimizer seed scaled_score_init basicConfig scale_rand_init addHandler val_method lr_policy k prepare_model show_gradients getattr load_state_dict warmup_epochs parse_args to CrossEntropyLoss range state_dict manual_seed_all create_subdirs SummaryWriter format initialize_scaled_score snip_init val trainer get_semisup_dataloader start_epoch warmup_lr lr import_module resume info manual_seed data_loaders current_model_pruned_fraction sanity_check_paramter_updates FileHandler load join deepcopy evaluate result_dir print makedirs source_net get_layers isfile train epochs clone_results_to_latest_subdir is_semisup layer_type len ceil n_repeats int load_config config_modelloader_and_convert2mlp arange plot at_radii xlabel plot_fmt close ylabel tight_layout ylim scale_x savefig figure legend title tick_params xlim set_major_locator arange plot at_radii xlabel plot_fmt close ylabel tight_layout MultipleLocator ylim savefig figure legend tick_params xlim format arange at_radii write close legend zeros enumerate open format arange at_radii len write close legend zeros range enumerate open Sequential Flatten Linear Sequential Flatten Linear Sequential Flatten Linear Sequential Flatten Linear linear_layer Sequential ReLU conv_layer Flatten linear_layer Sequential ReLU conv_layer Flatten isinstance linear_layer Sequential out_channels Conv2d normal_ sqrt modules zero_ ReLU conv_layer Flatten isinstance linear_layer Sequential out_channels Conv2d normal_ sqrt modules zero_ ReLU conv_layer Flatten isinstance block DenseSequential extend out_channels Conv2d normal_ sqrt modules zero_ range isinstance linear_layer Sequential out_channels Conv2d normal_ sqrt modules zero_ ReLU conv_layer Flatten randn print size Conv2d resnet18 net Linear kaiming_uniform_ isinstance fill_ print in_features in_channels Conv2d sign normal_ sqrt weight bias modules zero_ BatchNorm2d kaiming_normal_ constant_ Linear conv_layer initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG initialize_weights make_layers VGG Tensor type item size item Tensor type item Tensor type item size item size item model zero_grad write_to_tensorboard display trades_loss update size item add_image enumerate time make_grid backward print AverageMeter accuracy ProgressMeter step len numpy format criterion get_eps batch_size schedule_length unsqueeze starting_epsilon scatter EpsilonScheduler to range LongTensor schedule_start zeros epsilon clamp_ div_ grad n_repeats fgsm Tensor schedule_length starting_epsilon epsilon interval_weight schedule_length max min sym_interval_analyze mixtraink set_epsilon randint set_interval_weight noise_std log_softmax softmax beta view data KLDivLoss sub_ renorm_ model add_ zero_grad SGD sign div_ max view criterion_kl range detach log_softmax randn_like requires_grad_ eval softmax norm backward Variable clamp min natural_criterion any train step len data KLDivLoss sub_ renorm_ model add_ zero_grad SGD sign div_ max view criterion_kl range cross_entropy detach log_softmax randn_like requires_grad_ eval softmax norm backward Variable clamp min any train step len data backward Variable clamp zero_grad SGD sign to range len eval AverageMeter ProgressMeter len eval AverageMeter ProgressMeter len eval AverageMeter ProgressMeter len eval AverageMeter ProgressMeter len eval AverageMeter ProgressMeter model clamp_ div_ max write_to_tensorboard step_size display to range num_steps format eval add_image enumerate time make_grid criterion print Variable AverageMeter clone min ProgressMeter fgsm Tensor epsilon len subnet_to_dense join copyfile k save join mkdir copy_tree mkdir trim_preceding_hyphens replace append arg_to_varname load update read argv print argv_to_vars getattr sum len named_modules hasattr named_modules hasattr named_modules set_prune_rate hasattr print named_parameters data hasattr criterion model print backward abs zero_grad k freeze_vars modules unfreeze_vars popup_scores kaiming_normal_ set_prune_rate_model enumerate kaiming_uniform_ hasattr print xavier_uniform_ modules xavier_normal_ popup_scores kaiming_normal_ data hasattr print _calculate_correct_fan sqrt modules popup_scores abs max data isinstance print sqrt modules initialize_scores print k freeze_vars freeze_bn scores_init_type unfreeze_vars set_prune_rate_model items list int sort clone numel flatten abs load_state_dict named_modules join isinstance print size numpy append sum exists cpu named_modules print exit Adam RMSprop SGD parameters param_groups print DataLoader CustomDatasetFromNumpy to quick_smoothing print enumerate sum ppf view astype mean to numpy max cat | # HYDRA: Pruning Adversarially Robust Neural Networks (NeurIPS 2020) Repository with code to reproduce the results and checkpoints for compressed networks in [our paper on novel pruning techniques with robust training](https://arxiv.org/abs/2002.10509). This repository supports all four robust training objectives: iterative adversarial training, randomized smoothing, MixTrain, and CROWN-IBP. Following is a snippet of key results where we showed that accounting the robust training objective in pruning strategy can lead to large gains in the robustness of pruned networks.  In particular, the improvement arises from letting the robust training objective controlling which connections to prune. In almost all cases, it prefers to pruned certain high-magnitude weights while preserving other small magnitude weights, which is orthogonal to the strategy in well-established least-weight magnitude (LWM) based pruning.  ## Updates **April 30, 2020**: [Checkpoints for WRN-28-10](https://www.dropbox.com/sh/56yyfy16elwbnr8/AADmr7bXgFkrNdoHjKWwIFKqa?dl=0), a common network for benchmarking adv. robustness | 90% pruned with proposed technique | Benign test accuracy = 88.97% , PGD-50 test accuracy = 62.24%. **May 23, 2020**: Our WRN-28-10 network with 90% connection pruning comes in the second place in the [auto-attack robustness benchmark](https://github.com/fra31/auto-attack). ## Getting started | 2,402 |
intact-project/LungNet | ['semantic segmentation'] | ['Semantic Segmentation of Pathological Lung Tissue with Dilated Fully Convolutional Networks'] | custom_metrics.py train.py custom_layers.py LungNet.py test.py get_fmd_db.py BatchNormalization Softmax4D waccOA loss wcceOA entrONA download_and_unzip_from_url conv_block bn_block get_model sample_generator int read chr print extractall len write close urlopen info ZipFile open bn_block conv_block loss waccOA bn_block Model wcceOA entrONA append Input range compile len list permutation product squeeze len | # LungNet This is supplementary material for the manuscript: >"Semantic Segmentation of Pathological Lung Tissue with Dilated Fully Convolutional Networks" M. Anthimopoulos, S. Christodoulidis, L. Ebner, A. Christe and S. Mougiakakou IEEE Journal of Biomedical and Health infomatics (2018) https://arxiv.org/abs/1803.06167 In case of any questions, please do not hesitate to contact us. ### Environment: A `Dockerfile` is provided with all the necessary environment configurations. In order to build and run it you may use the following commands: ``` | 2,403 |
intel-isl/Intseg | ['interactive segmentation', 'semantic segmentation'] | ['Interactive Image Segmentation With Latent Diversity', 'Deep Interactive Object Selection'] | our_func_cvpr18.py IntSeg_GUI.py IntSeg_Train.py main Example lrelu get_weight_bias identity_initializer nm prepare_data build build_vgg19 build_net lrelu get_weight_bias our_func identity_initializer nm build compIoU build_vgg19 build_net Tk mainloop Example Variable reshape size constant get_weight_bias reuse_variables loadmat build_net build_vgg19 concat conv2d range sum imwrite Saver Session run restore ones placeholder build shape initialize_all_variables imread expand_dims concatenate get_checkpoint_state distance_transform_edt minimum deepcopy uint8 float32 maximum model_checkpoint_path int32 circle makedirs | intel-isl/Intseg | 2,404 |
intel-isl/MiDaS | ['depth estimation', 'monocular depth estimation', 'semantic segmentation'] | ['Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer', 'Vision Transformers for Dense Prediction'] | tf/run_onnx.py tf/run_pb.py hubconf.py tf/transforms.py ros/midas_cpp/scripts/talker.py run.py midas/dpt_depth.py midas/midas_net.py midas/midas_net_custom.py tf/make_onnx_model.py midas/blocks.py midas/vit.py utils.py ros/midas_cpp/scripts/listener.py midas/base_model.py ros/midas_cpp/scripts/listener_original.py mobile/android/models/src/main/assets/run_tflite.py tf/utils.py midas/transforms.py MiDaS MiDaS_small DPT_Hybrid DPT_Large transforms run write_depth read_pfm write_pfm resize_image resize_depth read_image BaseModel _make_efficientnet_backbone ResidualConvUnit Interpolate _make_pretrained_efficientnet_lite3 _make_encoder _make_resnet_backbone _make_scratch _make_pretrained_resnext101_wsl FeatureFusionBlock_custom ResidualConvUnit_custom FeatureFusionBlock DPTDepthModel _make_fusion_block DPT MidasNet fuse_model MidasNet_small Resize NormalizeImage apply_min_size PrepareForNet _make_pretrained_vitb_rn50_384 _make_pretrained_vitb16_384 get_readout_oper Transpose AddReadout forward_vit _resize_pos_embed _make_pretrained_vitl16_384 _make_pretrained_deitb16_384 _make_pretrained_deitb16_distil_384 _make_vit_b_rn50_backbone get_activation _make_vit_b16_backbone ProjectReadout forward_flex Slice main video_show main video_show talker run MidasNet_preprocessing modify_file restore_file run run Resize NormalizeImage apply_min_size PrepareForNet write_depth write_pfm read_image DPTDepthModel load_state_dict_from_url load_state_dict DPTDepthModel load_state_dict_from_url load_state_dict load_state_dict_from_url MidasNet load_state_dict load_state_dict_from_url load_state_dict MidasNet_small Compose NormalizeImage join format write_depth print DPTDepthModel glob Compose makedirs half eval MidasNet MidasNet_small device to read_image enumerate len imread COLOR_GRAY2BGR cvtColor COLOR_BGR2RGB float unsqueeze astype resize to numpy resize imwrite min astype float32 shape write_pfm zeros max _make_pretrained_vitb_rn50_384 _make_pretrained_vitb16_384 print _make_pretrained_efficientnet_lite3 _make_pretrained_vitl16_384 _make_scratch _make_pretrained_resnext101_wsl Module Conv2d load bn1 Module Sequential conv_stem act1 bn1 layer1 Module relu maxpool Sequential layer3 layer4 layer2 conv1 load named_modules type fuse_modules Identity list tuple astype float32 shape resize ceil max Unflatten unflatten Size Sequential shape forward_flex int reshape sqrt permute interpolate cat len norm blocks hasattr isinstance _resize_pos_embed transpose pos_embed expand shape blk backbone pos_drop patch_embed cat len Unflatten get_readout_oper Module Transpose Size register_forward_hook Sequential model MethodType Conv2d get_activation ConvTranspose2d create_model create_model create_model create_model Unflatten get_readout_oper Module Transpose Size register_forward_hook Sequential model MethodType Conv2d get_activation Identity ConvTranspose2d create_model init_node spin video_show destroyAllWindows VideoCapture Rate CvBridge read get_param cv2_to_imgmsg print init_node Publisher loginfo sleep publish replace copyfile copyfile MidasNet_preprocessing float32 export zeros compose2 PrepareForNet name reshape Resize InferenceSession resize get_operations GraphDef set_virtual_device_configuration list_physical_devices | ## Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer This repository contains code to compute depth from a single image. It accompanies our [paper](https://arxiv.org/abs/1907.01341v3): >Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer René Ranftl, Katrin Lasinger, David Hafner, Konrad Schindler, Vladlen Koltun and our [preprint](https://arxiv.org/abs/2103.13413): > Vision Transformers for Dense Prediction > René Ranftl, Alexey Bochkovskiy, Vladlen Koltun MiDaS was trained on 10 datasets (ReDWeb, DIML, Movies, MegaDepth, WSVD, TartanAir, HRWSI, ApolloScape, BlendedMVS, IRS) with multi-objective optimization. The original model that was trained on 5 datasets (`MIX 5` in the paper) can be found [here](https://github.com/isl-org/MiDaS/releases/tag/v2). | 2,405 |
inyukwo1/Coarse2fine_boilerplate | ['semantic parsing'] | ['Coarse-to-Fine Decoding for Neural Semantic Parsing'] | table/IO.py main.py table/__init__.py join_dicts __setstate__ merge_vocabs OrderedIterator TableDataset __getstate__ read_anno_json update defaultdict stoi sum Counter | # CoarseToFineBoilerplate This is a boilerplate for implementing CoarseToFine. (L Dong, Coarse-to-Fine Decoding for Neural Semantic Parsing, 2018 https://arxiv.org/pdf/1805.04793.pdf) Implementing CoarseToFine aims to practice pytorch and NLP. ## How to do it 1. Fork or make your branch for this project. 1. Read CoarseToFine paper carefully (https://arxiv.org/pdf/1805.04793.pdf). 2. Download python3.5 (https://www.python.org/downloads/release/python-352/). This project only can be run at python 3.5. 3. Make virtualenv (example shell commands are in below). 4. Install requirements (example shell commands are in below). 5. See main.py and see how to load dataset. I recommend you to run train.py first and see how ```batch``` looks like in line 32 and 35. | 2,406 |
inzva/Audio-Style-Transfer | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | mital/style.py ulyanov/style.py read_audio_spectum load angle stft log1p abs | inzva/Audio-Style-Transfer | 2,407 |
ioanabica/Time-Series-Deconfounder | ['causal inference', 'time series'] | ['Time Series Deconfounder: Estimating Treatment Effects over Time in the Presence of Hidden Confounders'] | utils/evaluation_utils.py utils/rnn_utils.py time_series_deconfounder.py factor_model.py rmsn/script_rnn_fit.py simulated_autoregressive.py rmsn/script_propensity_generation.py rmsn/script_rnn_test.py rmsn/libs/net_helpers.py rmsn/configs.py rmsn/core_routines.py rmsn/libs/model_rnn.py main_time_series_deconfounder.py utils/predictive_checks_utils.py FactorModel init_arg AutoregressiveSimulation train_factor_model get_dataset_splits train_rmsn test_time_series_deconfounder get_parameters_from_string load_optimal_parameters get_processed_data convert_to_tf_dataset train test propensity_generation rnn_fit rnn_test RnnModel StateDumpingRNN Seq2SeqDecoderCell randomise_minibatch_index reshape_for_sklearn add_hyperparameter_results create_folder_if_not_exist linear get_optimization_graph hyperparameter_result_exists load_hyperparameter_results calc_binary_cross_entropy save_network load_network last_relevant_time_slice write_results_to_file append_results_to_file compute_test_statistic_all_timesteps compute_predictive_checks_eval_metric AutoregressiveLSTMCell last_relevant compute_sequence_length add_argument ArgumentParser compute_hidden_confounders format eval_network write_results_to_file copy choice dict shape info FactorModel train range dict shape str join propensity_generation rnn_test print mean rmtree sqrt mkdir rnn_fit train_factor_model str basicConfig format train_rmsn write_results_to_file print get_dataset_splits ShuffleSplit info next split int float split join list replace print min load_hyperparameter_results index get_parameters_from_string array max reset_default_graph reset_default_graph from_tensor_slices int concatenate print copy shape zeros array range percentile join basicConfig format load_optimal_parameters concatenate ones shape save cumprod ConfigProto range load join basicConfig format columns T train choice info get_processed_data ConfigProto len join basicConfig get_mse_at_follow_up_time to_csv test get_processed_data ConfigProto makedirs as_list int min shuffle append range len trainable_variables list gradients clip_by_global_norm apply_gradients zip optimisation_function get_shape int subtract reshape gather range join format to_csv Saver save join restore format set Saver read_csv join Series min to_csv load_hyperparameter_results copy dropna empty join exists columns load_hyperparameter_results set squeeze where range zeros sum log mean_squared_error ones_like max reduce_max reduce_sum sign cast int32 abs gather int range reshape | # [Time Series Deconfounder: Estimating Treatment Effects over Time in the Presence of Hidden Confounders](https://arxiv.org/abs/1902.00450) ### Authors: Ioana Bica, Ahmed M. Alaa, Mihaela van der Schaar #### International Conference on Machine Learning (ICML) 2020 Code Author: Ioana Bica ([email protected]) ## Introduction The Time Series Deconfounder is a causal inference method that enables the estimation of treatment effects over time from observational data in the presence of hidden confounders. The Time Series Deconfounder consists of two steps: - Step 1: Fit factor model over time to infer substitutes for the hidden confounders. Proposed architecture | 2,408 |
iperov/DeepFaceLab | ['face swapping'] | ['DeepFaceLab: Integrated, flexible and extensible face-swapping framework'] | models/Model_XSeg/Model.py mainscripts/VideoEd.py XSegEditor/QImageDB.py merger/MergerScreen/MergerScreen.py mainscripts/dev_misc.py merger/InteractiveMergerSubprocessor.py samplelib/SampleGeneratorImageTemporal.py core/leras/models/__init__.py samplelib/Sample.py core/joblib/__init__.py core/imagelib/estimate_sharpness.py core/joblib/MPFunc.py core/leras/layers/DenseNorm.py core/leras/nn.py samplelib/SampleProcessor.py core/leras/archis/__init__.py core/leras/layers/Conv2D.py core/stdex.py core/imagelib/text.py core/leras/models/PatchDiscriminator.py core/leras/__init__.py models/Model_XSeg/__init__.py core/leras/layers/DepthwiseConv2D.py core/imagelib/equalize_and_stack_square.py samplelib/__init__.py core/imagelib/sd/draw.py core/leras/optimizers/AdaBelief.py models/Model_AMP/Model.py core/randomex.py core/joblib/MPClassFuncOnDemand.py core/leras/optimizers/__init__.py core/leras/initializers/__init__.py mainscripts/Extractor.py mainscripts/Sorter.py core/mathlib/__init__.py core/leras/optimizers/OptimizerBase.py core/imagelib/draw.py samplelib/SampleGeneratorBase.py core/leras/layers/BatchNorm2D.py core/leras/layers/ScaleAdd.py XSegEditor/QCursorDB.py models/__init__.py core/joblib/SubprocessGenerator.py DFLIMG/DFLIMG.py core/leras/layers/__init__.py models/ModelBase.py facelib/FaceEnhancer.py core/joblib/ThisThreadGenerator.py XSegEditor/QIconDB.py core/imagelib/blursharpen.py merger/MergeMasked.py core/cv2ex.py models/Model_Quick96/__init__.py main.py mainscripts/FacesetResizer.py core/leras/archis/ArchiBase.py localization/localization.py facelib/LandmarksProcessor.py core/leras/layers/Dense.py models/Model_SAEHD/__init__.py mainscripts/Merger.py mainscripts/XSegUtil.py core/imagelib/filters.py XSegEditor/QStringDB.py core/leras/initializers/CA.py core/imagelib/__init__.py core/leras/models/ModelBase.py models/Model_Quick96/Model.py samplelib/SampleGeneratorFaceTemporal.py core/leras/layers/InstanceNorm2D.py facelib/S3FDExtractor.py samplelib/SampleLoader.py samplelib/SampleGeneratorFaceXSeg.py core/qtex/qtex.py DFLIMG/__init__.py core/leras/optimizers/RMSprop.py core/structex.py core/leras/layers/BlurPool.py facelib/__init__.py core/leras/archis/DeepFakeArchi.py core/imagelib/SegIEPolys.py mainscripts/FacesetEnhancer.py merger/FrameInfo.py models/Model_SAEHD/Model.py core/mplib/__init__.py samplelib/SampleGeneratorFacePerson.py merger/MergerScreen/__init__.py core/imagelib/common.py core/imagelib/sd/__init__.py core/leras/layers/AdaIN.py core/leras/layers/LayerBase.py facelib/FANExtractor.py core/leras/layers/TanhPolar.py core/leras/models/XSeg.py samplelib/SampleGeneratorFace.py merger/MergeAvatar.py core/pathex.py core/leras/layers/Conv2DTranspose.py core/qtex/QXMainWindow.py merger/__init__.py core/imagelib/morph.py core/joblib/SubprocessorBase.py mainscripts/Trainer.py samplelib/PackedFaceset.py core/mathlib/umeyama.py mainscripts/Util.py core/interact/__init__.py core/leras/layers/FRNorm2D.py core/leras/layers/Saveable.py models/Model_AMP/__init__.py core/leras/layers/TLU.py facelib/XSegNet.py core/mplib/MPSharedList.py core/leras/models/CodeDiscriminator.py facelib/FaceType.py XSegEditor/XSegEditor.py merger/MergerConfig.py core/leras/ops/__init__.py core/interact/interact.py core/leras/device.py core/imagelib/sd/calc.py core/imagelib/reduce_colors.py samplelib/SampleGeneratorImage.py localization/__init__.py DFLIMG/DFLJPG.py core/qtex/__init__.py core/qtex/QSubprocessor.py core/qtex/QXIconButton.py samplelib/SampleGeneratorFaceCelebAMaskHQ.py core/imagelib/warp.py core/osex.py core/imagelib/color_transfer.py mainscripts/ExportDFM.py process_videoed_cut_video process_train process_xsegfetch process_xsegremovelabels process_videoed_denoise_image_sequence process_merge process_faceset_enhancer process_xsegremove process_exportdfm process_videoed_video_from_sequence process_faceset_resizer process_util process_extract process_videoed_extract_video process_sort process_dev_test process_xsegapply fixPathAction process_xsegeditor bad_args cv2_imwrite cv2_resize cv2_imread set_process_dpi_aware get_screen_size set_process_lowest_prio get_image_paths move_all_files write_bytes_safe get_first_file_by_stem get_image_unique_filestem_paths get_all_dir_names get_file_paths delete_all_files scantree get_paths get_all_dir_names_startswith random_normal suppress_stdout_stderr struct_unpack LinearMotionBlur blursharpen _scale_array color_transfer color_transfer_idt color_transfer_mkl reinhard_color_transfer lab_image_stats linear_color_transfer channel_hist_match color_transfer_mix color_transfer_sot color_hist_match overlay_alpha_image random_crop cut_odd_image normalize_channels draw_polygon draw_rect equalize_and_stack_square compute _calculate_sharpness_metric marziliano_method get_block_contrast _simple_thinning estimate_sharpness is_edge_block sobel apply_random_motion_blur apply_random_sharpen _min_resize _get_image_gradient _generate_lighting_effects apply_random_rgb_levels apply_random_hsv_shift apply_random_bilinear_resize _d_resize apply_random_gaussian_blur apply_random_overlay_triangle apply_random_relight apply_random_jpeg_compress apply_random_resize apply_random_nearest_resize morphTriangle morph_by_points applyAffineTransform reduce_colors SegIEPolys SegIEPolyType SegIEPoly get_text_image draw_text_lines draw_text _get_pil_font get_draw_text_lines warp_by_params gen_warp_params gen_pts mls_rigid_deformation dist_to_edges vector2_cross random_bezier_split_faded random_faded random_circle_faded vector2_dot circle_faded bezier vector2_dot2 InteractBase InteractColab InteractDesktop MPClassFuncOnDemand MPFunc SubprocessGenerator Subprocessor ThisThreadGenerator Devices Device nn ArchiBase DeepFakeArchi CAInitializerSubprocessor initializers AdaIN BatchNorm2D BlurPool Conv2D Conv2DTranspose Dense DenseNorm DepthwiseConv2D FRNorm2D InstanceNorm2D LayerBase Saveable ScaleAdd TanhPolar TLU CodeDiscriminator ModelBase UNetPatchDiscriminator PatchDiscriminator XSeg dssim concat _get_pixel_value average_gv_list resize2d_bilinear flatten rgb_to_lab bilinear_sampler resize2d_nearest space_to_depth tf_gradients random_binomial total_variation_mse style_loss gelu init_weights tf_get_value upsample2d pixel_norm reshape_4D batch_set_value max_pool average_tensor_list gaussian_blur depth_to_space AdaBelief OptimizerBase RMSprop umeyama get_power_of_two rotationMatrixToEulerAngles polygon_area transform_mat rotate_point transform_points MPSharedList IndexHost Index2DHost ListHost DictHostCli DictHost QSubprocessor QDarkPalette QActionEx QSize_to_np QImage_from_np QImage_to_np QPixmap_from_np QPoint_to_np QPoint_from_np QXIconButton QXMainWindow DFLIMG DFLJPG FaceEnhancer FaceType FANExtractor blur_image_hull_mask mirror_landmarks get_face_struct_mask estimate_pitch_yaw_roll convert_98_to_68 expand_eyebrows get_rect_from_landmarks get_transform_mat draw_rect_landmarks get_cmask transform_points estimate_averaged_yaw calc_face_pitch alpha_to_color get_image_eye_mask draw_landmarks get_image_hull_mask get_image_mouth_mask S3FDExtractor XSegNet dev_test_68 dev_test dev_test1 dev_resave_pngs extract_vggface2_dataset extract_umd_csv dev_segmented_trash main process_folder FacesetEnhancerSubprocessor FacesetResizerSubprocessor process_folder extract_video video_from_sequence denoise_image_sequence cut_video remove_xseg remove_xseg_labels apply_xseg fetch_xseg FrameInfo InteractiveMergerSubprocessor MergeFaceAvatar process_frame_info MergeMasked MergeMaskedFace MergerConfigMasked MergerConfigFaceAvatar MergerConfig ScreenManager ScreenAssets Screen ModelBase PreviewHistoryWriter import_model AMPModel QModel SAEHDModel XSegModel PackedFaceset Sample SampleType SampleGeneratorBase SampleGeneratorFace SampleGeneratorFaceCelebAMaskHQ MaskType SampleGeneratorFacePerson Index2DHost SampleGeneratorFaceTemporal SampleGeneratorFaceXSeg SegmentedSampleFilterSubprocessor SampleGeneratorImage SampleGeneratorImageTemporal FaceSamplesLoaderSubprocessor SampleLoader SampleProcessor QCursorDB QIconDB QImageDB QStringDB ImagePreviewSequenceBar QUIConfig QCanvasOperator LoaderQSubprocessor CanvasConfig OpMode QCanvas DragType ViewLock ColorScheme QCanvasControlsLeftBar start QCanvasControlsRightBar MainWindow PTEditMode main set_process_lowest_prio main set_process_lowest_prio unpack_faceset pack save_faceset_metadata log_info restore_faceset_metadata_folder pack_faceset save_faceset_metadata_folder restore_faceset_metadata Path input_dir unpack recover_original_aligned_filename set_process_lowest_prio add_landmarks_debug_images main set_process_lowest_prio main set_process_lowest_prio main set_process_lowest_prio output_ext fps extract_video output_dir input_file set_process_lowest_prio audio_track_id from_time bitrate to_time cut_video input_file set_process_lowest_prio factor denoise_image_sequence set_process_lowest_prio input_dir video_from_sequence set_process_lowest_prio Path set_process_lowest_prio input_dir process_folder Path set_process_lowest_prio input_dir process_folder dev_test set_process_lowest_prio input_dir start Path set_process_lowest_prio input_dir model_dir apply_xseg Path input_dir set_process_lowest_prio Path remove_xseg set_process_lowest_prio input_dir remove_xseg_labels Path set_process_lowest_prio input_dir Path fetch_xseg set_process_lowest_prio input_dir print_help exit loader_func asarray bytearray imencode suffix shape normalize_channels resize nice SetPriorityClass HANDLE GetCurrentProcess SetProcessDPIAware user32 write_bytes parent name unlink rename exists is_dir scandir str list scandir any Path scantree exists append remove get_image_paths name stem set add verbose_print_func Path exists Path exists Path exists str list lower scandir Path startswith append exists str sorted list path lower scandir Path exists name Path rename get_file_paths unlink Path get_file_paths normal random empty prod range calcsize warpAffine ones getRotationMatrix2D zeros sum medianBlur addWeighted ones zeros GaussianBlur max dtype reshape astype copy argsort shape bilateralFilter fill empty range eps T clip reshape eig dot shape sqrt cov mean diag T reshape min astype float32 empty_like solve dot shape histogram interp max range evaluate COLOR_BGR2LAB copy clip cvtColor T reshape transpose mean dot eigh eye cholesky split min max float64 astype shape unique interp ravel dtype astype shape channel_hist_match range uint8 astype float32 COLOR_BGR2LAB color_transfer_sot COLOR_LAB2BGR cvtColor color_transfer_idt color_transfer_mkl reinhard_color_transfer linear_color_transfer color_transfer_sot clip shape repeat len shape shape range tuple line range len draw_polygon concatenate shape resize expand_dims max enumerate T convolve square mean sqrt array shape zeros float64 marziliano_method astype canny sobel gradient atan2 shape any zeros round range int exp slice get_block_contrast shape flipud round zeros is_edge_block rot90 range cvtColor COLOR_BGR2GRAY rand random clip array COLOR_HSV2BGR random merge COLOR_BGR2HSV randint clip cvtColor split randint blursharpen random LinearMotionBlur randint random randint GaussianBlur random int rand random shape resize uint8 imencode random astype float32 shape imdecode randint zeros_like fillPoly random shape uniform clip int float min int INTER_LANCZOS4 min INTER_AREA resize array CV_32F filter2D max _get_image_gradient _d_resize shape pyrDown pyrUp _generate_lighting_effects random square mean sqrt uniform sum array clip float32 getAffineTransform float32 fillConvexPoly shape boundingRect int32 applyAffineTransform zeros expand_dims array shape morphTriangle zeros simplices fromarray uint8 convert astype COLOR_RGB2BGR array cvtColor truetype asarray Draw get_default_ttf_font_name concatenate text new _get_pil_font shape clip draw_text range len draw_text_lines zeros shape int16 norm reshape transpose astype float32 vstack true_divide interp zeros sum range flatnonzero int norm rand random cos pi sin append randint array range T random astype copy float32 getRotationMatrix2D dict uniform linspace random_normal warpAffine remap resize norm clip einsum concatenate norm reshape empty abs clip vector2_cross arccos abs cos float32 vector2_dot2 sign empty_like sqrt stack vector2_dot sin power empty clip randint max random randint float32 pi randint bezier max clip initializer inputs append batch_set_value run gradients expand_dims __enter__ __exit__ enumerate reduce_mean __enter__ __exit__ concat pow tanh sqrt pi resize_nearest_neighbor transpose transpose value resize transpose value resize transpose reshape transpose randint float32 pad make_kernel tile depthwise_conv2d gaussian_blur dtype constant arange reshape float32 square reduce_mean reducer cast softmax tile max as_list reshape transpose as_list getCurrentDeviceConfig transpose reshape constant reshape multiply matmul cast square reduce_sum reshape shape stack tile range _get_pixel_value float32 floor clip_by_value cast int32 add_n expand_dims svd T ones matrix_rank mean dot eye sum diag sqrt atan2 cos pi sin squeeze invertAffineTransform shape transform expand_dims norm astype float32 rotate_point transform_points shape Format_Grayscale8 Format_BGR888 Format_ARGB32 height reshape convertToFormat width constBits setsize range get norm getAffineTransform polygon_area astype float32 transform_points sqrt estimate_averaged_yaw array transform_points FULL_NO_ALIGN get_transform_mat float32 array copy concatenate expand_eyebrows fillConvexPoly convexHull zeros int getStructuringElement astype fillConvexPoly MORPH_ELLIPSE convexHull dilate zeros GaussianBlur int getStructuringElement astype fillConvexPoly MORPH_ELLIPSE convexHull dilate zeros GaussianBlur shape zeros concatenate process copy blend alpha_to_color zeros get_image_hull_mask gdf max clip int blur getStructuringElement min erode argwhere MORPH_ELLIPSE expand_dims copy draw_landmarks zeros expand_eyebrows concatenate polylines tuple shape get_image_hull_mask array circle get_transform_mat draw_rect transform_points draw_polygon draw_landmarks array array rotationMatrixToEulerAngles concatenate astype float32 pi solvePnP zeros array clip get pop get_image_paths parent log_info name stem progress_bar_generator get_all_dir_names Path mkdir run fromString split cv2_imread Path normalize_channels exists input_bool str log_info name stem append get_image_paths get_rect_from_landmarks unlink mkdir parent cv2_imwrite progress_bar_generator read_text split get str get_image_paths parent log_info name len unlink Path mkdir split log_err run range exists fromString input_bool blur interact cv2_imread Path save BestGPU INTER_LINEAR max exists run log_info stem input append HEAD range get_source_filename warpAffine get_image_paths unlink get_image_to_face_mat mkdir load set_xseg_mask min read_text array split get_image_paths cv2_imwrite progress_bar_generator cv2_imread Path get_image_paths parent name stem rename Path mkdir append cv2_imread WHOLE_FACE Path save exists run INTER_LANCZOS4 log_info stem input append isin get_source_filename warpAffine get_image_paths get_rect_from_landmarks astype unlink get_image_to_face_mat mkdir get_paths load parent set_xseg_mask print progress_bar_generator float32 array split export_dfm input_bool join get_image_paths log_info parent name copy unlink rmtree mkdir run input_int lower update str get_image_paths parent input_str stem output get_first_file_by_stem unlink input_int mkdir Path log_err input run str suffix parent input_str stem overwrite_output input_int log_err Path input max run update str suffix parent progress_bar_generator output input_int rename log_err Path run clip enumerate suffix input_str wait input_int Path max input_bool str stem input update run_async get_image_paths close mkdir parent overwrite_output get_first_file_by_stem log_err probe extract ask_choose_device transform_points loads save resize get_face_type exists INTER_LANCZOS4 initialize log_info getAffineTransform WARP_INVERSE_MAP shape read_bytes XSegNet get warpAffine get_image_paths astype lower get_source_landmarks load set_xseg_mask get_transform_mat progress_bar_generator float32 get_resolution zeros fromString load str get_image_paths log_info parent name has_polys progress_bar_generator copy get_seg_ie_polys unlink mkdir append input_bool load get_image_paths log_info set_xseg_mask input_str progress_bar_generator has_xseg_mask save load get_image_paths log_info input_str has_seg_ie_polys progress_bar_generator save set_seg_ie_polys warpAffine get_transform_mat astype float32 cv2_imread normalize_channels filename clip sharpen_func sharpen_mode concatenate predictor_func add_source_image process_frame_info temporal_face_count append range sharpen_amount predictor_func color_transfer_mkl motion_power bicubic_degrade_power motion_blur_power linear_color_transfer color_transfer_mix boundingRect resize reduce_colors max clip face_enhancer_func hist_match_threshold medianBlur super_resolution_power WARP_INVERSE_MAP ones LinearMotionBlur shape pad blur_mask_modifier image_denoise_power masked_hist_match blursharpen range color_hist_match warpAffine ones_like sharpen_mode xseg_256_extract_func seamlessClone color_transfer_idt astype copy reinhard_color_transfer empty_like motion_deg INTER_CUBIC MORPH_ELLIPSE color_transfer_sot dilate GaussianBlur get_image_hull_mask NORMAL_CLONE uint8 int erode_mask_modifier getStructuringElement get_transform_mat erode argwhere blursharpen_amount color_degrade_power landmarks_list concatenate astype float32 cv2_imread shape normalize_channels MergeMaskedFace filepath clip enumerate str parent cv2_imread locals __import__ globals dict setApplicationName setPalette QDarkPalette Path show str initialize log_info setWindowIcon addApplicationFont AA_EnableHighDpiScaling setStyle setFont gettempdir setAttribute QApplication path_contains app_icon MainWindow exec_ parent QFont raise_ AA_UseHighDpiPixmaps | <table align="center" border="0"> <tr><td colspan=2 align="center"> # DeepFaceLab <a href="https://arxiv.org/abs/2005.05535"> <img src="https://static.arxiv.org/static/browse/0.3.0/images/icons/favicon.ico" width=14></img> https://arxiv.org/abs/2005.05535</a> ### the leading software for creating deepfakes <img src="doc/DFL_welcome.png" align="center"> </td></tr> <tr><td colspan=2 align="center"> | 2,409 |
ipeter50/ken-burns-effect | ['depth estimation'] | ['3D Ken Burns Effect from a Single Image'] | training/train_depth.py training/eval_depth.py utils/utils.py utils/pipeline.py training/train_inpaint.py utils/fid.py train.py utils/losses.py training/eval_inpaint.py models/discriminator.py utils/partial_conv.py models/pointcloud_inpainting.py models/disparity_refinement.py kbe.py models/disparity_estimation.py models/disparity_refinement_pretrained.py utils/common.py utils/data_loader.py models/partial_inpainting.py utils/fov.py MPDDiscriminator MultiScalePerceptualDiscriminator PerceptualDiscriminator VGGBlock MultiScaleDiscriminator Discriminator ConvBlock Disparity Basic Downsample Semantics Upsample disparity_estimation Downsample Refine Upsample Basic Downsample Refine Upsample Basic Downsample Inpaint Upsample Basic Downsample Inpaint Upsample Basic DepthEval InpaintEval TrainerDepth TrainerInpaint launch_kernel preprocess_kernel process_inpaint depth_to_points process_autozoom process_shift Stream render_pointcloud generate_mask process_kenburns spatial_filter process_load fill_disocclusion Dataset PartialInceptionNetwork to_cuda FID netSummary reduceNet printLayer outFromIn extractParams compute_loss_grad compute_loss_ord JoinEdgeLoss InpaintingLoss compute_masked_grad_loss PartialConv2d Pipeline save_model make_vgg16_layers get_masks VGG16Partial sum_item get_tensor_shift resize_image normalize_depth normalize_torch_tensor compute_inpaint_metrics load_models compute_metrics weights_init class_to_masks generate_new_view_from_inpaint derivative_scale get_item_in_dict plot_all CustomWriter get_kernels spectral_norm_switch get_random_zoom gram_matrix total_variation_loss view depth_to_points float disparity_refinement cuda minMaxLoc item disparity_estimation max view depth_to_points pointcloud_inpainting float cat cuda clone view repeat item render_pointcloud range uint8 view process_inpaint astype getRectSubPix resize append render_pointcloud float max fill_disocclusion cuda_stream str int join replace size search group stride split size type_as expand view size new_zeros unfold conv2d pad range fill_ size new_zeros nelement cat view fill_ size spatial_filter to size clone is_available children list append __name__ ceil floor print print reduceNet printLayer outFromIn append range extractParams len L1Loss sum log10 L1loss derivative_scale sum MSELoss L1Loss derivative_scale sum make_grid transpose axis expand imshow figure append numpy max int size min interpolate float T view conv2d abs view get_kernels apply mean sqrt log10 abs max SSIM item append to unsqueeze unique remove_spectral_norm modules spectral_norm items list save print load load_state_dict enumerate process_shift max view depth_to_points get_tensor_shift cat generate_mask minMaxLoc item get_item_in_dict render_pointcloud float range append view reshape render_pointcloud float max cat uniform min max items list view size transpose baddbmm type Conv2d mean abs | # Improved 3D Ken Burns effect This repository contains code for generating 3D Ken Burns effect from single image. This work is mainly based on [3D Ken Burns Effect from a Single Image](https://arxiv.org/pdf/1909.05483.pdf). This paper was a starting point for our work and therefore the trained networks released by Niklaus et al. are comptible with our framework and can be downloaded from their [repository](https://github.com/sniklaus/3d-ken-burns). We provide code for the training of the different neural networks used to achieve the 3D Ken Burns effect. In addition we propose some extension of the original work, to improve both the depth estimation and the image inpainting. Finally, we develop an semi-supervised method for the disocclusion inpainting problem in order to prevent the difficulty of getting a synthetic dataset as used in the original paper. We also proposed a slight modification of the 3D KBE to produce fake [dolly zoom](https://en.wikipedia.org/wiki/Dolly_zoom). Here is a [video](https://www.youtube.com/watch?v=nSZrJOJFj9o) with some of our results. ### Download trained networks First download our trained networks by running `./donwload.sh` from the directory where the repository has been cloned. Note that you might need to make that script executable with `chmod +x download.sh`. ## [Generate 3D Ken Burns effects](https://www.youtube.com/watch?v=nSZrJOJFj9o)  To generate 3D KBE, use the script `kbe.py`. Some parameters can be set to change from default settings. If no path for the networks are specified, default names and paths from donwload script will be used. | 2,410 |
ir-lab/LanguagePolicies | ['imitation learning'] | ['Language-Conditioned Imitation Learning for Robot Manipulation Tasks'] | utils/intprim/gaussian_model.py model_src/basismodel.py utils/graphs.py model_src/glove.py utils/ros1compat/xml_reflection/__init__.py model_src/model.py utils/intprim/sigmoidal_model.py utils/collect_data.py utils/ros1compat/xml_reflection/core.py utils/ros1compat/sdf.py model_src/attention.py utils/ros1compat/xml_reflection/basics.py service.py utils/tf_util.py utils/intprim/basis_model.py utils/network.py viz_val_vrep.py model_src/feedbackcontroller.py val_model_vrep.py main.py utils/data_processing.py utils/ros1compat/urdf.py utils/intprim/polynomial_model.py utils/ros1compat/kdl_urdf_parser.py model_src/dmp.py utils/intprim/selection.py utils/voice.py DatasetRSS setupModel NetworkService Simulator calcMAE getUsedFeatures debugColors overallStatistics cleanJson transformCoordinate interpolateTrajectory normalize plotPhaseArrows averageBallSuccessPerTask rotateCoordinates TopDownAttention BasisModel DynamicMovementPrimitive FeedbackController GloveEmbeddings PolicyTranslationModel _setJointVelocityFromTarget SimulatorState _generatePouring kdlFrameToRot adjustTargetForPouring _getSimulatorState _getObjectInfo collectSingleSample run genPosition _setJointVelocityFromTarget_Direct _calculateAngle _graspClosestObject getCollisionWaypoints _moveJ Robot _generateVoice createEnvironment _moveL saveTaskToFile _setupTask _getCameraImage _setRobotJoints int64_list_feature DataConverter limitGPUMemory float_list_feature int64_feature bytes_feature getDMPData bytes_list_feature TBoardGraphs Network limitGPUMemory trainOnCPU Voice BasisModel GaussianModel PolynomialModel Selection SigmoidalModel treeFromFile treeFromParam _toKdlJoint treeFromString _toKdlPose _add_children_to_tree treeFromUrdfModel _toKdlInertia Entity Pose Link Inertia Inertial Model Material Pose Visual Texture JointMimic SafetyController Inertial Sphere JointLimit Box GeometricType Mesh Actuator PR2Transmission TransmissionJoint LinkMaterial Collision Robot Joint Link JointCalibration Color Transmission Inertia Cylinder JointDynamics SelectiveReflection pfloat xml_string to_yaml isstring YamlReflection xml_children node_add dict_sub ListType start_namespace Path Attribute Reflection Param end_namespace SimpleElementType VectorType reflect ValueType Info add_type Object Element RawType on_error_stderr DuckTypedFactory ObjectType BasicType ParseError AggregateElement make_type get_type FactoryType setDatasets print train Network PolicyTranslationModel tile expand_dims copy cos deg2rad sin list arrow transformCoordinate imshow title figure imread keys append float sum len asarray linspace interp zeros range asarray interpolateTrajectory list format cleanJson print mean dict averageBallSuccessPerTask nan unique zip float sum keys range len removeEmpty cos deg2rad sqrt uniform sin flip astype capture_rgb SimulatorState script_call script_call script_call script_call int getJointAnglesFromCurrent tolist sqrt getTcpFromAngles linspace ceil power range max zeros int getJointAnglesFromCurrent tolist hstack sqrt getTcpFromAngles linspace ceil power max genPosition _setRobotJoints tolist deg2rad choice append randint script_call range GetEulerZYX asarray script_call deg2rad sqrt getTcpFromAngles kdlFrameToRot power abs inter getJointAnglesFromCurrent tolist interp1d getTcpFromAngles kdlFrameToRot linspace tile expand_dims range norm _moveL insert deg2rad choice _generatePouring kdlFrameToRot getTcpFromAngles vstack adjustTargetForPouring tile append zeros expand_dims _moveJ _getObjectInfo enumerate dot asarray deg2rad arctan asarray deg2rad dot sqrt power range int list items print tolist print generateSentence data _setJointVelocityFromTarget toArray VisionSensor Voice _getSimulatorState append encode Robot _generateVoice Hashids start createEnvironment int time _setupTask _getCameraImage stop step PyRep launch range shutdown collectSingleSample GaussianModel linspace fit_basis_functions_linear_closed_form print list_physical_devices set_memory_growth list_logical_devices format len int set_inter_op_parallelism_threads print getenv set_visible_devices set_intra_op_parallelism_threads list_physical_devices inertia _toKdlPose origin inertial name _toKdlJoint _toKdlPose RigidBodyInertia Segment _toKdlInertia origin print name Tree property tostring _Element append isinstance getchildren _Element str list items hasattr isinstance tolist tostring Iterable Reflection write isinstance get add_type make_type startswith float issubclass isinstance | # Language-Conditioned Imitation Learning for Robot Manipulation Tasks This repository is the official implementation of [Language-Conditioned Imitation Learning for Robot Manipulation Tasks](https://arxiv.org/abs/2010.12083), which has been accepted to NeurIPS 2020 as spotlight presentation. <div style="text-align:center"><img src="doc/system.png" alt="Model figure" width="80%"/></div> When using this code and/or model, we would apprechiate the following citation: ``` @misc{stepputtis2020languageconditioned, title={Language-Conditioned Imitation Learning for Robot Manipulation Tasks}, booktitle = {Advances in Neural Information Processing Systems}, author={Simon Stepputtis and Joseph Campbell and Mariano Phielipp and Stefan Lee and Chitta Baral and Heni Ben Amor}, year={2020}, | 2,411 |
iro-cp/FCRN-DepthPrediction | ['depth estimation'] | ['Deeper Depth Prediction with Fully Convolutional Residual Networks'] | tensorflow/models/fcrn.py tensorflow/models/__init__.py tensorflow/predict.py tensorflow/models/network.py main predict ResNet50UpProj layer interleave get_incoming_shape Network asarray ANTIALIAS astype float32 placeholder ResNet50UpProj resize expand_dims open add_argument ArgumentParser model_path parse_args image_paths _exit predict Tensor isinstance | # Deeper Depth Prediction with Fully Convolutional Residual Networks By [Iro Laina](http://campar.in.tum.de/Main/IroLaina), [Christian Rupprecht](http://campar.in.tum.de/Main/ChristianRupprecht), [Vasileios Belagiannis](http://www.robots.ox.ac.uk/~vb/), [Federico Tombari](http://campar.in.tum.de/Main/FedericoTombari), [Nassir Navab](http://campar.in.tum.de/Main/NassirNavab). ## Contents 0. [Introduction](#introduction) 0. [Quick Guide](#quick-guide) 0. [Models](#models) 0. [Results](#results) 0. [Citation](#citation) 0. [License](#license) ## Introduction | 2,412 |
irom-lab/PAC-Imitation | ['generalization bounds', 'imitation learning'] | ['Generalization Guarantees for Imitation Learning'] | trainNav_bound.py testPushRollout.py trainPush_bound.py trainGrasp_es.py dataset/datasetBCPush.py src/grasp_rollout_env.py generateBox.py trainNav_bc.py dataset/datasetBCNav.py src/push_rollout_env.py trainNav_es.py src/__init__.py trainGrasp_bc.py trainPush_bc.py src/panda_env.py src/pac_es.py src/nn_push.py src/utils_depth.py src/nav_rollout_env.py src/nn_grasp.py trainGrasp_bound.py src/nn_func.py src/nn_nav.py trainPush_es.py dataset/datasetBCGrasp.py src/utils_geom.py src/panda.py main saveURDF_Box main TrainGrasp_BC TrainGrasp_bound collect_as TrainGrasp_PAC_ES TrainNav_BC collect_as TrainNav_bound TrainNav_PAC_ES TrainPush_BC TrainPush_bound collect_as TrainPush_PAC_ES test_dataset train_dataset train_dataset test_dataset my_collate train_dataset test_dataset my_collate GraspRolloutEnv quat2aa NavRolloutEnv reparameterize SpatialSoftmax PolicyNet Encoder Decoder_nav Encoder_nav CNN_nav Encoder_lstm PolicyNet kl_inverse utility compute_grad_ES Panda full_jacob_pb pandaEnv PushRolloutEnv getCameraParametersGrasp getCameraParametersPush NearZero rot2quat rot2euler QuinticTimeScaling LinearTimeScaling orient euler2rot skew quatInverse rot2aa quatDist quat2rot homogeneous euler2quat quat2aa log_rot quatMult vec2rot adjoint vec2quat SO3_6D_np quat2euler vecQuat2vec angleBwVec close write open obj_folder print add_argument uniform mkdir ArgumentParser parse_args range saveURDF_Box load exp ones posterior_path load_state_dict to zeros norm asarray arctan2 exp randn_like Maximize Problem Variable solve array zeros range max Tensor int ones_like exp transpose utility numel indices matmul log pow zeros range max Tensor cat flatten array cos sin sqrt arcsin sin arctan2 zeros sqrt trace arccos sin trace array arccos trace clip quat2rot quat2rot skew norm flatten cross dot dot reshape array euler array concatenate cross zeros norm dot dot asarray array dot cross array dot norm array dot cross | # Generalization Guarantees for (Multi-Modal) Imitation Learning [Paper](https://arxiv.org/abs/2008.01913) | [Review](https://drive.google.com/file/d/1VmLh07UuOVhDxGXh2YoVCJf3GvHNbG0M/view?usp=sharing) | [Experiment video](https://www.youtube.com/watch?v=dfXyHvOTolc&t=3s) | [5min presentation at CoRL 2020](https://www.youtube.com/watch?v=nabtvOWoIlo&feature=emb_logo) [](https://www.youtube.com/watch?v=dfXyHvOTolc) This repository includes codes for synthetic trainings of these robotic tasks in the paper: 1. Grasping diverse mugs 2. Planar box pushing using visual-feedback 3. Vision-based navigation through home environments Although the codes for all examples are included here, only the pushing example can be run without any additional codes/resources. The other two examples require data from online object dataset and object post-processing, which can take significant amount of time to set up and involves licensing. Meanwhile, all objects (rectangular boxes) used for the pushing example can be generated through URDF files (`generativeBox.py`). Moreover, we provide the pre-trained weights for the decoder network of the cVAE for the pushing example. The posterior policy distribution can be trained then using the weights and the prior distribution (unit Gaussians). ### Dependencies (`pip install` with python=3.7): | 2,413 |
ironbar/AnimalAI-Olympics | ['unity'] | ['Unity: A General Platform for Intelligent Agents'] | animalai/animalai/communicator_objects/header_pb2.py animalai/animalai/communicator_objects/unity_rl_reset_output_pb2.py animalai/animalai/communicator_objects/agent_action_proto_pb2.py examples/animalai_train/animalai_train/trainers/bc/online_trainer.py animalai/animalai/communicator_objects/__init__.py animalai/animalai/communicator_objects/command_proto_pb2.py animalai/animalai/communicator_objects/unity_rl_input_pb2.py animalai/animalai/envs/environment.py examples/animalai_train/animalai_train/trainers/meta_curriculum.py examples/visualizeArena.py animalai/animalai/communicator_objects/unity_rl_reset_input_pb2.py examples/animalai_train/animalai_train/trainers/trainer.py animalai/animalai/envs/brain.py examples/animalai_train/animalai_train/trainers/buffer.py examples/animalai_train/animalai_train/trainers/bc/policy.py examples/animalai_train/animalai_train/trainers/ppo/policy.py examples/animalai_train/animalai_train/trainers/ppo/__init__.py examples/animalai_train/animalai_train/trainers/demo_loader.py examples/animalai_train/animalai_train/trainers/bc/models.py animalai/animalai/communicator_objects/unity_rl_initialization_output_pb2.py animalai/animalai/envs/arena_config.py examples/animalai_train/animalai_train/dopamine/animalai_lib.py examples/animalai_train/animalai_train/trainers/ppo/trainer.py animalai/animalai/communicator_objects/unity_rl_output_pb2.py animalai/animalai/envs/base_unity_environment.py animalai/animalai/communicator_objects/brain_parameters_proto_pb2.py animalai/animalai/communicator_objects/agent_info_proto_pb2.py examples/animalai_train/animalai_train/trainers/models.py animalai/animalai/envs/communicator.py animalai/animalai/communicator_objects/unity_output_pb2.py animalai/animalai/communicator_objects/unity_input_pb2.py examples/animalai_train/setup.py examples/animalai_train/animalai_train/trainers/learn.py examples/animalai_train/animalai_train/trainers/curriculum.py animalai/animalai/__init__.py examples/animalai_train/animalai_train/trainers/exception.py animalai/animalai/envs/__init__.py examples/submission/agent.py examples/submission/test_submission/testDocker.py animalai/animalai/envs/subprocess_environment.py examples/trainMLAgents.py animalai/animalai/communicator_objects/demonstration_meta_proto_pb2.py examples/animalai_train/animalai_train/trainers/bc/offline_trainer.py animalai/animalai/communicator_objects/unity_rl_initialization_input_pb2.py animalai/animalai/communicator_objects/unity_to_external_pb2_grpc.py examples/animalai_train/animalai_train/trainers/trainer_controller.py examples/animalai_train/animalai_train/trainers/barracuda.py animalai/animalai/envs/socket_communicator.py examples/animalai_train/animalai_train/trainers/bc/__init__.py animalai/animalai/envs/exception.py examples/animalai_train/animalai_train/trainers/bc/trainer.py animalai/animalai/communicator_objects/space_type_proto_pb2.py animalai/animalai/envs/gym/environment.py examples/animalai_train/animalai_train/trainers/ppo/models.py animalai/animalai/envs/rpc_communicator.py examples/animalai_train/animalai_train/__init__.py agent.py animalai/animalai/communicator_objects/engine_configuration_proto_pb2.py animalai/animalai/communicator_objects/unity_message_pb2.py examples/animalai_train/animalai_train/trainers/tensorflow_to_barracuda.py examples/animalai_train/animalai_train/trainers/policy.py examples/visualizeLightsOff.py animalai/animalai/communicator_objects/unity_to_external_pb2.py examples/animalai_train/animalai_train/trainers/__init__.py examples/trainDopamine.py animalai/setup.py animalai/animalai/communicator_objects/resolution_proto_pb2.py animalai/animalai/communicator_objects/arena_parameters_proto_pb2.py examples/curriculum_trainMLAgents.py Agent UnityToExternalServicer UnityToExternalStub add_UnityToExternalServicer_to_server Vector3 ArenaConfig constructor_item RGB constructor_arena Item Arena BaseUnityEnvironment safe_concat_np_ndarray BrainInfo BrainParameters safe_concat_lists Communicator UnityEnvironment UnityWorkerInUseException UnityException UnityTimeOutException UnityEnvironmentException UnityActionException RpcCommunicator UnityToExternalServicerImplementation SocketCommunicator worker EnvironmentResponse EnvironmentCommand UnityEnvWorker SubprocessUnityEnvironment AnimalAIEnv UnityGymException ActionFlattener parse_args train copy_model_for_next_train get_n_arenas create_env_fn create_agent_fn init_environment parse_args train load_config init_environment run_step_imshow initialize_animation rainbow_network nature_dqn_network implicit_quantile_network BarracudaWriter compress Build sort lstm write fuse_batchnorm_weights trim gru Model summary Struct parse_args to_json rnn BufferException Buffer Curriculum make_demo_buffer load_demonstration demo_to_buffer CurriculumError MetaCurriculumError TrainerError run_training prepare_for_docker_run init_environment try_create_meta_curriculum main load_config MetaCurriculum LearningModel Policy UnityPolicyException get_layer_shape pool_to_HW flatten process_layer process_model basic_lstm get_attr ModelBuilderContext order_by get_epsilon get_tensor_dtype replace_strings_in_list get_tensor_dims by_op remove_duplicates_from_list by_name convert strides_to_HW get_tensor_data gru UnityTrainerException _create_HistogramProto Trainer TrainerController BehavioralCloningModel OfflineBCTrainer OnlineBCTrainer BCPolicy BCTrainer PPOModel PPOPolicy PPOTrainer get_gae discount_rewards Agent main method_handlers_generic_handler add_generic_rpc_handlers construct_mapping construct_mapping extend copy vector_action_space_size list external_brain_names external_brains global_done vector_action_descriptions payload reset _send_response brains reset_parameters env_factory step reset_initial_model join sorted basename glob print load_initial_model system copy_model_for_next_train dirname agent_path parse_args enumerate sorted remove print glob system add_argument ArgumentParser AnimalAIEnv start_learning suffix verbose_id keep_checkpoints load_config str external_brain_names load_model TrainerController init_environment arena_config reset_steps save_freq trainer_config_path partial close n_envs vars isdir ArenaConfig randint SubprocessUnityEnvironment replace zeros set_data range str suptitle set_data randint step range fully_connected float32 flatten div conv2d cast variance_scaling_initializer fully_connected reshape float32 reduce_sum flatten conv2d div cast softmax variance_scaling_initializer constant fully_connected multiply cos float32 pi flatten conv2d div cast tile random_uniform range join isdir print replaceFilenameExtension exit verbose source_file target_file sqrt topologicalSort list hasattr layers addEdge Graph print inputs set len list hasattr layers print filter match trim_model compile data layers print tensors float16 replace layers dumps layers isinstance print tensors inputs zip to_json globals Build tanh mad tanh mul Build concat add sigmoid sub mad _ tanh mul Build concat add sigmoid mad Buffer reset_local_buffers number_visual_observations append_update_buffer append range enumerate make_demo_buffer load_demonstration number_steps read suffix BrainParametersProto from_agent_proto DemonstrationMetaProto ParseFromString AgentInfoProto append from_proto _DecodeVarint32 start_learning int str format external_brain_names TrainerController put init_environment try_create_meta_curriculum load_config list MetaCurriculum keys _resetParameters chmod format basename isdir glob copyfile copytree prepare_for_docker_run int Process getLogger print run_training start Queue info append randint docopt range endswith len HasField hasattr get_attr tensor_shape ndarray isinstance shape int_val bool_val float_val ListFields name ndarray isinstance str tensor_content ndarray product isinstance get_tensor_dtype print get_tensor_dims unpack int_val bool_val array float_val enter append add set name find_tensor_by_name split name lstm find_tensor_by_name find_forget_bias split get_layer_shape id Struct tensor hasattr name patch_data input_shapes out_shapes input get_attr append replace_strings_in_list tensors astype op zip enumerate print float32 patch_data_fn model_tensors map_ignored_layer_to_its_input co_argcount len items list get_tensors hasattr name print process_layer eval ModelBuilderContext layers verbose Struct process_model open compress node GraphDef Model dims_to_barracuda_shape insert get_tensor_dims inputs ParseFromString cleanup_layers read memories print sort write trim summary max int min HistogramProto shape prod histogram append float sum array list zeros_like size reversed range asarray tolist discount_rewards Agent exec_module format ArenaConfig AnimalAIEnv module_from_spec t reset spec_from_file_location step | # Animal-AI Olympics <p align="center"> <img height="300" src="documentation/PrefabsPictures/steampunkFOURcrop.png"> </p> **July 1st - November 1st** The Animal-AI Olympics is an AI competition with tests inspired by animal cognition. Participants are given a small environment with just seven different classes of objects that can be placed inside. In each test, the agent needs to retrieve the food in the environment, but to do so there are obstacles to overcome, ramps to climb, boxes to push, and areas that must be avoided. The real challenge is that we don't provide the tests in advance. It's up to you to explore the possibilities with the environment and build interesting configurations that can help create an agent that understands how the environment's physics work and the affordances that it has. The final submission should be an agent capable of robust food retrieval behaviour similar to that of many kinds of animals. We know the animals can pass these tests, it's time to see if AI can too. ## Prizes $32,000 (equivalent value) * Overall Prizes * 1st place overall: **$7,500 total value** - $6,500 with up to $1,000 travel to speak at NeurIPS 2019. * 2nd place overall: **$6,000 total value** - $5,000 with up to $1,000 travel to speak at NeurIPS 2019. | 2,414 |
isVoid/DenoiseNet | ['denoising'] | ['Deep Convolutional Denoising of Low-Light Images'] | denoise_input.py denoise_eval.py denoise_train.py layers.py Denoisenet.py utils.py feed_forward loss psnr _log10 eval_patch patches_to_image image_to_patches main eval_image load_patches _int64_feature read_tfRecords extract_patches_from_image_tensor load_patches_as_array convert_patches_to_tfRecords input_tfRecords _bytes_feature main main random_mini_batches train train_tensors conv_layer_with_no_pooling conv_layer_with_idendity_act conv_layer_with_sigmoid_act conv_layer_with_pooling loss zeros_like print name add conv2d append expand_dims range mean _log10 max int concatenate reshape shape zeros array range int astype shape zeros range get_tensor_by_name loss get_default_graph run reset_default_graph ConfigProto time Output asarray EvalY uint8 psnr print convert Checkpoint astype Model mkdir save split eval_image EvalX open sorted asarray walk load_patches_as_array update join sorted asarray print TFRecordWriter convert write SerializeToString close tqdm tostring Example open listdir range len read TFRecordReader decode_raw uint8 reshape set_shape parse_single_example root convert_patches_to_tfRecords seed arange reshape shuffle append range trainable_variables remove join image global_variables_initializer ConfigProto listdir trainable_variables remove join global_variables_initializer ConfigProto listdir load_patches dataset_file noisy_patches_root input_tfRecords clean_patches_root train train_tensors | # Denoisenet [arXiv:1701.01698](https://arxiv.org/pdf/1701.01687.pdf) by Remez et el. ## Result   ## Usage #### Install Requirements ```shell pip install -r requirements.txt | 2,415 |
isaacaddis/Seung | ['optical character recognition', 'scene text detection', 'curved text detection'] | ['EAST: An Efficient and Accurate Scene Text Detector'] | seung.py data/data_util.py data/retrieve.py Dataset | # Seung Neural networks and OpenCV team up together to do my homework. ## Text Detection The first process Seung undergoes is detecting coherent regions of text using the [https://arxiv.org/abs/1704.03155v2](EAST text detection algorithm). As with OpenCV4, you can now construct neural networks using the nn module under OpenCV. ## Text Recognition Seung uses a Connectionist Text Proposal Network (CTPN) to take the regions of text outputted by EAST detection and predict the inner text by localizing lines in a natural image. ## Customization ## Sample Query ``` | 2,416 |
isayev/ANI1_dataset | ['active learning'] | ['Less is more: sampling chemical space with active learning'] | readers/example_data_sampler.py readers/lib/pyanitools.py datapacker anidataloader | # ANI-1 dataset support repository This repository contains the scripts needed to access the ANI-1 data set. ##### If you use ANI-1 dataset please cite the following two papers: Justin S. Smith, Olexandr Isayev, Adrian E. Roitberg. *ANI-1: An extensible neural network potential with DFT accuracy at force field computational cost.* Chemical Science, 2017, DOI: 10.1039/C6SC05720A Justin S. Smith, Olexandr Isayev, Adrian E. Roitberg. *ANI-1, A data set of 20 million calculated off-equilibrium conformations for organic molecules.* Scientific Data, 4, Article number: 170193, DOI: 10.1038/sdata.2017.193 https://www.nature.com/articles/sdata2017193 ### Required software Python3.5 or better Numpy H5PY ### Included extraction software | 2,417 |
isayev/ASE_ANI | ['active learning'] | ['Less is more: sampling chemical space with active learning'] | examples/ani_quicktest.py lib/ase_mc_npt.py lib/IRC.py lib/ase_interface.py lib/hessian.py lib/pyanitools.py ensemblemolecule_multigpu dtanhcut ANIENS D3 coscut ensemblemolecule molecule_worker ANID3 aniensloader dcoscut tanhcut ANI MCBarostat vnorm get_hessian IRC vnorm calc_angle datapacker anidataloader get setMolecule setCoordinates print astype float32 copy setPairWise sleep task_done setPBC setCell enumerate loadtxt int list T product set_calculator reshape get_calculator copy flatten zeros range len flatten norm arccos dot | # ASE-ANI ### NOTICE: Python binaries built for python 3.6 and CUDA 9.2 ### Works only under Ubuntu variants of Linux with a NVIDIA GPU This is a prototype interface for ANI-1x and ANI-1ccx neural network potentials for The Atomic Simulation Environment (ASE). Current ANI-1x and ANI-1ccx potentials provide predictions for the CHNO elements. The original ANI-1 and ANI-1x potentials are available in the "deprecated_original" original branch. For best performance the ANI-1x and ANI-1ccx ensembles in this branch should be used in any application. ## REQUIREMENTS: * Python 3.6 (we recommend [Anaconda](https://www.continuum.io/downloads) distribution) * Modern NVIDIA GPU, [compute capability 5.0](https://developer.nvidia.com/cuda-gpus) of newer. * [CUDA 9.2](https://developer.nvidia.com/cuda-downloads) * [ASE](https://wiki.fysik.dtu.dk/ase/index.html) * MOPAC2012 or MOPAC2016 for some examples to compare results (Optional) | 2,418 |
isht7/pytorch-deeplab-resnet | ['semantic segmentation'] | ['DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs'] | convert_deeplab_resnet.py train.py data/create_h5.py evalpyt2.py deeplab_resnet.py init_net_surgery.py evalpyt.py get_data_from_chunk_v2 lr_poly resize_label_batch get_10x_lr_params loss_calc scale_gt read_file get_1x_lr_params_NOscale scale_im chunker flip outS load_image preprocess ceil int Variable transpose from_numpy UpsamplingBilinear2d zeros int transpose astype scale_gt uniform scale_im resize zeros float flip enumerate outS transpose LogSoftmax NLLLoss2d cuda m long bn1 layer1 requires_grad layer3 layer4 parameters modules append layer2 conv1 range len append parameters range len imread astype | # pytorch-deeplab-resnet [DeepLab resnet v2](https://arxiv.org/abs/1606.00915) model implementation in pytorch. The architecture of deepLab-ResNet has been replicated exactly as it is from the caffe implementation. This architecture calculates losses on input images over multiple scales ( 1x, 0.75x, 0.5x ). Losses are calculated individually over these 3 scales. In addition to these 3 losses, one more loss is calculated after merging the output score maps on the 3 scales. These 4 losses are added to calculate the total loss. ## Updates **18 July 2017** * One more evaluation script is added, `evalpyt2.py`. The old evaluation script `evalpyt.py` uses a different methodoloy to take mean of IOUs than the one used by [authors](https://arxiv.org/abs/1606.00915). Results section has been updated to incorporate this change. **24 June 2017** * Now, weights over the 3 scales ( 1x, 0.75x, 0.5x ) are shared as in the caffe implementation. Previously, each of the 3 scales had seperate weights. Results are almost same after making this change (more in the results section). However, the size of the trained .pth model has reduced significantly. Memory occupied on GPU(11.9 GB) and time taken (~3.5 hours) during training are same as before. Links to corresponding .pth files have been updated. * Custom data can be used to train pytorch-deeplab-resnet using train.py, flag --NoLabels (total number of labels in training data) has been added to train.py and evalpyt.py for this purpose. **Please note that labels should be denoted by contiguous values (starting from 0) in the ground truth images. For eg. if there are 7 (no_labels) different labels, then each ground truth image must have these labels as 0,1,2,3,...6 (no_labels-1).** The older version (prior to 24 June 2017) is available [here](https://github.com/isht7/pytorch-deeplab-resnet/tree/independent_wts). | 2,419 |
ishwarsawale/keras_style_transfer | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | n_style.py deprocess_image Evaluator gram_matrix eval_loss_and_grads content_loss total_variation_loss preprocess_image style_loss expand_dims preprocess_input img_to_array load_img reshape transpose astype dot transpose batch_flatten permute_dimensions gram_matrix square reshape astype f_outputs | # keras_style_transfer Keras Based Implementation of Style Transfer Algorithm Keras Style Transfer is originated from Keras <https://keras.io> example implementation of neural style transfer to create "deep" and impressive image (The original paper "A Neural Algorithm of Artistic Style" can be found at <https://arxiv.org/abs/1508.06576>) ## n_style.py > The script has been updated to work with latest Keras 2.2.0 The python script is `n_style.py` is the Keras implementation of the neural style transfer algorithm, using a pre-trained convolutional neural network (VGG19). The `run.sh` bash script takes your input {content_image}, {style_image} and {output_directory} for generating the results. ```bash sh run.sh input_image style_image output_directory ``` | 2,420 |
isukrit/encodingHumanActivity | ['time series'] | ['Deep ConvLSTM with self-attention for human activity decoding using wearables'] | codes/model_proposed/layers.py codes/model_proposed/model_with_self_attn.py codes/model_baseline/model_baseline.py model Attention SelfAttention model print LSTM Lambda sq_layer dense_layer rnn_layer Dense Model dropout_layer summary Conv2D cnn_layer Input Dropout | # Deep ConvLSTM with self-attention for human activity decoding using wearables. In this git repository we implement the proposed novel architecture for encoding human activity data for body sensors. The proposed model encodes the sensor data in both the spatial domain (whereby it selects important sensors) and the time domain (whereby it selects important time points). If you're using our code, please cite our paper (available on [ArXiV](https://arxiv.org/abs/2005.00698)): [S. P. Singh, M. K. Sharma, A. Lay-Ekuakille, D. Gangwar and S. Gupta, "Deep ConvLSTM with self-attention for human activity decoding using wearable sensors," in IEEE Sensors Journal, doi: 10.1109/JSEN.2020.3045135.](https://ieeexplore.ieee.org/document/9296308)  We have added codes for two of models that we tested: - Baseline CNN + LSTM model - Proposed model with self-attention ## Setup `pip3 install -r requirements.txt` | 2,421 |
itailang/geometric_adv | ['adversarial defense', 'adversarial attack'] | ['Geometric Adversarial Attacks and Defenses on 3D Point Clouds'] | classifier/pointnet_cls_basic.py transfer/atlasnet/auxiliary/ChamferDistancePytorch/chamfer3D/dist_chamfer_3D.py transfer/atlasnet/training/trainer.py transfer/atlasnet/auxiliary/netvision/HtmlGenerator.py classifier/tst_classifier.py src/adversary_utils.py src/autoencoder.py transfer/atlasnet/dataset/dataset_shapenet.py transfer/atlasnet/auxiliary/argument_parser.py transfer/atlasnet/training/trainer_iteration.py src/shift_rotate_util.py attacker/run_attack.py transfer/atlasnet/auxiliary/launcher.py src/in_out.py external/grouping/__init__.py external/grouping/tf_grouping_op_test.py transfer/atlasnet/auxiliary/netvision/MeshGenerator.py transfer/atlasnet/train.py transfer/atlasnet/model/atlasnet.py transfer/atlasnet/dataset/trainer_dataset.py transfer/foldingnet/prepare_graph.py attacker/prepare_indices_for_attack.py transfer/atlasnet/model/model.py transfer/atlasnet/auxiliary/trainer_iteration.py defender/run_defense_critical.py transfer/atlasnet/dataset/pointcloud_processor.py src/adversary_autoencoder.py classifier/provider.py defender/run_defense_surface.py src/ae_templates.py src/tf_utils.py transfer/foldingnet/foldingnet_ae.py transfer/atlasnet/dataset/augmenter.py autoencoder/train_ae.py classifier/tf_util.py transfer/foldingnet/train_foldingnet.py autoencoder/tst_ae.py classifier/train_classifier.py attacker/get_dists_per_point.py transfer/atlasnet/auxiliary/sampling_and_meshing/O-CNN/process_raw_obj.py transfer/run_transfer.py transfer/atlasnet/auxiliary/ChamferDistancePytorch/chamfer3D/setup.py transfer/atlasnet/auxiliary/sampling_and_meshing/O-CNN/pcSamplingInfRayShapeNet.py transfer/atlasnet/auxiliary/sampling_and_meshing/O-CNN/sample30kpoints.py transfer/atlasnet/auxiliary/visualization.py transfer/atlasnet/auxiliary/metro.py transfer/atlasnet/auxiliary/netvision/ChartGenerator.py transfer/foldingnet/tst_foldingnet.py src/general_utils.py classifier/pointnet_cls.py defender/get_knn_dists_per_point.py transfer/atlasnet/training/trainer_abstract.py src/adv_ae.py transfer/atlasnet/auxiliary/ChamferDistancePytorch/fscore.py transfer/atlasnet/auxiliary/sampling_and_meshing/Shuffle/parallel_shuffle.py transfer/atlasnet/auxiliary/sampling_and_meshing/Shuffle/shuffle.py transfer/atlasnet/model/model_blocks.py transfer/atlasnet/auxiliary/sampling_and_meshing/O-CNN/randomizePointCloud.py classifier/run_classifier.py transfer/atlasnet/model/trainer_model.py transfer/atlasnet/auxiliary/netvision/ConfusionMatrixGenerator.py classifier/evaluate_classifier.py transfer/atlasnet/model/template.py transfer/atlasnet/auxiliary/ChamferDistancePytorch/chamfer_python.py external/python_plyfile/plyfile.py transfer/atlasnet/auxiliary/netvision/Table.py transfer/atlasnet/auxiliary/ChamferDistancePytorch/unit_test.py transfer/atlasnet/training/metro.py transfer/atlasnet/training/launcher.py src/ae_utils.py attacker/evaluate_attack.py transfer/atlasnet/training/trainer_loss.py defender/evaluate_defense.py transfer/atlasnet/auxiliary/trainer_loss.py transfer/atlasnet/atlasnet_ae.py src/encoders_decoders.py external/grouping/tf_grouping.py src/adversary.py transfer/evaluate_transfer.py transfer/foldingnet/foldingnet.py transfer/atlasnet/dataset/mesh_processor.py transfer/atlasnet/auxiliary/my_utils.py transfer/atlasnet/auxiliary/html_report.py src/pointnet_ae.py transfer/atlasnet/auxiliary/init_html_report.py classifier/pointnet_classifier.py transfer/atlasnet/auxiliary/trainer_abstract.py external/structural_losses/tf_approxmatch.py src/neural_net.py transfer/atlasnet/auxiliary/meter.py external/structural_losses/tf_nndistance.py classifier/transform_nets.py transfer/atlasnet/model/resnet.py sort_dist_mat get_chamfer_nn get_latent_nn get_rand_idx PointNetClassifier get_model get_loss placeholder_inputs get_model get_loss placeholder_inputs rotate_point_cloud_by_angle shuffle_data rotate_point_cloud jitter_point_cloud batch_norm_template batch_norm_for_conv1d conv2d_transpose dropout fully_connected conv3d batch_norm_for_conv2d batch_norm_for_fc avg_pool2d conv2d conv1d avg_pool3d max_pool3d max_pool2d _variable_with_weight_decay batch_norm_for_conv3d _variable_on_cpu get_learning_rate eval_one_epoch log_string train_one_epoch train get_bn_decay feature_transform_net input_transform_net eval_one_epoch log_string evaluate query_ball_point group_point select_top_k _group_point_grad knn_point GroupPointTest _open_stream _lookup_type PlyData _split_line PlyProperty PlyParseError make2d PlyListProperty PlyElement _match_cost_grad match_cost _match_cost_shape approx_match _approx_match_shape _nn_distance_grad _nn_distance_shape nn_distance Adversary AdversaryAutoEncoder write_classification_statistics_to_file write_defense_statistics_to_file prepare_data_for_attack get_quantity_at_index_per_target_class write_transfer_statistics_to_file load_data get_quantity_at_index get_outlier_pc_inlier_pc get_quantity_for_targeted_untargeted_attack get_idx_for_correct_pred write_attack_statistics_to_file AdvAE default_train_params mlp_architecture get_critical_pc_non_critical_pc get_critical_points AutoEncoder Configuration decoder_with_fc_only decoder_with_convs_only encoder_with_convs_and_symmetry apply_augmentations get_complementary_idx get_complementary_points rand_rotation_matrix plot_3d_point_cloud plot_heatmap_graph unit_cube_grid_point_cloud get_dist_mat iterate_in_chunks add_gaussian_noise_to_pcloud PointCloudDataSet pc_loader load_and_split_all_point_clouds_under_folder load_ply files_in_subdirs unpickle_data create_dir load_dataset load_all_point_clouds_under_folder split_data pickle_data snc_category_to_synth_id load_point_clouds_from_filenames NeuralNet PointNetAutoEncoder scale_object samp_object euler2mat_np euler2mat_tf sort_axes get_sort_axes_idx reset_tf_graph safe_log leaky_relu replicate_parameter_for_all_layers expand_scope_by_name AtlasNetAutoEncoder parser parser_transfer main main job_scheduler_parralel Experiments job_scheduler_sequential get_first_available_gpu AverageValueMeter Logs main isolate_files metro blue_print green_print print_arg cyan_print yellow_print red_print grey_print plant_seeds white_print magenta_print TrainerAbstract TrainerIteration TrainerLoss is_port_in_use Visualizer distChamfer NN_loss pairwise_dist fscore chamfer_3DFunction chamfer_3DDist Chart ChartGenerator ColorMap ConfusionMatrixGenerator HtmlGenerator MeshGenerator Mesh TableException Table main Count sample_instance shoot_rays main main shuffle_pc shuffle_folder main test_folder test_pc main shuffle_pc main shuffle_pc Augmenter ShapeNet ColorMap save barycentric Normalization Operation DataAugmentation TranslationFunctions ScaleFunctions FunctionGenerator RotationFunctions TrainerDataset Atlasnet weights_init EncoderDecoder Mapping2Dto3D get_activation PointNet Identity ResNet resnet50 Bottleneck resnet152 conv3x3 resnet34 resnet18 BasicBlock resnet101 SphereTemplate get_template Template SquareTemplate TrainerModel job_scheduler_parralel Experiments job_scheduler_sequential get_first_available_gpu main isolate_files metro Trainer TrainerAbstract TrainerIteration TrainerLoss GridSamplingLayer ChamferDistance FoldingNet_graph FoldingNetDecFold2 FoldingNetDecFold1 ChamferLoss FoldingNetDec Graph_Pooling FoldingNetEnc_with_graph FoldingNetAutoEncoder build_graph knn_search build_graph_core edges2A GraphOptions seed join arange ones min shuffle save num_instance_per_class sort_dist_mat join get_dist_mat save save nn_distance exists Session run ones placeholder shape expand_dims range tile load reset_tf_graph time join print reshape float32 reduce_mean sort_dist_mat len ones shape astype int16 int32 float32 placeholder value dropout reshape squeeze fully_connected matmul conv2d max_pool2d expand_dims value l2_loss transpose matmul sparse_softmax_cross_entropy_with_logits reduce_mean scalar arange shuffle len reshape cos pi dot shape uniform sin zeros array range reshape cos dot shape sin zeros array range shape clip randn multiply add_to_collection xavier_initializer _variable_on_cpu l2_loss truncated_normal_initializer print write flush exponential_decay maximum minimum exponential_decay load join sum squeeze log_string shuffle_data jitter_point_cloud train_labels add_summary float argmax train_data range run load join argmax sum val_labels squeeze log_string mean float val_data array range run value reshape fully_connected conv2d max_pool2d expand_dims value fully_connected reshape conv2d max_pool2d join restore eval_one_epoch log_string ConfigProto Session pi rotate_point_cloud_by_angle save test_labels open shape dump_dir enumerate print write test_data zeros value print slice reduce_sum select_top_k tile expand_dims append split dtype len property hasattr property property property with_rank with_rank match_cost_grad with_rank load join enumerate len concatenate reshape copy shape vstack append expand_dims range get_idx_for_correct_pred len array range len range enumerate len shape range zeros get_quantity_at_index reshape get_quantity_at_index_per_target_class shape get_quantity_at_index zeros range zeros_like shape zeros range len join len write mean vstack enumerate join len write mean vstack enumerate join len write mean vstack enumerate join len write mean vstack enumerate pop join shape unique save zeros argmax max range zeros_like get_complementary_points get_critical_points range len str pool dropout print symmetry closing non_linearity conv_op replicate_parameter_for_all_layers batch_normalization expand_scope_by_name range len str dropout print fully_connected non_linearity replicate_parameter_for_all_layers batch_normalization expand_scope_by_name range len str dropout print non_linearity conv_op replicate_parameter_for_all_layers batch_normalization tile expand_scope_by_name range len seed cos pi dot sqrt uniform sin array get_complementary_idx shape zeros range len full arange norm expand_dims tile len range len normal T rand_rotation_matrix dot z_rotate copy ndarray reshape float32 float range show set_ylim3d view_init min add_subplot set_xlim tight_layout set_zlim3d axis colorbar title scatter set_zlim figure set_xlim3d max set_ylim xlabel close ylabel tight_layout set title savefig figure DataFrame heatmap makedirs dump len close open load close range open join search walk compile read T hstack vstack append split join print merge load_and_split_all_point_clouds_under_folder append range point_clouds len load_point_clouds_from_filenames PointCloudDataSet split_data load_point_clouds_from_filenames join format print len close warn imap unique empty Pool enumerate seed int arange shuffle expand_dims min max norm shuffle copy int T zeros_like get_sort_axes_idx range len min max cos astype matmul float32 dot sin array constant value squeeze cos matmul stack sin append range isinstance tolist array reset_default_graph close EasyDict dir_name id ArgumentParser demo exists str list train_pc_path eval_pc_path parse_args __dict__ env colored isoformat keys pop join print cyan_print add_argument system now test_pc_path EasyDict dir_name id demo exists str list train_pc_path eval_pc_path env colored isoformat keys pop join print cyan_print system now test_pc_path join deepcopy chart dir_name add_table add_row fscore_curve return_html avg add_title add_titleless_columns data_curve HtmlGenerator range add_column print system new_query range len pop get_first_available_gpu list print system sleep keys pop get_first_available_gpu list print system sleep keys decode print check_output float find load_mesh join load copy save_mesh mkdir save parse_args add_argument ArgumentParser print colored print colored print colored print colored print colored print colored print colored print colored str __dict__ cyan_print print colored print randint seed manual_seed t expand_as min pairwise_dist bmm size transpose expand sum mean float join system rename makedirs join remove sorted failed_example_path print any shapenet_path makedirs EasyDict __dict__ shoot_rays test_folder print shuffle_folder load_mesh deepcopy permutation vertices save len print join failed_example_path makedirs load print save choice print join failed_example_path makedirs faces form_mesh save_mesh add_attribute set_attribute shuffle_pc output input get_attribute astype save_mesh add_attribute set_attribute multiply sum normal_ __name__ fill_ load_url ResNet load_state_dict load_url ResNet load_state_dict load_url ResNet load_state_dict load_url ResNet load_state_dict load_url ResNet load_state_dict get reshape repeat meshgrid zeros range len size squeeze min mean pow unsqueeze repeat sum ones astype zeros range len T reshape KDTree query dict zeros range reshape mode knn_search edges2A partial num_points close GraphOptions map from_numpy append zeros Pool | # Geometric Adversarial Attacks and Defenses on 3D Point Clouds Created by Itai Lang, Uriel Kotlicki, and Shai Avidan from Tel Aviv University. [[Paper]](https://arxiv.org/abs/2012.05657) [[Introduction Video (2 minutes)]](https://slideslive.com/38972228/geometric-adversarial-attacks-and-defenses-on-3d-point-clouds) [[Introduction Slides]](./doc/introduction_slides.pdf) [[Full Video (10 minutes)]](https://slideslive.com/38972369/geometric-adversarial-attacks-and-defenses-on-3d-point-clouds) [[Full Slides]](./doc/full_slides.pdf) [[Poster]](./doc/poster.pdf)  ## Introduction This code repository is based on our [arXiv tech report](https://arxiv.org/abs/2012.05657). Please read it for more information. Deep neural networks are prone to adversarial examples that maliciously alter the network's outcome. Due to the increasing popularity of 3D sensors in safety-critical systems and the vast deployment of deep learning models for 3D point sets, there is a growing interest in adversarial attacks and defenses for such models. So far, the research has focused on the semantic level, namely, deep point cloud classifiers. However, point clouds are also widely used in a geometric-related form that includes encoding and reconstructing the geometry. In this work, we are the first to consider the problem of adversarial examples at a geometric level. In this setting, the question is how to craft a small change to a clean source point cloud that leads, after passing through an autoencoder model, to the reconstruction of a different target shape. Our attack is in sharp contrast to existing semantic attacks on 3D point clouds. While such works aim to modify the predicted label by a classifier, we alter the entire reconstructed geometry. Additionally, we demonstrate the robustness of our attack in the case of defense, where we show that remnant characteristics of the target shape are still present at the output after applying the defense to the adversarial input. ## Citation If you find our work useful in your research, please consider citing: | 2,422 |
its-mayank/SqueezeAttention-PyTorch | ['semantic segmentation'] | ['Squeeze-and-Attention Networks for Semantic Segmentation'] | SABlock.py conv_block SqueezeAttentionBlock | # SqueezeAttention-PyTorch It has my implementation of Squeeze and Attention Networks in PyTorch which are defined in Zhong et al. https://arxiv.org/abs/1909.03402 Feel Free to open any issue if you see anything wrong or any improvement! | 2,423 |
itsron717/Neural-Style-Transfer | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | style_transfer.py Evaluator gram_matrix eval_loss_and_grads content_loss total_variation_loss style_loss dot transpose batch_flatten permute_dimensions gram_matrix square reshape astype f_outputs | # Neural Style Transfer ## Introduction This is a Keras implementation of the paper [A Neural Algorithm of Artistic Style](https://arxiv.org/abs/1508.06576) by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge. The paper presents an algorithm for combining the content of one image with the style of another image using convolutional neural networks. ## Usage ``` $ python3 style_transfer.py content.jpg style.jpg ``` ## Input <p float="left"> | 2,424 |
iurteaga/hmc | ['gaussian processes'] | ['Towards Personalized Modeling of the Female Hormonal Cycle: Experiments with Mechanistic Models and Gaussian Processes', 'Multi-Task Gaussian Processes and Dilated Convolutional Networks for Reconstruction of Reproductive Hormonal Dynamics'] | scripts/plot_hmc_data.py src/MGP_DCNN/TNN.py src/MGP_DCNN/data_processing.py src/MGP_DCNN/MGP.py src/MGP_DCNN/RNN.py src/MGP_DCNN/MGP_subclasses.py scripts/mlhc2019.py scripts/evaluate_predict_hmc_gp_xtime.py src/MGP_DCNN/TNN_subclasses.py scripts/execute_predict_hmc_gp_xtime.py src/predict_hmc_gp_xtime.py src/MGP_DCNN/expected_distance.py main main plot_GP_predict_y_error plot_GP_predict_peaks fit_GP main plot_GP_predict_y change_representation_covariance_matrix reorganize_samples_single_id generate_posterior_samples align_data_on_peak select_subset_of_points generate_samples_single_id_with_covar_matrix generate_samples_single_id from_samples_vector_to_final_array generate_samples_single_id_with_covar_matrix_2 prepare_data_before_GP import_and_split_data_train_val_test compute_ed_sampling_list expected_distance resample_data_for_ed train_Block_MGP_multiple_individuals Block_MGP Multitask_GP_Model Single_task_GP_model RNN_time_prediction Time_Neural_Network RNN_time_prediction CNN_time_prediction arange where abs max sorted shape append sum format size astype power listdir diff enumerate int isdir print loadtxt nanmean split array len join replace system GPR optimize setPrior setOptimizer show fm arange plot xlabel size min close ylabel scatter savefig figure legend fill_between xlim max axvspan show arange plot xlabel size close ylabel savefig figure legend power xlim axvspan show arange plot xlabel size close ylabel savefig figure legend xlim sum axvspan randn linspace Periodic predict concatenate unique Const fit_GP zeros std makedirs append argmax vstack range permutation arange setdiff1d concatenate ones sort find_peaks range arange reshape shape float array fit_transform len normal reshape dot cholesky eye tile reshape swapaxes reorganize_samples_single_id print shape generate_samples_single_id empty range reshape range zeros normal reshape dot cholesky eye tile reshape swapaxes show arange subplots plot print reshape randint shape swapaxes tile zeros empty range len zeros_like concatenate resample shape find_peaks range cdf sum array pdf arange Block_MGP argmax test_block_model list ones shape append expected_distance range format setdiff1d concatenate plot_model mean float print build_and_train_block_models len arange Block_MGP test_block_model ones shape append range format plot_model close nan T print build_and_train_block_models File index create_dataset array len Model Input compile Adam range l2 Adam Model Input range compile | # Hormonal menstrual cycle project Repository for the work on hormonal menstrual cycle: experiments with mechanistic models and machine learning. ## References [1] Towards Personalized Modeling of the Female Hormonal Cycle: Experiments with Mechanistic Models and Gaussian Processes, Iñigo Urteaga, David J. Albers, Marija Vlajic Wheeler, Anna Druet, Hans Raffauf, Noémie Elhadad, Accepted at NIPS 2017 Workshop on Machine Learning for Health (https://ml4health.github.io/2017/) [2] Multi-Task Gaussian Processes and Dilated Convolutional Networks for Reconstruction of Reproductive Hormonal Dynamics, Iñigo Urteaga, Tristan Bertin, Theresa M. Hardy, David J. Albers, Noémie Elhadad, Presented at Machine Learning for Healtcare (MLHC) 2019 (https://arxiv.org/abs/1908.10226) ## Directories ### src Directory where the algorithms for simulation and prediction of hmc data are implemented. ./src/ contains the GP based prediction code presented in [1]. ./src/MGP_DCNN/ contains the MGP+DCNN python implementation developed in collaboration with https://github.com/TristanBertin and presented in [2]. | 2,425 |
ivanfeliciano/AnimalAI-INAOE | ['unity'] | ['Unity: A General Platform for Intelligent Agents'] | data_generator/copy_config_to_dirs.py examples/animalai_train/animalai_train/trainers/bc/online_trainer.py examples/trainCurriculum.py animalai/animalai/communicator_objects/__init__.py animalai/animalai/envs/environment.py examples/animalai_train/animalai_train/trainers/meta_curriculum.py animalai/animalai/communicator_objects/unity_rl_reset_input_pb2.py examples/animalai_train/animalai_train/trainers/buffer.py simplifiedEnv/dqn_video.py data_generator/prueba_gym.py config_maker/draw_arena.py examples/animalai_train/animalai_train/trainers/bc/models.py animalai/animalai/communicator_objects/unity_input_pb2.py examples/animalai_kerasRL.py examples/animalai_train/animalai_train/trainers/bc/trainer.py animalai/animalai/communicator_objects/space_type_proto_pb2.py animalai/animalai/communicator_objects/unity_message_pb2.py examples/animalai_train/animalai_train/trainers/policy.py examples/visualizeLightsOff.py firstSubmission/animal_ai_save_data.py animalai/animalai/communicator_objects/arena_parameters_proto_pb2.py animalai/animalai/communicator_objects/unity_rl_input_pb2.py firstSubmission/prueba_gym.py animalai/animalai/envs/arena_config.py animalai/animalai/communicator_objects/unity_rl_output_pb2.py animalai/animalai/communicator_objects/brain_parameters_proto_pb2.py examples/animalai_train/setup.py examples/animalai_train/animalai_train/trainers/learn.py examples/animalai_train/animalai_train/trainers/exception.py animalai/animalai/envs/__init__.py examples/submission/agent.py examples/trainMLAgents.py examples/animalai_train/animalai_train/trainers/bc/offline_trainer.py examples/animalai_train/animalai_train/trainers/trainer_controller.py animalai/animalai/envs/socket_communicator.py agent.py examples/animalai_train/animalai_train/trainers/__init__.py examples/trainDopamine.py data_generator/visualizeArena.py animalai/animalai/communicator_objects/unity_rl_reset_output_pb2.py animalai/animalai/envs/brain.py examples/distance.py firstSubmission/test_submission/testDocker.py animalai/animalai/envs/communicator.py examples/prueba_gym.py examples/animalai_train/animalai_train/trainers/curriculum.py examples/animalai_train/animalai_train/trainers/barracuda.py simplifiedEnv/assisted_policy.py examples/animalai_train/animalai_train/trainers/ppo/models.py animalai/animalai/envs/gym/environment.py examples/animalai_train/animalai_train/__init__.py animalai/animalai/communicator_objects/unity_to_external_pb2.py simplifiedEnv/assisted_agent.py animalai/setup.py examples/animalai_train/animalai_train/trainers/trainer.py simplifiedEnv/test.py animalai/animalai/communicator_objects/header_pb2.py simplifiedEnv/visualizeArena.py animalai/animalai/communicator_objects/agent_action_proto_pb2.py animalai/animalai/communicator_objects/command_proto_pb2.py data_generator/configs/animal-cognition/generate_files.py examples/visualizeArena.py examples/animalai_train/animalai_train/trainers/bc/policy.py examples/animalai_train/animalai_train/trainers/ppo/policy.py animalai/animalai/communicator_objects/unity_rl_initialization_output_pb2.py examples/animalai_train/animalai_train/trainers/ppo/trainer.py examples/animalai_train/animalai_train/dopamine/animalai_lib.py animalai/animalai/communicator_objects/agent_info_proto_pb2.py examples/animalai_train/animalai_train/trainers/models.py animalai/animalai/communicator_objects/unity_output_pb2.py animalai/animalai/__init__.py simplifiedEnv/generate_config_files_modified_env.py examples/submission/test_submission/testDocker.py simplifiedEnv/animalai_kerasRL.py animalai/animalai/communicator_objects/demonstration_meta_proto_pb2.py examples/animalai_train/animalai_train/trainers/bc/__init__.py animalai/animalai/communicator_objects/unity_rl_initialization_input_pb2.py animalai/animalai/communicator_objects/unity_to_external_pb2_grpc.py prueba_gym.py animalai/animalai/envs/exception.py animalai/animalai/envs/rpc_communicator.py firstSubmission/agent.py animalai/animalai/communicator_objects/engine_configuration_proto_pb2.py examples/animalai_train/animalai_train/trainers/tensorflow_to_barracuda.py data_generator/generate_datasets.py examples/animalai_train/animalai_train/trainers/demo_loader.py animalai/animalai/communicator_objects/resolution_proto_pb2.py examples/animalai_train/animalai_train/trainers/ppo/__init__.py Agent get_colours UnityToExternalServicer UnityToExternalStub add_UnityToExternalServicer_to_server Vector3 ArenaConfig constructor_item RGB constructor_arena Item Arena BrainInfo BrainParameters Communicator UnityEnvironment UnityWorkerInUseException UnityException UnityTimeOutException UnityEnvironmentException UnityActionException RpcCommunicator UnityToExternalServicerImplementation SocketCommunicator AnimalAIEnv UnityGymException ActionFlattener main init_environment tunnel_tasks ArenaConfig detour_tasks build_y_mazes save_arena AnimalAIProcessor create_env_fn create_agent_fn init_environment load_config init_environment run_step_imshow initialize_animation rainbow_network nature_dqn_network implicit_quantile_network BarracudaWriter compress Build sort lstm write fuse_batchnorm_weights trim gru Model summary Struct parse_args to_json rnn BufferException Buffer Curriculum make_demo_buffer load_demonstration demo_to_buffer CurriculumError MetaCurriculumError TrainerError run_training prepare_for_docker_run init_environment try_create_meta_curriculum main load_config MetaCurriculum LearningModel Policy UnityPolicyException get_layer_shape pool_to_HW flatten process_layer process_model basic_lstm get_attr ModelBuilderContext order_by get_epsilon get_tensor_dtype replace_strings_in_list get_tensor_dims by_op remove_duplicates_from_list by_name convert strides_to_HW get_tensor_data gru UnityTrainerException Trainer TrainerController BehavioralCloningModel OfflineBCTrainer OnlineBCTrainer BCPolicy BCTrainer PPOModel PPOPolicy PPOTrainer get_gae discount_rewards Agent main Agent get_colours get_colours main AnimalAIProcessor count_pixels AssistedAgent get_colours count_pixels get_colours AssistedPolicy DQNAgentVideoRecording save_arena ArenaMatrix ArenaConfig generate_basic_good init_environment method_handlers_generic_handler add_generic_rpc_handlers construct_mapping construct_mapping format copyfile makedirs replace format Vector3 save_arena randint Item range randint range Vector3 format Vector3 degrees save_arena sqrt randint atan range print AnimalAIEnv zeros set_data range str suptitle set_data randint step range fully_connected float32 flatten div conv2d cast variance_scaling_initializer fully_connected reshape float32 reduce_sum flatten conv2d div cast softmax variance_scaling_initializer constant fully_connected multiply cos float32 pi flatten conv2d div cast tile random_uniform range join isdir print replaceFilenameExtension add_argument exit verbose source_file ArgumentParser target_file sqrt topologicalSort list hasattr layers addEdge Graph print inputs set len list hasattr layers print filter match trim_model compile data layers print tensors float16 replace layers dumps data dtype layers isinstance print name tensors inputs outputs shape zip array_without_brackets to_json globals Build tanh mad tanh mul Build concat add sigmoid sub mad _ tanh mul Build concat add sigmoid mad Buffer reset_local_buffers number_visual_observations append_update_buffer append range enumerate make_demo_buffer load_demonstration number_steps read suffix BrainParametersProto from_agent_proto DemonstrationMetaProto ParseFromString AgentInfoProto append from_proto _DecodeVarint32 start_learning int str format external_brain_names TrainerController put init_environment try_create_meta_curriculum load_config list MetaCurriculum keys chmod format basename isdir glob copyfile copytree prepare_for_docker_run int Process getLogger print run_training start Queue info append randint docopt range endswith len HasField hasattr get_attr tensor_shape ndarray isinstance shape int_val bool_val float_val ListFields name ndarray isinstance str tensor_content ndarray product isinstance get_tensor_dtype print get_tensor_dims unpack int_val bool_val array float_val enter append add set name find_tensor_by_name split name lstm find_tensor_by_name find_forget_bias split get_layer_shape id Struct tensor hasattr name patch_data input_shapes out_shapes input get_attr append replace_strings_in_list tensors astype op zip enumerate print float32 patch_data_fn model_tensors map_ignored_layer_to_its_input co_argcount len items list get_tensors hasattr name print process_layer eval ModelBuilderContext layers verbose Struct process_model open compress node GraphDef Model dims_to_barracuda_shape insert get_tensor_dims inputs MessageToJson ParseFromString cleanup_layers read memories print sort write trim summary list zeros_like size reversed range asarray tolist discount_rewards Agent exec_module ArenaConfig AnimalAIEnv module_from_spec resolution t reset spec_from_file_location step range get_colours len type list format print sort sample randint range len | # Animal-AI Olympics <p align="center"> <img height="300" src="documentation/PrefabsPictures/steampunkFOURcrop.png"> </p> **July 1st - November 1st** The Animal-AI Olympics is an AI competition with tests inspired by animal cognition. Participants are given a small environment with just seven different classes of objects that can be placed inside. In each test, the agent needs to retrieve the food in the environment, but to do so there are obstacles to overcome, ramps to climb, boxes to push, and areas that must be avoided. The real challenge is that we don't provide the tests in advance. It's up to you to explore the possibilities with the environment and build interesting configurations that can help create an agent that understands how the environment's physics work and the affordances that it has. The final submission should be an agent capable of robust food retrieval behaviour similar to that of many kinds of animals. We know the animals can pass these tests, it's time to see if AI can too. ## Prizes $32,000 (equivalent value) * Overall Prizes * 1st place overall: **$7,500 total value** - $6,500 with up to $1,000 travel to speak at NeurIPS 2019. * 2nd place overall: **$6,000 total value** - $5,000 with up to $1,000 travel to speak at NeurIPS 2019. | 2,426 |
ivanvovk/DurIAN | ['speech synthesis'] | ['DurIAN: Duration Informed Attention Network For Multimodal Synthesis'] | logger.py model/__init__.py model/decoder.py torchaudio/mel.py tests/test_default_forward_pass.py loss.py tests/test_baseline_backward_pass.py train.py model/encoder.py model/layers.py data.py model/duration.py trainer.py model/prenet.py torchaudio/vocoders.py tests/test_data_loading.py inference.py torchaudio/autils.py tests/base.py torchaudio/stft.py utils.py model/utils.py model/postnet.py text/text_frontend.py model/base.py tests/test_baseline_forward_pass.py model/model.py text/__init__.py model/baseline.py tests/test_default_backward_pass.py model/alignment.py str_to_int_list Dataset BatchCollate inference load_model test Logger MaskedL2Loss DurIANLoss run ModelTrainer plot_tensor_to_numpy save_figure_to_numpy get_lr show_message AlignmentModule BaseModule BaseDurIAN BaselineDurIAN BaselineBackboneModel Decoder BaselineDecoder DurationModel CBHG BaselineEncoder Conv1dResidualBlock Highway BatchNormConv1d DurIAN BackboneModel Postnet Prenet get_mask_from_lengths suite BaseModelBackwardPassTest BaseModelForwardPassTest BaselineDurIANBackwardPassJoinTest BaselineDurIANBackwardPassBCETest BaselineDurIANBackwardPassMSETest BaselineDurIANForwardPassTest DurIANBackwardPassJoinTest DurIANBackwardPassBCETest DurIANBackwardPassMSETest DurIANForwardPassTest TextFrontend window_sumsquare MelTransformer STFT griffin_lim TTS_FRONTEND finetune_duration_model finetune_backbone_model mel_basis stft_fn griffin_lim transpose spectral_de_normalize unsqueeze MelTransformer mm load_model LongTensor SYMBOLS TextFrontend eval inference len validate show_message SYMBOLS DataLoader ReduceLROnPlateau save_checkpoint Logger compute_loss cuda ModelTrainer get_current_lrs Adam BatchCollate parse_batch TTS_FRONTEND range update log_training run_backward DurIANLoss step Dataset len print param_groups reshape tostring_rgb fromstring subplots use draw close tight_layout colorbar imshow save_figure_to_numpy to unsqueeze cat item append TestSuite loadTestsFromTestCase TestLoader split get_window normalize pad_center zeros range exp angle Variable squeeze rand astype float32 pi from_numpy transform range | # DurIAN Implementation of "Duration Informed Attention Network for Multimodal Synthesis" (https://arxiv.org/pdf/1909.01700.pdf) paper. **Status**: released # 1 Info DurIAN is encoder-decoder architecture for text-to-speech synthesis task. Unlike prior architectures like Tacotron 2 it doesn't learn attention mechanism but takes into account phoneme durations information. So, of course, to use this model one should have phonemized and duration-aligned dataset. However, you may try to use pretrained duration model on LJSpeech dataset (CMU dict used). Links will be provided below. # 2 Architecture details DurIAN model consists of two modules: backbone synthesizer and duration predictor. Here are some of the most notable differences from DurIAN described in paper: * Prosodic boundary markers aren't used (didn't have them labeled), and thus there's no 'skip states' exclusion of prosodic boundaries' hidden states * Style codes aren't used too (same reason) * Removed Prenet before CBHG encoder (didn't improved accuracy during experiments) | 2,427 |
ivipsourcecode/RaP-Net | ['indoor localization', 'visual localization'] | ['RaP-Net: A Region-wise and Point-wise Weighting Network to Extract Robust Features for Indoor Localization'] | lib/utils.py lib/exceptions.py lib/nms.py lib/model_test.py extract_features.py NoGradientError EmptyTensorError DenseFeatureExtractionModule HardDetectionModule RegionWeight HandcraftedLocalizationModule RaPNet nms_point imshow_image interpolate_dense_features downscale_positions savefig upscale_positions preprocess_image grid_positions astype where argsort pad enumerate reshape transpose astype float32 array uint8 reshape transpose astype array repeat range range arange size min stack device float long cat gcf set_major_locator NullLocator axes axis margins subplots_adjust | # RaP-Net RaP-Net apply **R**egion-wise weight, reflecting the invariability of regions, to re-weight **P**oint-wise reliability of each pixel and extract local features for robust indoor localization. Technical details are described in [this paper](https://arxiv.org/abs/2012.00234) (under review) > ``` > Dongjiang Li, Jinyu Miao, Xuesong Shi, Yuxin Tian, Qiwei Long, Tianyu Cai, Ping Guo, Hongfei Yu, Wei Yang, Haosong Yue, Qi Wei, Fei Qiao, "RaP-Net: A Region-wise and Point-wise Weighting Network to Extract Robust Features for Indoor Localization," arXiv preprint arXiv:2012.00234, 2020. > ``` If you use RaP-net in an academic work, please cite: ``` @article{li2020rapnet, title={RaP-Net: A Region-wise and Point-wise Weighting Network to Extract Robust Features for Indoor Localization}, author={Dongjiang Li and Jinyu Miao and Xuesong Shi and Yuxin Tian and Tianyu Cai and Qiwei Long and Ping Guo and Hongfei Yu and Wei Yang and Haosong Yue and Qi Wei and Fei Qiao}, | 2,428 |
ivri/DiffVec | ['word embeddings'] | ['Take and Took, Gaggle and Goose, Book and Read: Evaluating the Utility of Vector Differences for Lexical Relation Learning'] | preprocess.py cluster.py generate_NS.py | # DiffVec The dataset for evaluating of vector differences. ## Take and Took, Gaggle and Goose, Book and Read: Evaluating the Utility of Vector Differences for Lexical Relation Learning *Ekaterina Vylomova, Laura Rimell, Trevor Cohn, and Timothy Baldwin* Recent work has shown that simple vector subtraction over word embeddings is surprisingly effective at capturing different lexical relations, despite lacking explicit supervision. Prior work has evaluated this intriguing result using a word analogy prediction formulation and hand-selected relations, but the generality of the finding over a broader range of lexical relation types and different learning settings has not been evaluated. In this paper, we carry out such an evaluation in two learning settings: (1) spectral clustering to induce word relations, and (2) supervised learning to classify vector differences into relation types. We find that word embeddings capture a surprising amount of information, and that, under suitable supervised training, vector subtraction generalises well to a broad range of relations, | 2,429 |
ixa-ehu/rec-coco | ['common sense reasoning'] | ['Inferring spatial relations from textual descriptions of images'] | code_bert_ft_SO/learn_and_eval.py code_bert_ft_SO/write_data.py code_capt/eval_tools.py code_capt/models.py code_bert_ft_cap/models.py code_bert_ft_SRO/data_tools.py code_bert_ft_SRO/write_data.py code_capt/param_tools.py embeddings/clean_embeddings.py code_bert_ft_cap/param_tools.py code/learn_and_eval.py code_bert_ft_SRO/models.py code/write_data.py code_bert_ft_SO/pre-process_data.py code/models.py code_capt/learn_and_eval.py code_bert_ft_SO/models.py code_bert_ft_SRO/read_data.py code_bert_ft_SO/eval_tools.py code_bert_ft_SO/param_tools.py code_capt/data_tools.py code_bert_ft_cap/eval_tools.py code_bert_ft_cap/read_data.py code_bert_ft_SRO/pre-process_data.py code_bert_ft_SRO/eval_tools.py code_bert_ft_cap/pre-process_data.py code_capt/write_data.py code/read_data.py code/param_tools.py code_bert_ft_SRO/learn_and_eval.py code_capt/get_bert_embeddings.py code_bert_ft_SRO/param_tools.py code_capt/read_data.py code/pre-process_data.py code_bert_ft_cap/learn_and_eval.py code/data_tools.py code/eval_tools.py code_bert_ft_cap/data_tools.py code_bert_ft_SO/data_tools.py code_bert_ft_cap/write_data.py code_capt/pre-process_data.py code_bert_ft_SO/read_data.py coord2pixel_indiv get_random_EMB get_folds get_TRAIN_relevant pixl_idx2coord_all_examples get_maximums_idx aux_get_train_test_splits get_data wordlist2emb_matrix compute_centers get_CLEAN_train_test_idx get_GEN get_enforce_gen relevant_instances2X_and_y mirror_x pixl_idx2coord_indiv build_emb_dict find_threshold evaluate_perf_COORD merge_two_dicts classification_f1_acc evaluate_perf_PIXL correlations evaluate_perf bb_intersection_over_union_arrays main NeuralnetModel get_default_params bool_str main load_dict_data readDATA load_training_data readWordlist write_results_all matrix2csv write_results_enf_gen get_folder_name writeCSV write_indiv_predictions coord2pixel_indiv get_folds getCaptionWords get_maximums_idx get_data get_BERT_Embeddings get_enforce_gen mirror_x build_emb_dict get_TRAIN_relevant pixl_idx2coord_all_examples aux_get_train_test_splits get_GEN relevant_instances2X_and_y get_CLEAN_train_test_idx pixl_idx2coord_indiv get_random_EMB getCaptionIndices compute_centers wordlist2emb_matrix find_threshold evaluate_perf_COORD merge_two_dicts classification_f1_acc evaluate_perf_PIXL correlations evaluate_perf bb_intersection_over_union_arrays main NeuralnetModel get_default_params bool_str main load_dict_data readDATA load_training_data readWordlist write_results_all matrix2csv write_results_enf_gen get_folder_name writeCSV write_indiv_predictions coord2pixel_indiv get_folds getCaptionWords get_maximums_idx get_data get_BERT_Embeddings get_enforce_gen mirror_x build_emb_dict get_TRAIN_relevant pixl_idx2coord_all_examples aux_get_train_test_splits get_GEN relevant_instances2X_and_y get_CLEAN_train_test_idx pixl_idx2coord_indiv get_random_EMB getCaptionIndices compute_centers wordlist2emb_matrix find_threshold evaluate_perf_COORD merge_two_dicts classification_f1_acc evaluate_perf_PIXL correlations evaluate_perf bb_intersection_over_union_arrays main NeuralnetModel get_default_params bool_str main load_dict_data readDATA load_training_data readWordlist write_results_all matrix2csv write_results_enf_gen get_folder_name writeCSV write_indiv_predictions coord2pixel_indiv get_folds getCaptionWords get_maximums_idx get_data get_BERT_Embeddings get_enforce_gen mirror_x build_emb_dict get_TRAIN_relevant pixl_idx2coord_all_examples aux_get_train_test_splits get_GEN relevant_instances2X_and_y get_CLEAN_train_test_idx pixl_idx2coord_indiv get_random_EMB getCaptionIndices compute_centers wordlist2emb_matrix find_threshold evaluate_perf_COORD merge_two_dicts classification_f1_acc evaluate_perf_PIXL correlations evaluate_perf bb_intersection_over_union_arrays get_default_params bool_str main load_dict_data readDATA load_training_data readWordlist write_results_all matrix2csv write_results_enf_gen get_folder_name writeCSV write_indiv_predictions coord2pixel_indiv get_folds getCaptionWords get_maximums_idx get_data get_enforce_gen mirror_x build_emb_dict get_TRAIN_relevant pixl_idx2coord_all_examples aux_get_train_test_splits get_GEN relevant_instances2X_and_y get_CLEAN_train_test_idx pixl_idx2coord_indiv get_random_EMB getCaptionIndices compute_centers wordlist2emb_matrix find_threshold evaluate_perf_COORD merge_two_dicts classification_f1_acc evaluate_perf_PIXL correlations evaluate_perf bb_intersection_over_union_arrays load_dict_data load_training_data NeuralnetModel get_default_params bool_str main load_dict_data readDATA load_training_data readWordlist write_results_all matrix2csv write_results_enf_gen get_folder_name writeCSV write_indiv_predictions list get_random_EMB concatenate get_TRAIN_relevant identity set wordlist2emb_matrix relevant_instances2X_and_y array build_emb_dict len coord2pixel_indiv str print reshape extend index append array range len str print append array range len append normal array range zeros list range reshape append pixl_idx2coord_indiv range get_maximums_idx where mean float astype int permutation arange floor range len append array range len print set list concatenate print readWordlist list set load_training_data append range len float int evaluate_perf_COORD merge_two_dicts reshape pixl_idx2coord_all_examples evaluate_perf_PIXL sqrt any update copy print find_threshold astype classification_f1_acc bb_intersection_over_union_arrays correlations r2_score float array remove savetxt isfile nanmax nanmin concatenate astype mean float precision_recall_fscore_support deepcopy arange print reshape classification_f1_acc append round range len get_folds get_data save_weights ArgumentParser get_enforce_gen method_compare mirror_x str aux_get_train_test_splits model_type load_training_data append parse_args get_CLEAN_train_test_idx NeuralnetModel write_indiv_predictions method_learn replace write_results_all model_predict n_folds evaluate_perf n_side_pixl enumerate readDATA relations print add_argument write_results_enf_gen get_default_params list matrix2csv outFolder set lower compute_centers range len append load_dict_data range len splitlines extend append array range len append matrix2csv extend append matrix2csv extend int list concatenate matrix2csv extend floor vstack sample array range len str model_type relations makedirs list punctuation set translate add lower maketrans range split int punctuation index translate lower maketrans append range split len Tokenizer uniform encode zeros tokenize range append enumerate get_BERT_Embeddings uniform get_pretrained load_vocabulary get_checkpoint_paths clear_model vocab multi_cased_base getCaptionWords getCaptionIndices split | # REC-COCO DATASET FOR INFERRING SPATIAL RELATIONS FROM TEXTUAL DESCRIPTIONS # Requirements Python 3 Keras 2.0.9 (tested with tensorflow backend) sklearn 0.19.1 (for evaluation) h5py (if we want to store model weights) Notice that we do not require actual images for our setting but only coordinates and bounding boxes. Download the glove embeddings, and saved them on the ./embeddings folder: https://drive.google.com/file/d/1CLNCtIh8CXi7abctH7UYwb6WqNdZ6pVE/view?usp=sharing The REF-COCO dataset is saved in the ./training_data folder. | 2,430 |
iyyun/Part-CNN | ['pedestrian detection'] | ['Part-Level Convolutional Neural Networks for Pedestrian Detection Using Saliency and Boundary Box Alignment'] | libs/setup.py libs/rpn/generate_anchors.py libs/utils/nms.py libs/network/iy_layer.py libs/imdb/sal_imdb.py libs/rpn/proposal_target_layer.py libs/nms/py_cpu_nms.py libs/imdb/make_saliency_db.py libs/imdb/det_imdb.py libs/detection/nms_wrapper.py libs/rpn/anchor_target_layer.py libs/roi/roi_pooling_op_test.py libs/detection/config.py libs/network/factory.py libs/network/__init__.py libs/roi/roi_pooling_op_grad.py libs/detection/bbox_transform.py libs/rpn/proposal_layer.py libs/roi/roi_pooling_op.py libs/network/train_iy_cls_net.py libs/roi/__init__.py libs/rpn/__init__.py libs/imdb/cls_imdb.py libs/network/train_iy_det_net.py find_in_path customize_compiler_for_nvcc custom_build_ext locate_cuda clip_boxes bbox_transform bbox_transform_inv nms DataSet get_db load_cls_information get_dbinfo DataSet tData get_db load_label_file load_label_file tData onMouse get_db load_saliency_information DataSet get_network layer Network train_iy_cls_net train_iy_det_net py_cpu_nms _roi_pool_shape _roi_pool_grad conv2d weight_variable _unmap _compute_targets anchor_target_layer generate_anchors _scale_enum _whctrs _ratio_enum _mkanchors _filter_boxes proposal_layer _get_bbox_regression_labels _compute_targets proposal_target_layer _sample_rois nms pathsep pjoin exists split find_in_path items pjoin pathsep dirname sep append _compile compiler_so transpose log dtype exp astype shape zeros minimum maximum join print glob index append zeros array len seed int isinstance DataSet shuffle load_cls_information DataSets join get_dbinfo int glob sort tData close index split append range open load_label_file len abs imwrite occlusion waitKey shape imshow imread astype copy skip_p mkdir float uint8 rectangle zeros join print sort glob len index append array range split load_saliency_information print append maximum minimum as_list TensorShape get_attr get_attr roi_pool_grad truncated_normal arange RPN_BBOX_INSIDE_WEIGHTS _unmap argmax RPN_FG_FRACTION generate_anchors ones transpose shape array meshgrid sum RPN_BATCHSIZE format ascontiguousarray choice fill empty RPN_POSITIVE_WEIGHT int print reshape RPN_CLOBBER_POSITIVES _compute_targets zeros bbox_overlaps len fill empty vstack _ratio_enum array hstack sqrt _whctrs round _mkanchors _whctrs _mkanchors nms generate_anchors RPN_POST_NMS_TOP_N arange meshgrid reshape transpose clip_boxes _filter_boxes bbox_transform_inv hstack RPN_NMS_THRESH RPN_PRE_NMS_TOP_N zeros RPN_MIN_SIZE FG_FRACTION BATCH_SIZE _sample_rois reshape astype float32 vstack zeros round zeros BBOX_INSIDE_WEIGHTS array shape BBOX_NORMALIZE_STDS bbox_transform BBOX_NORMALIZE_MEANS BBOX_NORMALIZE_TARGETS_PRECOMPUTED array int _get_bbox_regression_labels size min _compute_targets ascontiguousarray choice bbox_overlaps argmax max append append maximum minimum | # Part-Level Convolutional Neural Networks for Pedestrian Detection Using Saliency and Boundary Box Alignment Abstract -------- Pedestrians in videos have a wide range of appearance factors such as body poses, occlusions, and complex backgrounds, which make their detection difficult. Moreover, a proposal shift problem causes the loss of body parts such as head and legs in pedestrian detection, which further degrades the detection accuracy. In this paper, we propose part-level convolutional neural networks (CNNs) for pedestrian detection using saliency and boundary box (BB) alignment. The proposed network consists of two subnetworks: detection and alignment. In the detection subnetwork, we use saliency to remove false positives such as lamp posts and trees by combining fully convolutional network (FCN) and class activation map (CAM) to extract deep features. Subsequently, we adopt the BB alignment on detection proposals in the alignment subnetwork to overcome the proposal shift problem by applying the part-level CNN to recall the lost body parts. Experimental results on various datasets demonstrate that the proposed method remarkably improves accuracy in pedestrian detection and outperforms existing state-of-the-art techniques. Contribution Highlights ----------------------- - We use saliency in the detection subnetwork to remove background components such as lamp posts and trees from pedestrians. - We combine FCN and CAM into the alignment subnetwork to enhance the resolution of confidence maps and successfully recall the lost body parts. Images | 2,431 |
izikgo/AnomalyDetectionTransformations | ['anomaly detection'] | ['Deep Anomaly Detection Using Geometric Transformations'] | multiclass_experiment.py intuition_experiments.py models/dagmm.py experiments.py models/wide_residual_network.py transformations.py models/encoders_decoders.py utils.py models/adgan.py models/dsebm.py _raw_ocsvm_experiment _dagmm_experiment run_experiments _transformations_experiment create_auc_table _adgan_experiment _train_ocsvm_and_score _dsebm_experiment _cae_ocsvm_experiment optimize_normal_images affine optimize_anomaly_images train_cifar10_transformations transformation_cifar10_vs_tinyimagenet load_tinyimagenet train_cifar10 AbstractTransformer Transformer SimpleTransformer AffineTransformation load_cifar10 create_cats_vs_dogs_npz load_fashion_mnist get_class_name_from_index load_mnist resize_and_crop_image load_cats_vs_dogs save_roc_pr_curve_data get_channels_axis load_cifar100 normalize_minus1_1 train_wgan_with_grad_penalty scores_from_adgan_generator GradPenLayer GaussianMixtureComponent create_dagmm_model Prior create_energy_model create_reconstruction_model conv_encoder conv_decoder dense SGDTorch _add_basic_block batch_norm _get_channels_axis create_wide_residual_network conv2d _add_conv_group _conv_kernel_initializer _dense_kernel_initializer Transformer arange put save_weights transform_batch len create_wide_residual_network strftime save_roc_pr_curve_data range predict get format get_class_name_from_index mean tile compile dataset_load_fn join n_transforms fixed_point_dirichlet_mle repeat zeros calc_approx_alpha_sum fit dataset_load_fn list format join get_class_name_from_index ParameterGrid reshape fit strftime choice save_roc_pr_curve_data decision_function zip max len put conv_encoder decision_function Input max list strftime save_roc_pr_curve_data Model conv_decoder predict get format get_class_name_from_index choice zip compile dataset_load_fn join print ParameterGrid fit dec enc len get dataset_load_fn join format create_energy_model create_reconstruction_model get_class_name_from_index strftime put conv_encoder save_roc_pr_curve_data compile fit get dataset_load_fn join format get_class_name_from_index Sequential fit min strftime put flatten conv_encoder Model save_roc_pr_curve_data input conv_decoder compile create_dagmm_model get dataset_load_fn join format train_wgan_with_grad_penalty get_class_name_from_index strftime choice put conv_encoder save_roc_pr_curve_data scores_from_adgan_generator conv_decoder len start join range _raw_ocsvm_experiment load join defaultdict glob set add append split format subplots print squeeze grid close copy imshow savefig tick_params range clip gaussian_filter len format subplots print squeeze grid close copy imshow savefig tick_params range clip gaussian_filter len cast_to_floatx stack normalize_minus1_1 range len SGDTorch format create_wide_residual_network fit_generator save_weights load_cifar10 ImageDataGenerator LearningRateScheduler compile fit Transformer SGDTorch format create_wide_residual_network output fit_generator Model save_weights load_cifar10 input LearningRateScheduler compile Transformer format load_tinyimagenet n_transforms concatenate create_wide_residual_network output mean save_roc_pr_curve_data Model load_weights load_cifar10 input zeros range int imread cvtColor resize image_data_format cast_to_floatx pad load_data normalize_minus1_1 expand_dims cast_to_floatx pad load_data normalize_minus1_1 expand_dims cast_to_floatx load_data normalize_minus1_1 cast_to_floatx load_data normalize_minus1_1 concatenate roc_curve flatten precision_recall_curve savez_compressed auc join _load_from_dir savez_compressed load join cast_to_floatx normalize_minus1_1 generator on_epoch_begin on_epoch_end set_model data_gen Input on_train_begin train_on_batch list add shape Model uniform on_batch_end critic range predict update format subtract on_batch_begin prior_gen zip compile set_params print reshape zeros on_train_end array Progbar CallbackList len generator function set_value g_train_fn variable Adam placeholder prior_gen mean square expand_dims z_train_fn append get_weights range set_weights decoder concatenate estimation_encoder Model encoder Input Input encoder_mdl Input energy_mdl Input Input sqrt _compute_fans sqrt _compute_fans add _add_basic_block range _add_conv_group Input | # Deep Anomaly Detection Using Geometric Transformations To be presented in NIPS 2018 by Izhak Golan and Ran El-Yaniv. ## Introduction This is the official implementation of "Deep Anomaly Detection Using Geometric Transformations". It includes all experiments reported in the paper. ## Requirements * Python 3.5+ * Keras 2.2.0 * Tensorflow 1.8.0 * sklearn 0.19.1 | 2,432 |
izmailovpavel/understandingbdl | ['gaussian processes'] | ['Bayesian Deep Learning and a Probabilistic Perspective of Generalization'] | swag/posteriors/ffg_vi_model.py swag/posteriors/sghmc.py ubdl_data/corruptions.py swag/posteriors/ess.py swag/models/wide_resnet_dropout.py swag/posteriors/sgld.py swag/models/tiramisu.py swag/models/wide_resnet.py swag/models/lenet5.py experiments/rethinking_generalization/gp_cifar_prepare_data.py swag/models/__init__.py swag/posteriors/realnvp.py swag/posteriors/vi_model.py swag/posteriors/vinf_model.py swag/camvid.py swag/models/vgg.py swag/models/regression_net.py swag/utils.py swag/models/preresnet.py swag/posteriors/swag.py swag/models/preresnet_dropout.py swag/posteriors/elliptical_slice.py swag/posteriors/proj_model.py swag/data.py experiments/train/eval_multiswag.py swag/models/joint_transforms.py swag/posteriors/laplace.py swag/posteriors/__init__.py experiments/rethinking_generalization/gp_train_cifar_binary_corrupted.py swag/posteriors/diag_laplace.py swag/posteriors/inferences.py swag/models/mlp.py swag/__init__.py swag/posteriors/subspaces.py ubdl_data/make_cifar_c.py swag/posteriors/pyro.py swag/models/layers.py swag/models/vgg_dropout.py swag/losses.py swag/posteriors/_assess_dimension.py experiments/train/run_swag.py experiments/rethinking_generalization/gp_train_cifar_one_vs_all.py GPClassificationModel GPClassificationModel schedule is_image_file _make_dataset LabelTensorToPILImage CamVid has_file_allowed_extension camvid_loaders get_imagenette160 loaders loaders_inc imagenette_loaders svhn_loaders GaussianLikelihood seg_cross_entropy seg_ale_cross_entropy masked_loss kl_div adversarial_cross_entropy cross_entropy_output cross_entropy calibration_curve inv_softmax flatten get_logging_print adjust_learning_rate save_checkpoint nll predictions set_weights moving_average _check_bn LogSumExp unflatten_like ece predict eval schedule set_weights_old extract_parameters bn_update train_epoch _get_momenta accuracy check_bn _set_momenta reset_bn JointRandomResizedCrop JointCompose JointRandomHorizontalFlip LabelToLongTensor TransitionDown center_crop Bottleneck DenseLayer DenseBlock TransitionUp LeNet5 LeNet5Base MLPBoston MLPBase MLP PreResNet20 PreResNet83 PreResNet Bottleneck PreResNet20ImageNette PreResNet164 PreResNet110 conv3x3 PreResNet20NoSkipImageNette BasicBlockNoSkip PreResNet20NoAug PreResNet56 PreResNet20NoSkip BasicBlock PreResNet8 PreResNet110Drop PreResNet56Drop PreResNetDrop Bottleneck conv3x3 PreResNet164Drop PreResNet8Drop BasicBlock RegNetCurve ToyRegNet RegNet MDropout sample_masks SplitDim RegNetBase FCDenseNet57 FCDenseNet103 FCDenseNet FCDenseNet67 VGG16 VGG16BNNoDropNoAug classifier_half VGG16BN classifier_quarter VGG VGG19 VGG16NoDropNoAug VGG19BN VGG16Half classifier BaseNoAug VGG16Quarter VGG16NoDrop make_layers classifier_nodrop Base VGG16BNNoDrop VGG19Drop VGG16BNDrop VGGDrop VGG19BNDrop make_layers VGG16Drop Base WideResNet28x10 conv_init WideResNet conv3x3 WideBasic conv_init conv3x3 WideBasic WideResNetDrop WideResNet28x10Drop Laplace slice_sample elliptical_slice EllipticalSliceSampling VIFFGModel LRGaussian ProjSGD Inference VI hessian KFACLaplace jacobian SubspaceModel ProjectedModel RealNVP construct_flow SGHMCModel SGLD RandomSpace FreqDirSpace PCASpace Subspace CovarianceSpace SWAG ELBO_NF VINFModel BenchmarkVINFModel ELBO BenchmarkVIModel VIModel _infer_dimension_ _assess_dimension_ glass_blur plasma_fractal jpeg_compression frost zoom_blur speckle_noise contrast disk brightness spatter pixelate defocus_blur clipped_zoom gaussian_noise impulse_noise motion_blur fog snow elastic_transform shot_noise saturate MotionImage gaussian_blur lower is_image_file join sorted append walk print CamVid print SVHN expanduser join ImageFolder seed get_imagenette160 format print shuffle samples sum range len data join str format print tolist ds targets lower datasets getattr array isin sum max range len join int list RandomState permutation delattr print ds lower datasets getattr train_labels append max range model log_softmax model cross_entropy backward model min grad sign lossfn zero_ max detach float ones_like long cross_entropy masked_loss model exp rsample model Normal masked_loss abs range gmtime strftime append shape view numel max param_groups update join save argmax int list defaultdict items criterion backward print islice zero_grad tqdm train step cuda enumerate len dataset defaultdict train len eval list tqdm parameters zip _BatchNorm issubclass __class__ apply ones_like issubclass zeros_like running_mean _BatchNorm __class__ running_var _BatchNorm issubclass __class__ momentum _BatchNorm issubclass __class__ train len apply model softmax manual_seed append numpy cuda copy_ parameters to pop list modules append keys to setattr prod astype concatenate mean array zip append argmax max size list Compose list ToTensor Parameter list ones ToTensor log list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose list Compose sample isinstance list Compose list Compose JointCompose list Compose JointCompose list Compose JointCompose list Compose list Conv2d dict list Compose dict list Compose constant xavier_uniform bias weight __name__ list Compose list Compose normal lnpdf cos pi dot uniform sin log len list ones lnpdf rand shuffle log copy range len zeros_like reshape grad shape append range len size MultivariateNormal zeros to range copy log pi sum range len _assess_dimension_ empty sum range len meshgrid arange array filldiamonds empty fillsquares ceil int scizoom array array random_noise array array gaussian array uint8 gaussian randint array range transpose disk filter2D append array range uint8 BytesIO make_blob fromstring imdecode save IMREAD_UNCHANGED MotionImage astype float32 zeros_like len max array randint imread resize fromarray normal uint8 BytesIO motion_blur make_blob reshape fromstring astype maximum imdecode array save IMREAD_UNCHANGED MotionImage clipped_zoom DIST_L2 threshold where gaussian COLOR_GRAY2BGRA CV_8U COLOR_BGR2BGRA normal Canny concatenate astype distanceTransform THRESH_TRUNC uint8 equalizeHist float32 filter2D array cvtColor mean array hsv2rgb rgb2hsv array clip hsv2rgb rgb2hsv array clip BytesIO save open BOX resize warpAffine arange getAffineTransform min astype float32 shape meshgrid array | # Bayesian Deep Learning and a Probabilistic Perspective of Generalization This repository contains experiments for the paper [_Bayesian Deep Learning and a Probabilistic Perspective of Generalization_](https://arxiv.org/abs/2002.08791) by Andrew Gordon Wilson and Pavel Izmailov. ## Introduction In the paper, we present a probabilistic perspective for reasoning about model construction and generalization, and consider Bayesian deep learning in this context. - We show that deep ensembles provide a compelling mechanism for approximate Bayesian inference, and argue that one should think about Bayesian deep learning more from the perspective of integration, rather than simple Monte Carlo, or obtaining precise samples from a posterior. - We propose MultiSWA and MultiSWAG, which improve over deep ensembles by marginalizing the posterior within multiple basins of attraction. - We investigate the function-space distribution implied by a Gaussian distribution over weights from multiple different perspectives, considering for example the induced correlation structure across data instances. - We discuss temperature scaling in Bayesian deep learning. | 2,433 |
j-duan/VS-Net | ['mri reconstruction'] | ['VS-Net: Variable splitting network for accelerated parallel MRI reconstruction'] | common/utils.py data/transforms.py common/test_subsample.py data/__init__.py data/mri_data.py data/test_transforms.py common/__init__.py common/mriutils.py architecture.py inference.py common/evaluate.py common/args.py save_png.py common/subsample.py data_loader.py vs_net.py dataConsistencyTerm weightedAverageTerm network cnn_layer get_epoch_batch load_traindata_path cobmine_all_coils MRIDataset data2complex data_for_training load_file data_for_training ssim psnr lr_scheduler psnr create_image_window test nmse create_log create_plot_window ssim train Args evaluate psnr mse nmse Metrics ssim saveAsMat ifft2c ssim ksave mriForwardOp removePEOversampling psnr phaseshow fft2c imshow normalize imsave addFEOversampling postprocess removeFEOversampling kshow _normalize brighten mriAdjointOp contrastStretching getContrastStretchingLimits imsaveDiff rmse ssim_ MaskFunc test_mask_reuse test_mask_low_freqs tensor_to_complex_np save_reconstructions SliceData create_input test_fft2 test_complex_center_crop test_ifft2 test_normalize test_root_sum_of_squares test_ifftshift test_apply_mask test_fftshift test_normalize_instance test_center_crop test_complex_abs test_roll normalize_instance complex_abs fftshift center_crop fft2 roll apply_mask to_tensor fft2c ifft2c complex_multiply ifftshift complex_center_crop normalize root_sum_of_squares ifft2 complex_multiply mask_func max arange where cobmine_all_coils shape repeat ifftshift meshgrid Tensor float array transpose MaskFunc to_tensor complex64 join str format glob range len transpose complex64 to_tensor param_groups format print join format makedirs write open model image ssim abs max clip psnr nmse to range format mse eval item flush enumerate line print write numpy len model zero_grad image ssim abs max clip psnr step nmse to range format mse item flush enumerate line backward print write numpy len Metrics iterdir dtype list concatenate tuple copy shape zeros transpose savemat copy makedirs min axis imshow figure abs log uint8 astype log abs imsave makedirs print axis title figure abs set_cmap angle print axis colorbar imshow title figure removePEOversampling print Warning ndim flipud rot90 fliplr range minimum int sort size maximum round sqrt min sort size round int minimum maximum uint8 print makedirs astype abs _normalize minimum uint8 print astype abs imsave makedirs mean sqrt real sum conj compare_ssim min mean append abs max range mean append abs range compare_psnr compare_ssim mean append abs range mask_func MaskFunc mask_func int all MaskFunc round items mkdir numpy reshape float mask_func MaskFunc create_input apply_mask create_input fftshift fft2 tensor_to_complex_np ifftshift numpy create_input fftshift tensor_to_complex_np ifftshift numpy ifft2 abs tensor_to_complex_np numpy create_input sqrt numpy create_input sum numpy create_input numpy create_input numpy create_input normalize_instance numpy create_input reshape numpy roll reshape numpy fftshift reshape numpy ifftshift stack iscomplexobj shape mask_func array fft ifft fft fftshift ifftshift ifft fftshift ifftshift mean std isinstance size zip narrow tuple dim range isinstance tuple dim range isinstance | # VS-Net: Variable splitting network for accelerated parallel MRI reconstruction The code in this repository implements VS-Net (Fig.1), a model-driven neural network for accelerated parallel MRI reconstruction (see our [presentation slides](http://www.cs.bham.ac.uk/~duanj/slides/VS-Net-MICCAI.pdf) and [poster](http://www.cs.bham.ac.uk/~duanj/slides/VS-Net-Poster.pdf)). Specifically, we formulate the generalized parallel compressed sensing reconstruction as an energy minimization problem, for which a variable splitting optimization method is derived. Based on this formulation we propose a novel, end-to-end trainable deep neural network architecture by unrolling the resulting iterative process of such variable splitting scheme. We evaluated VS-Net on complex valued multi-coil knee images for 4-fold and 6-fold acceleration factors showed improved performance (Fig.2).  :--: *Fig.1: VS-Net overall architecture (left) and each block in VS-net (right). DB, DCB and WAB stand for Denoiser Block, Data Consistency Block and Weighted Average Block, respectively.*  :--: *Fig.2: Visual comparison using Cartesian undersampling with AF 4 (top) and 6 (bottom). From left to right: zero-filling, l1-SPIRiT, Variational Network, VS-Net and ground truth. Click [here](http://www.cs.bham.ac.uk/~duanj/moive/more_visual_comparison.pdf) for more visual comparison.* ## Overview The files in this repository are organized into 5 directories and 1 root directory: | 2,434 |
j-friedrich/OASIS | ['time series'] | ['Fast Online Deconvolution of Calcium Imaging Data'] | examples/fig1.py oasis/plotting.py examples/fig4.py examples/fig3.py examples/table1.py examples/fig2.py setup.py oasis/functions.py examples/fig5.py oasis/__init__.py examples/fig6.py tests/test_deconvolution.py deconvolveAR1 cb update_lam foo bar plot_trace update_g plotTrace deconvolveAR1 gen_sinusoidal_data GetSn constrained_foopsi foopsi constrained_onnlsAR2 gen_data estimate_parameters axcov onnls deconvolve estimate_time_constant _nnls simpleaxis init_fig test_AR2 test_AR1 test_constrainedAR1 AR2 test_constrainedAR2 AR1 pop callback arange empty max range arange simpleaxis set_xlabel scatter savefig axvspan plot set_xlim copy empty enumerate clear set_yticks pause subplots_adjust set_xticks set_ylabel set_ylim len pop empty arange len arange dot sqrt foo empty len arange dot foo fminbound max plot set_xticklabels text gca simpleaxis ylim legend append xlim xticks yticks arange show set_verticalalignment get_major_ticks plot set_xticklabels xlabel ylabel xlim add_axes ylim simpleaxis figure legend gca xticks range enumerate yticks seed randn astype zeros range seed randn astype zeros range dtype print astype estimate_parameters warn can_cast double norm Minimize Problem asarray value Variable size squeeze solve dia_matrix sum_squares sum enumerate norm Minimize Problem value asarray Variable size squeeze solve dia_matrix append enumerate ones min copy dot zeros argmax range len exp arange zeros_like ones min log dot sqrt zeros sum max range _nnls len arange cumsum max log exp onnls c4smin append range astype mean sqrt empty enumerate int norm minimize sort min dot constrained_oasisAR1 zeros ravel len GetSn estimate_time_constant normal GetSn list concatenate roots curve_fit mean dot toeplitz poly eye conjugate sum array range len welch logical_and ifft fft concatenate square mean power abs len rc tick_bottom tick_left set_visible assert_allclose AR1 AR1 assert_allclose AR2 AR2 | [](https://github.com/j-friedrich/OASIS/actions/workflows/ci.yml) # OASIS: Fast online deconvolution of calcium imaging data Tools for extracting the neural activity from fluorescence calcium imaging data   The code can be readily run on neural temporal fluorescence calcium imaging data. Please have a look at the [demo](https://github.com/j-friedrich/OASIS/blob/master/examples/Demo.ipynb). ## Requirements The scripts were tested on Linux and MacOS (some users successfully used Windows too) with a typical numerical/scientific Python 2.7 or 3.5-3.9 installation, e.g. using Anaconda or Canopy, that included the following - python >= 2.7.11 - matplotlib >= 1.5.1 - numpy >= 1.10.2 - scipy >= 0.16.1 | 2,435 |
j-wilson/GPflowSampling | ['gaussian processes'] | ['Efficiently Sampling Functions from Gaussian Process Posteriors', 'Pathwise Conditioning of Gaussian Processes'] | tests/sampling/updates/test_exact.py gpflow_sampling/bases/dispatch.py gpflow_sampling/bases/__init__.py gpflow_sampling/__init__.py gpflow_sampling/sampling/decoupled_samplers.py gpflow_sampling/utils/array_ops.py gpflow_sampling/covariances/__init__.py tests/sampling/updates/common.py gpflow_sampling/bases/core.py gpflow_sampling/bases/fourier_initializers.py gpflow_sampling/kernels.py tests/sampling/priors/test_fourier_dense.py gpflow_sampling/sampling/core.py gpflow_sampling/sampling/updates/__init__.py gpflow_sampling/covariances/Kfus.py gpflow_sampling/sampling/updates/linear_updates.py gpflow_sampling/sampling/priors/fourier_priors.py gpflow_sampling/utils/__init__.py gpflow_sampling/sampling/priors/__init__.py gpflow_sampling/covariances/Kuus.py tests/sampling/updates/test_linear.py gpflow_sampling/utils/gpflow_ops.py gpflow_sampling/sampling/__init__.py gpflow_sampling/covariances/Kufs.py gpflow_sampling/sampling/updates/exact_updates.py gpflow_sampling/utils/conv_ops.py tests/sampling/priors/test_fourier_conv2d.py setup.py gpflow_sampling/models.py gpflow_sampling/inducing_variables.py gpflow_sampling/sampling/updates/cg_updates.py gpflow_sampling/utils/linalg.py tests/kernels/test_conv2d.py gpflow_sampling/bases/fourier_bases.py tests/sampling/updates/test_cg.py SharedDepthwiseInducingImages SharedInducingImages InducingImages DepthwiseInducingImages DepthwiseConv2d Conv2dTranspose Conv2d PathwiseSVGP PathwiseGPR PathwiseGPModel AbstractBasis KernelBasis _fourier_stationary _fourier_conv2d_transposed _fourier_depthwise_conv2d _fourier_conv2d _kernel_fallback _fourier_multioutput AbstractFourierBasis DepthwiseConv2d MultioutputDense Conv2d Dense Conv2dTranspose _weight_initializer_squaredExp _weight_initializer_matern _bias_initializer_fallback _Kfu_depthwise_conv2d _Kfu_fallback _Kfu_fallback_shared _Kfu_conv2d _Kfu_fallback_multioutput _Kfu_depthwise_conv2d_fallback _Kfu_conv2d_fallback _Kuf_conv2d_fallback _Kuu_depthwise_conv2d _Kuu_conv2d AbstractSampler DenseSampler MultioutputDenseSampler CompositeSampler _decoupled_conv _decoupled_lcm _decoupled_multioutput _decoupled_fallback _random_fourier_depthwise_conv _random_fourier_multioutput _random_fourier _random_fourier_conv _cg_shared _cg_independent _cg_conv2d _cg_fallback _exact_shared _exact_fallback _exact_conv2d _exact_independent _linear_fallback _linear_multioutput expand_to swap_axes move_axis normalize_axis expand_n reformat_shape reformat_data _getter _convert get_default_preconditioner batch_tensordot test_conv2d_transpose test_conv2d test_depthwise_conv2d ConfigConv2d ConfigFourierConv2d test_conv2d test_depthwise_conv2d _test_fourier_conv2d_common _avg_spatial_inner_product test_dense_shared test_dense ConfigFourierDense _test_fourier_dense_common test_dense_separate test_update_sparse_shared test_update_sparse_separate _sample_joint_fallback avg_spatial_inner_product test_update_conv2d test_update_sparse _sample_joint_conv2d _sample_joint_inducing test_update_dense _test_cg_gpr test_cg_sparse_separate ConfigDense test_cg_sparse test_cg_conv2d ConfigConv2d test_cg_sparse_shared test_cg_dense _test_cg_svgp ConfigConv2d ConfigDense test_exact_conv2d _test_exact_gpr _test_exact_svgp test_exact_sparse test_exact_sparse_separate test_exact_sparse_shared test_exact_dense ConfigDense _test_linear_svgp test_linear_sparse_shared test_linear_sparse test_linear_sparse_separate default_float default_float convert_to_tensor normal isinstance Matern12 gamma Matern52 default_float Matern32 list Kuf_dispatch get_inducing_shape ndims range len list Kuf_dispatch ndims range get_spatial_out K as_patches get_patches reciprocal list K_r2 patch_shape reshape transpose weights square conv2d reduce_mean lengthscales ard fill tensordot K_r2 reduce_sum get_patches scale expand_dims as_patches squared_difference reciprocal dtype list K_r2 patch_shape reshape transpose weights square depthwise_conv2d reduce_mean lengthscales ard cast fill tensordot move_axis len Kfu_dispatch list ndims range as_patches K square_distance K_r2 reduce_mean scale move_axis as_patches update_rule prior update_rule prior squeeze update_rule prior fourier_basis normal list default_float fourier_basis normal list default_float fourier_basis normal list default_float normal list fourier_basis channels_in default_float kern tuple Kuu warn count_nonzero default_jitter InducingVariables shape get_default_preconditioner LinearOperatorFullMatrix kernel_basis matvec set_diag isinstance adjoint is_nan diag_part conjugate_gradient x kern tuple Kuu warn count_nonzero default_jitter InducingVariables shape get_default_preconditioner LinearOperatorFullMatrix kernel_basis matvec set_diag isinstance adjoint is_nan diag_part conjugate_gradient x kernel_basis convert_to_tensor kern set_diag isinstance kernel_basis adjoint tuple Kuu default_jitter InducingVariables shape diag_part cholesky cholesky_solve expand_dims convert_to_tensor kern set_diag isinstance kernel_basis tuple Kuu default_jitter InducingVariables shape diag_part cholesky cholesky_solve expand_dims swap_axes move_axis kernel_basis convert_to_tensor reciprocal set_diag isinstance adjoint tuple inducing_to_tensor matmul default_jitter InducingVariables shape diag_part cholesky basis eye cholesky_solve expand_dims swap_axes convert_to_tensor reciprocal set_diag isinstance adjoint inducing_to_tensor matmul default_jitter InducingVariables diag_part cholesky basis eye cholesky_solve expand_dims swap_axes SharedIndependentInducingVariables pop list insert shape range normalize_axis len list shape range normalize_axis len shape normalize_axis len shape len inducing_variables get_inducing_shape enumerate parse_axes list squeeze shape zip append enumerate len convert_to_tensor LinearOperatorScaledIdentity default_jitter LinearOperatorDiag LinearOperatorLowRankUpdate pivoted_cholesky reduce_prod image_shape Kfu rel_lengthscales_max channels_in seed cls set_seed shape uniform ConfigConv2d jitter range normal rel_lengthscales_min floatx _Kfu_conv2d_fallback int set_default_float reshape patch_shape Conv2d set_default_jitter allclose reduce_prod image_shape Kfu rel_lengthscales_max channels_in Conv2dTranspose seed cls set_seed shape uniform ConfigConv2d jitter range normal rel_lengthscales_min floatx _Kfu_conv2d_fallback int set_default_float reshape patch_shape set_default_jitter allclose reduce_prod image_shape Kfu rel_lengthscales_max seed cls set_seed shape uniform ConfigConv2d jitter range normal rel_lengthscales_min floatx _Kfu_depthwise_conv2d_fallback int DepthwiseConv2d set_default_float reshape patch_shape set_default_jitter allclose reshape list batch_tensordot num_bases kern random_fourier funcs shard_size ndims concat min num_samples Kuu basis fourier_basis swap_axes Kfu append ConfigFourierConv2d InducingImages _test_fourier_conv2d_common base_cls ConfigFourierConv2d base_cls DepthwiseInducingImages _test_fourier_conv2d_common num_bases kern random_fourier funcs isinstance setdefault shard_size transpose min num_samples Kuu concat dict basis Kfu fourier_basis append seed cls set_seed set_default_float ConfigFourierDense uniform floatx set_default_jitter InducingPoints _test_fourier_dense_common jitter seed cls set_seed set_default_float SharedIndependent ConfigFourierDense uniform floatx set_default_jitter InducingPoints _test_fourier_dense_common SharedIndependentInducingVariables jitter seed cls SeparateIndependent set_seed SeparateIndependentInducingVariables set_default_float ConfigFourierDense uniform floatx set_default_jitter InducingPoints _test_fourier_dense_common append jitter normal list kern set_diag concat default_jitter diag_part cholesky expand_dims normal list Kuf kern set_diag isinstance concat Kuu default_jitter diag_part tile cholesky expand_dims normal get_spatial_out list set_diag reshape concat transpose default_jitter kernel diag_part get_patches cholesky tile as_patches split reshape list batch_tensordot data get_default_preconditioner cg_update mean_function num_cond shard_size concat min num_samples sample_joint update_fns kernel append get_default_preconditioner normal cg_update inducing_variable num_cond shard_size transpose min num_samples Kuu sample_joint update_fns kernel concat append q_sqrt _test_cg_gpr reduce_mean squeeze matmul reduce_mean squeeze matmul _test_cg_svgp reduce_mean transpose matmul _test_cg_svgp reduce_mean transpose matmul _test_cg_svgp transpose avg_spatial_inner_product reduce_mean swap_axes _test_cg_svgp data mean_function set_diag shard_size concat variance min num_samples sample_joint update_fns kernel diag_part exact_update cholesky append normal inducing_variable shard_size transpose min num_samples Kuu sample_joint update_fns kernel concat exact_update cholesky append q_sqrt squeeze reduce_mean _test_exact_gpr matmul matmul reduce_mean squeeze _test_exact_svgp matmul reduce_mean transpose _test_exact_svgp matmul reduce_mean transpose _test_exact_svgp transpose avg_spatial_inner_product _test_exact_svgp reduce_mean swap_axes normal inducing_variable shard_size linear_update transpose min num_samples sample_joint concat update_fns kernel fourier_basis q_sqrt append _test_linear_svgp reduce_mean squeeze matmul _test_linear_svgp reduce_mean transpose matmul _test_linear_svgp reduce_mean transpose matmul | # GPflowSampling Companion code for [Efficiently Sampling Functions from Gaussian Process Posteriors](https://arxiv.org/abs/2002.09309) and [Pathwise Conditioning of Gaussian processes](https://arxiv.org/abs/2011.04026). ## Overview Software provided here revolves around Matheron's update rule <a href="https://www.codecogs.com/eqnedit.php?latex=\large&space;(f&space;\mid&space;\mathbf{y})(\cdot)&space;=&space;f(\cdot)&space;+&space;k(\cdot,&space;\mathbf{X})\mathbf{K}^{-1}\big(\mathbf{y}&space;-&space;f(\mathbf{X})\big)," target="_blank"><img src="https://latex.codecogs.com/svg.latex?\large&space;(f&space;\mid&space;\mathbf{y})(\cdot)&space;=&space;f(\cdot)&space;+&space;k(\cdot,&space;\mathbf{X})\mathbf{K}^{-1}\big(\mathbf{y}&space;-&space;f(\mathbf{X})\big)," title="matherons_update_rule" /></a> which allows us to represent a GP posterior as the sum of a prior random function and a data-driven update term. Thinking about conditioning at the level of random function (rather than marginal distributions) enables us to accurately sample GP posteriors in linear time. Please see `examples` for tutorials and (hopefully) illustrative use cases. ## Installation ``` git clone [email protected]:j-wilson/GPflowSampling.git | 2,436 |
j201/gibbs-pruning | ['network pruning'] | ['A Framework for Neural Network Pruning Using Gibbs Distributions'] | example.py gibbs_pruning.py lr_schedule resnet_block GibbsPrunedConv2D GibbsPruningAnnealer tf_sample_gibbs add list constant product gather sum max tensordot | # Gibbs Pruning Implementation of Gibbs pruning (https://arxiv.org/abs/2006.04981) for Keras/Tensorflow. Code should work with Tensorflow 1.14, 1.15, and 2.1, but our results were generated with Tensorflow 1.14, so note that other versions may lead to slightly different results. ## Usage Code and full documentation for Gibbs pruning on 2D convolutional layers is in `gibbs_pruning.py`. `example.py` gives an example of using Gibbs pruning on ResNet-20 with CIFAR-10. Run `python example.py --help` to see all options. | 2,437 |
j3xugit/RaptorX-Contact | ['protein folding'] | ['Accurate De Novo Prediction of Protein Contact Map by Ultra-Deep Learning Model'] | DL4DistancePrediction2/CalcCASPContactPredAccuracy.py DL4DistancePrediction2/Optimizers.py DL4DistancePrediction2/CalcMCCF1.py DL4DistancePrediction2/Metrics.py DL4DistancePrediction2/Adams.py DL4DistancePrediction2/SGD_Nestrov.py DL4DistancePrediction2/ResNet4Distance.py DL4DistancePrediction2/LogReg.py DL4DistancePrediction2/ReadProteinFeatures.py DL4DistancePrediction2/utils.py DL4DistancePrediction2/RunDistancePredictor2.py DL4DistancePrediction2/ReadOneProteinFeatures.py DL4DistancePrediction2/Model4DistancePrediction.py DL4DistancePrediction2/DistanceUtils.py DL4DistancePrediction2/resnet.py DL4DistancePrediction2/DataProcessor.py Common/LoadHHM.py DL4DistancePrediction2/Conv1d.py DL4DistancePrediction2/CalcContactPredAccuracy.py DL4DistancePrediction2/BatchCalcMCCF1.py DL4DistancePrediction2/EmbeddingLayer.py DL4DistancePrediction2/BatchEvaluateContactAccuracy.py DL4DistancePrediction2/config.py DL4DistancePrediction2/EvaluateDistanceAccuracy.py DL4DistancePrediction2/mlLogReg.py DL4DistancePrediction2/BatchEvaluateDistanceAccuracy.py DL4DistancePrediction2/DilatedResNet4Distance.py DL4DistancePrediction2/NN4LogReg.py DL4DistancePrediction2/NN4Normal.py DL4DistancePrediction2/ContactUtils.py load_hmm ReadHHM batch_norm relu log_softmax conv main build_resnet resnet_bottleneck sgd_nesterov print exit float32 pow log2 zeros sum array range split join replace print ReadHHM exit float32 int32 startswith split exp sum max log normal asarray print sqrt conv2d shared asarray ones mean batch_normalization shared std zeros print conv batch_norm relu batch_norm relu log_softmax conv max_pool_2d resnet_bottleneck asarray function floatX shared print f grad get_value astype mean tensor4 matrix sum build_resnet scalar | # RaptorX-Contact: a software package for protein contact and distance prediction by deep residual neural network. A new version of the software is now available at https://github.com/j3xugit/RaptorX-3DModeling . This package has source code of the deep convolutional residual neural network method initiated by me for protein contact/distance prediction and distance-based folding. The code and documentation will be improved gradually. Anaconda (for Python 2.7), Theano and possibly BioPython shall be installed in order to use this package. Mr. Hung Nguyen has improved my code so that it works with Python 3. See his revision at https://github.com/nd-hung/DL4DistancePrediction2 . The package contains core code used to produce results in the following papers. 1) Analysis of distance-based protein structure prediction by deep learning in CASP13. PROTEINS, 2019. 2) Distance-based protein folding powered by deep learning. PNAS, August 2019. A 2-page abstract also appeared at RECOMB2019 in April 2019. This paper describes in details that distance predicted by deep ResNet may result in much better folding than contacts predicted by the same deep ResNet. 3) Protein threading using residue co-variation and deep learning, ISMB and Bioinformatics, July 2018. The first paper shows how to extend deep learning to distance prediction and then apply it to greatly improve protein alignment/threading. 4) ComplexContact: a web server for inter-protein contact prediction using deep learning. NAR, May 2018. The first paper shows that deep ResNet trained on single-chain proteins works well in predicting contacts between two interacting proteins. 5) Analysis of deep learning methods for blind protein contact prediction in CASP12. PROTEINS, March 2018 6) Folding Membrane Proteins by Deep Transfer Learning. Cell Systems, September 2017. The first paper shows in details that deep ResNet works well on membrane proteins even if trained without any membrane proteins. | 2,438 |
jMetal/jMetalPy | ['data visualization'] | ['jMetalPy: a Python Framework for Multi-Objective Optimization with Metaheuristics'] | examples/multiobjective/ibea/ibea_zdt1.py jmetal/problem/multiobjective/constrained.py jmetal/util/constraint_handling.py examples/multiobjective/spea2/spea2_zdt1.py jmetal/problem/multiobjective/test/test_zdt.py examples/multiobjective/omopso/omopso_zdt1.py examples/multiobjective/smpso/smpsorp_zdt4.py jmetal/lab/visualization/interactive.py jmetal/problem/multiobjective/uf.py jmetal/util/distance.py examples/multiobjective/nsgaii/dynamic_nsgaii_solving_fda2.py examples/multiobjective/moead/moead_iepsilon_lircmop1.py jmetal/core/test/test_quality_indicator.py jmetal/core/test/test_solution.py jmetal/operator/test/test_selection.py examples/multiobjective/nsgaii/distributed_nsgaii_with_dask_evaluator.py examples/multiobjective/hype/hype_zdt1.py examples/multiobjective/mocell/mocell_zdt1.py jmetal/problem/singleobjective/unconstrained.py jmetal/core/operator.py examples/multiobjective/gde3/dynamic_gde3.py jmetal/algorithm/multiobjective/random_search.py examples/multiobjective/random_search/random_search_zdt1.py jmetal/util/solution.py jmetal/lab/statistical_test/functions.py jmetal/algorithm/singleobjective/local_search.py jmetal/operator/crossover.py examples/singleobjective/genetic_algorithm/steady_state_genetic_algorithm.py examples/multiobjective/nsgaii/distributed_nsgaii_with_spark_evaluator.py jmetal/core/test/test_operator.py jmetal/util/test/test_point.py jmetal/util/test/test_aggregativefunction.py examples/multiobjective/nsgaii/nsgaii_steady_state.py jmetal/lab/statistical_test/apv_procedures.py examples/experiment/comparison.py examples/multiobjective/nsgaii/nsgaii_solving_constrained_srinivas_problem.py jmetal/util/test/test_evaluator.py jmetal/core/algorithm.py setup.py jmetal/algorithm/singleobjective/simulated_annealing.py jmetal/problem/multiobjective/lircmop.py examples/singleobjective/genetic_algorithm/generational_genetic_algorithm_binary.py jmetal/problem/multiobjective/fda.py examples/singleobjective/simulated_annealing/simulated_annealing_float.py jmetal/operator/mutation.py jmetal/util/test/test_distance.py examples/singleobjective/evolution_strategy/evolution_strategy_float.py examples/multiobjective/nsgaii/gnsgaii_solving_zdt2_with_reference_point.py examples/multiobjective/nsgaii/nsgaii_ssp.py examples/singleobjective/local_search/local_search_binary.py jmetal/algorithm/singleobjective/__init__.py jmetal/util/test/test_neighborhood.py examples/multiobjective/nsgaii/nsgaii_defining_schaffer_problem_on_the_fly.py examples/multiobjective/moead/moead_lz09.py jmetal/algorithm/singleobjective/evolution_strategy.py jmetal/util/test/test_constraint_handling.py examples/multiobjective/smpso/smpso_srinivas_on_the_fly.py jmetal/problem/singleobjective/test/test_knapsack.py examples/multiobjective/nsgaii/nsgaii_solving_3D_problem.py examples/multiobjective/gde3/gde3_zdt1.py examples/multiobjective/spea2/gspea2_zdt1.py examples/singleobjective/genetic_algorithm/generational_genetic_algorithm_tsp.py jmetal/util/observable.py examples/multiobjective/nsgaii/nsgaii_standard_settings_with_real_time_plotting.py examples/multiobjective/gde3/ggde3_zdt2.py examples/multiobjective/nsgaii/nsgaii_solving_binary_problem.py jmetal/problem/multiobjective/lz09.py examples/experiment/statistical_analysis.py examples/multiobjective/nsgaiii/nsgaiii_dtlz2.py jmetal/util/test/test_comparator.py jmetal/util/test/test_checking.py jmetal/lab/statistical_test/bayesian.py docs/source/conf.py jmetal/problem/singleobjective/test/test_unconstrained.py examples/multiobjective/smpso/smpso_zdt4.py jmetal/util/test/test_archive.py jmetal/util/ranking.py jmetal/problem/multiobjective/test/test_constrained.py examples/multiobjective/omopso/omopso_spark_evaluator.py jmetal/algorithm/multiobjective/omopso.py jmetal/lab/visualization/plotting.py jmetal/util/archive.py jmetal/algorithm/multiobjective/smpso.py examples/multiobjective/nsgaii/parallel_nsgaii_with_multiprocess_evaluator.py jmetal/lab/visualization/chord_plot.py jmetal/algorithm/multiobjective/spea2.py jmetal/util/generator.py jmetal/core/quality_indicator.py jmetal/lab/statistical_test/critical_distance.py jmetal/algorithm/multiobjective/moead.py jmetal/operator/__init__.py examples/multiobjective/spea2/spea2_dtlz1.py jmetal/operator/test/test_mutation.py examples/singleobjective/genetic_algorithm/generational_genetic_algorithm_float.py jmetal/util/test/test_ranking.py examples/multiobjective/nsgaii/distributed_nsgaii_with_dask.py jmetal/util/test/test_density_estimator.py examples/singleobjective/nsgaii/nsgaii_single_objective_float.py jmetal/problem/multiobjective/unconstrained.py examples/singleobjective/nsgaii/nsgaii_single_objective_binary.py jmetal/lab/experiment.py examples/multiobjective/gde3/gde3_spark_evaluator.py examples/singleobjective/evolution_strategy/evolution_strategy_binary.py jmetal/util/point.py jmetal/algorithm/multiobjective/gde3.py jmetal/util/test/test_replacement.py jmetal/util/evaluator.py jmetal/algorithm/multiobjective/hype.py jmetal/problem/multiobjective/test/test_unconstrained.py jmetal/algorithm/multiobjective/__init__.py jmetal/util/comparator.py examples/multiobjective/smpso/smpso_spark_evaluator.py jmetal/util/observer.py jmetal/core/problem.py examples/singleobjective/local_search/local_search_float.py jmetal/algorithm/multiobjective/mocell.py jmetal/util/neighborhood.py jmetal/__init__.py jmetal/algorithm/test/ittest_algorithm.py jmetal/core/observer.py examples/singleobjective/gde3/gde3_single_objective.py examples/multiobjective/smpso/smpso_srinivas.py jmetal/core/test/test_observable.py jmetal/problem/__init__.py jmetal/util/termination_criterion.py jmetal/lab/visualization/__init__.py examples/multiobjective/nsgaii/nsgaii_steady_state_with_real_time_plotting.py jmetal/algorithm/multiobjective/nsgaii.py jmetal/util/aggregative_function.py examples/singleobjective/simulated_annealing/simulated_annealing_binary.py jmetal/operator/test/test_crossover.py examples/multiobjective/smpso/smpso_schaffer_on_the_fly.py jmetal/util/replacement.py jmetal/algorithm/multiobjective/ibea.py examples/multiobjective/moead/moeaddra_lz09.py jmetal/problem/singleobjective/tsp.py examples/multiobjective/smpso/dynamic_smpso.py jmetal/util/ckecking.py examples/multiobjective/nsgaii/nsgaii_standard_settings.py examples/singleobjective/genetic_algorithm/steady_state_genetic_algorithm_with_knapsack_problem.py examples/multiobjective/preferences/ggde3_zdt2.py jmetal/core/test/test_problem.py jmetal/core/solution.py jmetal/problem/multiobjective/dtlz.py jmetal/util/density_estimator.py jmetal/problem/singleobjective/knapsack.py jmetal/problem/multiobjective/zdt.py jmetal/algorithm/singleobjective/genetic_algorithm.py jmetal/lab/visualization/streaming.py examples/multiobjective/moead/moead_dtlz2.py jmetal/config.py jmetal/operator/selection.py jmetal/algorithm/multiobjective/nsgaiii.py examples/multiobjective/nsgaii/nsgaii_defining_srinivas_problem_on_the_fly.py examples/multiobjective/nsgaii/nsgaii_solving_mixed_encoding_problem.py jmetal/lab/visualization/posterior.py configure_experiment f1 f2 f1 f2 c2 c1 f1 f2 f1 f2 c2 c1 _Store DynamicGDE3 GDE3 HYPE IBEA MOCell MOEAD_DRA MOEAD Permutation MOEADIEpsilon DistributedNSGAII DynamicNSGAII NSGAII reproduction compute_niche_count get_extreme_points get_nadir_point associate_to_niches niching NSGAIII UniformReferenceDirectionFactory ReferenceDirectionFactory OMOPSO RandomSearch _change_reference_point DynamicSMPSO SMPSORP SMPSO SPEA2 EvolutionStrategy GeneticAlgorithm LocalSearch SimulatedAnnealing RunningAlgorithmsTestCases IntegrationTestCases DynamicAlgorithm EvolutionaryAlgorithm ParticleSwarmOptimization Algorithm Observer Observable check_valid_probability_value Mutation Operator Selection Crossover Problem BinaryProblem DynamicProblem PermutationProblem OnTheFlyFloatProblem IntegerProblem FloatProblem QualityIndicator MultiList FitnessValue GenerationalDistance EpsilonIndicator InvertedGenerationalDistance HyperVolume Solution IntegerSolution FloatSolution CompositeSolution BinarySolution PermutationSolution ObservableTestCases DummyCrossover OperatorTestCase DummyMutation DummyIntegerProblem FloatProblemTestCases DummyFloatProblem IntegerProblemTestCases EpsilonIndicatorTestCases InvertedGenerationalDistanceTestCases HyperVolumeTestCases GenerationalDistanceTestCases BinarySolutionTestCase IntegerSolutionTestCase CompositeSolutionTestCase FloatSolutionTestCase SolutionTestCase __averages_to_latex compute_wilcoxon generate_summary_from_experiment Experiment generate_latex_tables Job __wilcoxon_to_latex compute_mean_indicator check_minimization generate_boxplot hochberg holland holm nemenyi li finner bonferroni_dunn shaffer bayesian_signed_rank_test bayesian_sign_test NemenyiCD CDplot friedman_ph_test friedman_aligned_ph_test quade_ph_test friedman_test ranks friedman_aligned_rank_test quade_test sign_test hover_over_bin draw_chord polar_to_cartesian draw_sector chord_diagram InteractivePlot Plot plot_posterior pause StreamingPlot CXCrossover IntegerSBXCrossover SPXCrossover NullCrossover SBXCrossover PMXCrossover CompositeCrossover DifferentialEvolutionCrossover CompositeMutation SimpleRandomMutation PolynomialMutation ScrambleMutation UniformMutation IntegerPolynomialMutation NonUniformMutation BitFlipMutation NullMutation PermutationSwapMutation NaryRandomSolutionSelection BinaryTournament2Selection RandomSolutionSelection BestSolutionSelection BinaryTournamentSelection RouletteWheelSelection RankingAndFitnessSelection RankingAndCrowdingDistanceSelection DifferentialEvolutionSelection CXTestCases NullCrossoverTestCases SinglePointTestCases PMXTestCases CompositeCrossoverTestCases SBXCrossoverTestCases CompositeMutationTestCases RandomMutationTestCases IntegerPolynomialMutationTestCases UniformMutationTestCases BitFlipTestCases PolynomialMutationTestMethods BestSolutionSelectionTestCases BinaryTournament2TestCases DominanceRankingTestCases RandomSolutionSelectionTestCases NaryRandomSolutionSelectionTestCases BinaryTournamentTestCases DifferentialEvolutionSelectionTestCases Binh2 Srinivas Tanaka Osyczka2 DTLZ4 DTLZ1 DTLZ2 DTLZ7 DTLZ6 DTLZ5 DTLZ3 FDA4 FDA FDA3 FDA2 FDA1 FDA5 LIRCMOP1 LIRCMOP9 LIRCMOP10 LIRCMOP13 LIRCMOP12 LIRCMOP2 LIRCMOP5 LIRCMOP4 LIRCMOP3 LIRCMOP8 LIRCMOP7 LIRCMOP11 LIRCMOP6 LIRCMOP14 LZ09_F3 LZ09_F1 LZ09_F4 LZ09_F2 LZ09_F5 LZ09 LZ09_F6 LZ09_F9 LZ09_F7 LZ09_F8 UF1 Kursawe Schaffer OneZeroMax Fonseca MixedIntegerFloatProblem Viennet2 SubsetSum ZDT4 ZDT6 ZDT1Modified ZDT2 ZDT1 ZDT3 TanakaTestCases SrinivasTestCases Viennet2TestCases KursaweTestCases FonsecaTestCases SchafferTestCases ZDT4TestCases ZDT6TestCases ZDT3TestCases ZDT2TestCases ZDT1TestCases Knapsack TSP OneMax Rastrigin Sphere SubsetSum KnapsackTestCases OneMaxTestCases SphereTestCases Tschebycheff AggregativeFunction WeightedSum ArchiveWithReferencePoint CrowdingDistanceArchiveWithReferencePoint Archive NonDominatedSolutionsArchive BoundedArchive CrowdingDistanceArchive InvalidConditionException Check InvalidProbabilityValueException ValueOutOfRangeException EmptyCollectionException NoneParameterException SolutionAttributeComparator MultiComparator DominanceComparator StrengthAndKNNDistanceComparator OverallConstraintViolationComparator GDominanceComparator EqualSolutionsComparator RankingAndCrowdingDistanceComparator EpsilonDominanceComparator Comparator number_of_violated_constraints feasibility_ratio overall_constraint_violation_degree is_feasible CrowdingDistance KNearestNeighborDensityEstimator DensityEstimator Distance CosineDistance EuclideanDistance MapEvaluator MultiprocessEvaluator Evaluator DaskEvaluator evaluate_solution SequentialEvaluator SparkEvaluator Generator RandomGenerator InjectorGenerator C9 WeightVectorNeighborhood Neighborhood TwoDimensionalMesh WeightNeighborhood L5 TimeCounter DefaultObservable PlotFrontToFileObserver WriteFrontToFileObserver VisualizerObserver ProgressBarObserver BasicObserver PrintObjectivesObserver Point IdealPoint FastNonDominatedRanking Ranking StrengthRanking RankingAndDensityEstimatorReplacement RemovalPolicyType print_variables_to_screen print_function_values_to_file print_variables_to_file get_non_dominated_solutions read_solutions print_function_values_to_screen StoppingByQualityIndicator StoppingByKeyboard TerminationCriterion StoppingByTime StoppingByEvaluations key_has_been_pressed WeightedSumTestCases CrowdingDistanceArchiveTestCases BoundedArchiveTestCases ArchiveTestCases NonDominatedSolutionListArchiveTestCases CheckingTestCases RankingAndCrowdingComparatorTestCases SolutionAttributeComparatorTestCases MultiComparatorTestCases DominanceComparatorTestCases OverallConstraintViolationComparatorTestCases ConstraintHandlingTestCases CrowdingDistanceTestCases KNearestNeighborDensityEstimatorTest EuclideanDistanceTestCases ParallelEvaluatorTestCases SequentialEvaluatorTestCases MockedProblem TwoDimensionalMeshTestCases L5TestCases WeightVectorNeighborhoodTestCases IdealPointTestCases FastNonDominatedRankingTestCases StrengthRankingTestCases RankingAndDensityEstimatorReplacementTestCases items list Job append range append zip execute argmin max eye concatenate ones solve int min shuffle unique append full len argmin compute_perpendicular_distance zeros unique reference_points print append update_reference_point number_of_objectives range len pop join compute hasattr warning read_solutions walk is_file join remove format suptitle boxplot set_xticklabels add_subplot close is_dir warning mkdir unique figure append tick_params savefig listdir read_csv groupby concat is_dir warning rename list droplevel format mean mkdir listdir keys join remove set_index get_group to_csv quantile median std read_csv drop join remove format mannwhitneyu DataFrame len to_csv is_dir warning mkdir unique append median listdir read_csv check_minimization enumerate columns mean unique zeros reindex DataFrame read_csv join sorted format write zip range StringIO join format write range StringIO int columns min argsort append zeros array range values int max columns arange min argsort append zeros array range values int max columns arange min argsort append zeros float array range values int uint8 columns max min astype argsort append zeros array range values int columns min argsort append zeros array range values triu_indices int columns arange max min argsort append zeros array range values triu_indices int columns max insert sort min argsort append zeros array range values triu_indices int columns min argsort append zeros array range values sum dirichlet argmax array values sum concatenate weights zeros argmax range values sqrt qsturng values show transpose ranks shape savefig hlines range set_xlim astype mean add_axes T uint8 vlines _join_alg text set_axis_off reshape index figure NemenyiCD array set_ylim ones sort size shape unique range cdf sum values min ranks mean shape cdf sum values sum reshape ranks mean shape cdf float ravel values min ranks shape Inf cdf zeros float sum max range values factorial finner DataFrame abs values columns ranks shape bonferroni_dunn shaffer nemenyi range holland mean sqrt li cdf hochberg int holm zeros array finner abs DataFrame values columns ranks shape bonferroni_dunn shaffer nemenyi range holland mean sqrt li cdf hochberg int reshape holm zeros ravel array finner abs max DataFrame values columns ranks shape bonferroni_dunn sum shaffer nemenyi range holland sqrt li cdf hochberg int min holm zeros array PathPatch tan Path add_patch PathPatch tan Path add_patch draw_idle contains set_visible setp range len tuple axis polar_to_cartesian pi set_visible max show str list draw_chord shape draw_sector append range plot mpl_connect set_xlim axes text tqdm dict figure histogram array set_ylim len show plot text set_ylim set_xlim set_axis_off hexbin add_axes shape savefig figure transform zeros range values canvas stale draw start_event_loop get_active that add format warning is_file makedirs dirname info print makedirs dirname info print str objectives index input eval |  [](https://github.com/jMetal/jMetalPy/actions/workflows/ci.yml) []() [](https://doi.org/10.1016/j.swevo.2019.100598) []() [](https://github.com/psf/black) A paper introducing jMetalPy is available at: https://doi.org/10.1016/j.swevo.2019.100598 ### Table of Contents - [Installation](#installation) - [Usage](#hello-world-) | 2,439 |
jacke121/A-Light-and-Fast-Face-Detector-for-Edge-Devices | ['face detection'] | ['LFFD: A Light and Fast Face Detector for Edge Devices'] | ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/cross_entropy_with_focal_loss_for_one_class_detection.py face_detection/data_provider_farm/pic_provider.py ChasingTrainFramework_GeneralOneClassDetection/image_augmentation/augmentor.py face_detection/config_farm/train_10_320_20L_5scales_v2.py face_detection/demo/demo_cam.py face_detection/config_farm/configuration_10_560_25L_8scales_v1.py face_detection/symbol_farm/symbol_10_560_25L_8scales_v1.py face_detection/data_provider_farm/text_list_adapter.py ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/cross_entropy_with_hnm_for_one_class_detection.py face_detection/inference_speed_evaluation/inference_speed_eval.py face_detection/accuracy_evaluation/predict.py ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/base_provider.py ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/base_data_adapter.py ChasingTrainFramework_GeneralOneClassDetection/logging_GOCD.py face_detection/deploy_tensorrt/predict_tensorrt.py face_detection/symbol_farm/symbol_10_320_20L_5scales_v2.py ChasingTrainFramework_GeneralOneClassDetection/data_iterator_base/data_batch.py face_detection/data_iterator_farm/multithread_dataiter_for_cross_entropy_v1.py ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/text_list_adapter.py face_detection/data_iterator_farm/multithread_dataiter_for_cross_entropy_v2.py ChasingTrainFramework_GeneralOneClassDetection/data_provider_base/pickle_provider.py ChasingTrainFramework_GeneralOneClassDetection/inference_speed_eval/inference_speed_eval_with_tensorrt_cudnn.py ChasingTrainFramework_GeneralOneClassDetection/train_GOCD.py face_detection/config_farm/__init__.py face_detection/demo/demo.py ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/mean_squared_error_with_hnm_for_one_class_detection.py face_detection/symbol_farm/__init__.py face_detection/metric_farm/metric_default.py face_detection/accuracy_evaluation/evaluation_on_fddb.py ChasingTrainFramework_GeneralOneClassDetection/solver_GOCD.py ChasingTrainFramework_GeneralOneClassDetection/loss_layer_farm/mean_squared_error_with_ohem_for_one_class_detection.py face_detection/data_provider_farm/pickle_provider.py ChasingTrainFramework_GeneralOneClassDetection/inference_speed_eval/inference_speed_eval_with_mxnet_cudnn.py face_detection/config_farm/configuration_10_320_20L_5scales_v2.py face_detection/deploy_tensorrt/to_onnx.py face_detection/accuracy_evaluation/evaluation_on_widerface.py temp_test init_logging Solver start_train DataBatch DataAdapterBaseclass ProviderBaseclass read_file write_file PickleProvider TextListAdapter Augmentor InferenceSpeedEval InferenceSpeedEval HostDeviceMem focal_loss_for_twoclass focal_loss_for_twoclass_Prop cross_entropy_with_hnm_for_one_class_detection_Prop cross_entropy_with_hnm_for_one_class_detection mean_squared_error_with_hnm_for_one_class_detection mean_squared_error_with_hnm_for_one_class_detection_Prop mean_squared_error_with_ohem_for_one_class_detection_Prop mean_squared_error_with_ohem_for_one_class_detection DataBatch run_prediction_folder Predict NMS run run run Multithread_DataIter_for_CrossEntropy Multithread_DataIter_for_CrossEntropy read_file write_file PickleProvider read_file write_file PickleProvider TextListAdapter main parse_args main parse_args run_prediction_folder Inference_TensorRT HostDeviceMem NMS generate_onnx_file Metric run_get_net_symbol_for_train loss_branch get_net_symbol run_get_net_symbol_for_train loss_branch get_net_symbol setFormatter addHandler print makedirs exit StreamHandler Formatter dirname setLevel FileHandler init_logging str list items __version__ info Solver fit write PickleProvider TextListAdapter PickleProvider ndarray isinstance print read_by_index positive_index shuffle waitKey imshow rectangle negative_index range enumerate minimum concatenate astype float32 maximum delete argsort append len join Predict waitKey imshow rectangle resize append imread max predict PickleProvider start_train get_net_symbol Xavier DataIter Metric init_logging info append add_argument ArgumentParser data VideoCapture imwrite FONT_HERSHEY_SIMPLEX VideoWriter VideoWriter_fourcc release destroyAllWindows waitKey shape imshow parse_args imread predict use_gpu replace astype join read Predict time uint8 print putText write rectangle cpu gpu do_inference Inference_TensorRT load update basicConfig list items load_model graph export_model float32 dict check_graph split Convolution Custom slice_axis softmax LinearRegressionOutput Activation Variable Convolution Group loss_branch Activation list_outputs list_arguments print get_net_symbol list_auxiliary_states infer_shape print_summary | # A Light and Fast Face Detector for Edge Devices ## Recent Update * `2019.07.25` This repos is first online. Face detection code and trained models are released. * `2019.08.15` This repos is formally released. Any advice and error reports are sincerely welcome. * `2019.08.22` face_detection: latency evaluation on TX2 is added. * `2019.08.25` face_detection: RetinaFace-MobileNet-0.25 is added for comparison (both accuracy and latency). ## Introduction This repo releases the source code of paper "[LFFD: A Light and Fast Face Detector for Edge Devices](https://arxiv.org/abs/1904.10633)". Our paper presents a light and fast face detector (**LFFD**) for edge devices. LFFD considerably balances both accuracy and latency, resulting in small model size, fast inference speed while achieving excellent accuracy. **Understanding the essence of receptive field makes detection networks interpretable.** | 2,440 |
jackie840129/STE-NVAN | ['person re identification', 'video based person re identification'] | ['Spatially and Temporally Efficient Non-local Attention Network for Video-based Person Re-Identification'] | creat_DukeV_database.py net/models.py util/cmc.py parser.py train_baseline.py train_NL.py create_MARS_database.py evaluate.py net/resnet.py util/loss.py util/utils.py is_image_file is_image_file validation parse_args validation validation CNN Resnet50_NL Resnet50_s1 weights_init_classifier weights_init_kaiming ResNet_Video_nonlocal_stripe_hr Stripe_NonLocalBlock ResNet ResNet_Video_nonlocal ResNet_Video_nonlocal_hr Bottleneck ResNet_Video_nonlocal_stripe NonLocalBlock np_norm_eudist np_cdist Compute_AP cdist Cmc Video_Cmc sqdist TripletLoss ClusterLoss Video_train_collate_fn Video_test_collate_fn process_labels Video_test_Dataset Get_Video_test_DataLoader Video_train_Dataset Get_Video_train_DataLoader query_idx close tqdm eval set_description Video_Cmc train numpy add_argument ArgumentParser affine bias kaiming_normal_ weight __name__ constant_ bias normal_ weight __name__ constant_ Cmc arange len update np_cdist Compute_AP ProgressBar argsort mean finish zeros range zeros any range len normalize transpose mm FloatTensor norm norm sum dot sum eye range unique len list isinstance MARS_collate_fn zip Mapping cat DataLoader Video_train_Dataset list isinstance MARS_collate_fn zip Mapping cat Video_test_Dataset DataLoader | # Spatially and Temporally Efficient Non-local Attention Network for Video-based Person Re-Identification - **NVAN** <p align="center"><img src='fig/NVAN.jpg' ></p> - **STE-NVAN** <p align="center"><img src='fig/STE-NVAN.jpg' width="800pix"></p> [[Paper]](http://media.ee.ntu.edu.tw/research/STE_NVAN/BMVC19_STE_NVAN_cam.pdf) [[arXiv]](https://arxiv.org/abs/1908.01683) [Chih-Ting Liu](https://jackie840129.github.io/), Chih-Wei Wu, [Yu-Chiang Frank Wang](http://vllab.ee.ntu.edu.tw/members.html) and [Shao-Yi Chien](http://www.ee.ntu.edu.tw/profile?id=101),<br/>British Machine Vision Conference (**BMVC**), 2019 This is the pytorch implementatin of Spatially and Temporally Efficient Non-local Video Attention Network **(STE-NVAN)** for video-based person Re-ID. <br/>It achieves **90.0%** for the baseline version and **88.9%** for the ST-efficient model in rank-1 accuracy on MARS dataset. ## News ## | 2,441 |
jackknife007/crnn | ['optical character recognition', 'scene text recognition'] | ['An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition'] | cnn+lstm+ctc.py generate.py build_graph get_next_batch get_test_data get_image_and_text test get_sparse_tuple get_acc train get_text generate transpose convert len list asarray extend map index zip range enumerate len glob get_image_and_text shuffle floor append zeros enumerate len glob get_image_and_text choice floor append zeros enumerate as_list constant max_pooling2d truncated_normal Variable reshape transpose float32 sparse_placeholder placeholder matmul conv2d batch_normalization add int32 join range len ctc_beam_search_decoder build_graph minimize ctc_loss reduce_mean Saver sparse_tensor_to_dense ctc_beam_search_decoder build_graph print Saver sparse_tensor_to_dense append randint range choice str ImageCaptcha write get_text mkdir range len | # crnn 基于tensoeflow的crnn实现,识别长度为3-10的验证码,除了容易混淆的大小写,其他的识别率都还不错.论文原地址https://arxiv.org/abs/1507.05717 | 2,442 |
jackryo/ricap | ['image cropping', 'data augmentation', 'image augmentation'] | ['Data Augmentation using Random Image Cropping and Patching for Deep CNNs'] | models/wide_resnet_cifar.py models/wide_resnet_imagenet.py models/commonlib.py models/__init__.py trainers.py utils.py main.py main make_trainer TrainerRICAP Trainer Lighting ProgressBar get_dataloaders adjust_learning_rate format_time get_num_classes Vectorize BasicWideBlock WideResNetDropout WideResNet Group init_params WideBlockBottleneck Group WideResNetDropoutBottleneck init_params WideResNetBottleneck Shortcut SGD params ArgumentParser depth dataset adlr savemodel sorted list load_state_dict update_learning_rate parse_args append range epoch format eval lr mkdir resume make_trainer load print loadtxt add_argument parameters get_dataloaders array len join Compose ImageFolder DataLoader Normalize CIFAR10 Tensor dataset CIFAR100 param_groups int isinstance size Conv2d bias sqrt kaiming_normal_ modules uniform_ BatchNorm2d weight constant_ Linear int print get_num_classes Sequential ReLU Conv2d init_params Group Vectorize item BatchNorm2d AdaptiveAvgPool2d Linear int print get_num_classes Sequential MaxPool2d Conv2d init_params Group Vectorize ReLU BatchNorm2d AdaptiveAvgPool2d Linear | # RICAP: Data Augmentation using Random Image Cropping and Patching for Deep CNNs PyTorch implementation of data augmentation method RICAP for deep CNNs proposed by "[Data Augmentation using Random Image Cropping and Patching for Deep CNNs](https://arxiv.org/abs/1811.09030)." ## Prerequisites * Python 3.5 * PyTorch 1.0 * GPU (recommended) ## Datasets * CIFAR-10/100: automatically downloaded by PyTorch scripts to `data` folder * ImageNet: manually downloaded from [ImageNet](http://www.image-net.org/) (ILSVRC2012 version) and moved to `train` and `val` folders in your `dataroot` path (e.g., `./imagenet/`) ## Results | 2,443 |
jaehanlee-mcl/multi-loss-rebalancing-depth | ['depth estimation', 'monocular depth estimation'] | ['Multi-Loss Rebalancing Algorithm for Monocular Depth Estimation'] | train.py utils/data.py utils/transform.py utils/utils.py evaluation.py prediction.py networks/pnasnet.py utils/get_data.py utils/multi_loss.py networks/model.py utils/loss.py main main main Up create_model Model_PNASNet5Large ReluConvBn pnasnet5large PNASNet5Large MaxPool Cell SeparableConv2d BranchSeparables CellStem0 CellBase FactorizedReduction _is_numpy_image depthDatasetMemoryTrain RandomChannelSwap ToTensor_with_RandomZoom RandomHorizontalFlip getTestDataPath _is_pil_image loadZipToMem _is_numpy_image getTestingData Scale getTrainingData Normalize _is_pil_image gradient_dx loss_for_normalized_depth loss_L1_by_channel loss_for_metric8 gradient_dy norm_loss normalized_depth loss_for_derivative print_scores pred2png get_model_summary make_model_path print_metrics get_notable_iter pred_path batch_size model print_metrics getTestingData DataParallel ArgumentParser ReLU DataFrame cuda half load_state_dict test_dataset_csv_list parse_args interpolate_bicubic_fullsize range pred2png size interpolate_bicubic_inputsize mean eval test_dataset_path mkdir model_path float compute_multi_metric enumerate load time get_metric_1batch print Variable add_argument to_csv model_name Upsample zeros numpy len print_scores get_loss_initialize_scale zero_grad save backbone max initialize train_dataset_path lambda_for_adjust_min make_model_path get_loss_weights Adam epochs weight_initialization train_dataset_csv_list sum state_dict format create_model get_model_summary relu get_loss_1batch get_notable_iter bs lr lambda_for_adjust_slope decoder_scale backward compute_multi_loss zfill min parameters getTrainingData weight_rebalancing lambda_for_adjust_start train step array cuda PNASNet5Large in_features load_url load_state_dict Linear list format print ZipFile len Compose depthDatasetMemoryTrain copy loadZipToMem Compose depthDatasetMemoryTrain copy loadZipToMem size conv2d pad zeros float size conv2d pad zeros float mean abs mean pow size min exp relu mean pow log10 ReLU float abs log norm_loss gradient_dx loss_L1_by_channel gradient_dy avg_pool2d pad mean loss_L1_by_channel normalized_depth fromarray uint16 astype zfill save remove format namedtuple model linesep apply eval len print format print format mkdir now zfill ceil zeros range | # [ECCV 2020] Multi-Loss Rebalancing Algorithm for Monocular Depth Estimation  ------ ## 1. Paper If you use our code or results, please cite: ``` @InProceedings{Lee_2020_ECCV, author = {Lee, Jae-Han and Kim, Chang-Su}, title = {Multi-Loss Rebalancing Algorithm for Monocular Depth Estimation}, booktitle = {Proceedings of the European Conference on Computer Vision (ECCV)}, | 2,444 |
jaehyunnn/cnngeometric_tensorflow | ['geometric matching'] | ['Convolutional neural network architecture for geometric matching'] | train.py geotnf/transformation.py demo.py image/normalization.py util/train_test_fn.py data/download_datasets.py util/tf_util.py geotnf/point_tnf.py model/cnn_geometric_model.py data/pf_dataset.py data/synth_dataset.py model/loss.py model/nets.py download_PF_willow download_pascal PFDataset SynthDataset PointTnf PointsToUnitCoords PointsToPixelCoords SynthPairTnf AffineGridGen GeometricTnf normalize_image NormalizeImageDict CNNGeometric FeatureExtraction FeatureL2Norm FeatureRegression FeatureCorrelation TransformedGridLoss resnet101 vgg16 str_to_bool save_checkpoint BatchTensorToVars reload_checkpoint train join remove basename print extractall close urlopen ZipFile makedirs join remove basename print extractall close urlopen open makedirs identity shape tile NormAxis expand_dims identity shape tile NormAxis expand_dims ndarray isinstance multiply subtract astype divide add shape tile expand_dims array print save print restore int format pair_generation_tnf print default_timer choice dict run append array range len | # CNNGeometric Re-implementation using TensorFlow <p align="center"> <img width="30%" src="https://blogs.rstudio.com/tensorflow/posts/2017-08-17-tensorflow-v13-released/tensorflow-logo.png"> </p> ----------------- <p align="center"> <img src="http://www.di.ens.fr/willow/research/cnngeometric/images/teaser.png"><br><br> </p> This is the re-implementation of the paper: I. Rocco, R. Arandjelović and J. Sivic. Convolutional neural network architecture for geometric matching. CVPR 2017 <br> | 2,445 |
jain-abhinav02/VoiceFilter | ['speech recognition', 'speaker recognition', 'speaker separation', 'speech enhancement'] | ['VoiceFilter: Targeted Voice Separation by Speaker-Conditioned Spectrogram Masking'] | train_test/train.py dataset/dataset_creation.py dataset/speech_collection.py model/model.py dataset/preload_training_dataset.py configuration/Audio.py model/sequence_generator.py train_test/testing.py dataset/directory_structure.py configuration/HyperParams.py Audio HyperParams get_dvector create_example SpeechEmbedder LinearNorm create_dataset save_batch create_folders load_all_data preload_training_data load_col_data get_model data_generator compute_loss_sdr numpy float embedder get_mel_spec load int wave2spec join get_dvector sample_rate trim save abs max data_audio_len list print min create_example append abs max range len join to_csv append DataFrame read_csv join makedirs append load range join list str load_col_data save range join list load_col_data save range Model Input concatenate list square tqdm mean load_weights spec2wave append median array range predict | # Voice Filter This is a Tensorflow/Keras implementation of Google AI VoiceFilter. Our work is inspired from the the academic paper : https://arxiv.org/abs/1810.04826 The implementation is based on the work : https://github.com/mindslab-ai/voicefilter --- ### Team Members 1. [Angshuman Saikia](https://github.com/HeliosX7) 1. [Abhinav Jain](https://github.com/jain-abhinav02) 1. [Yashwardhan Gautam](https://github.com/yashwardhan-gautam) --- | 2,446 |
jakeju/wav2letter | ['speech recognition'] | ['wav2letter++: The Fastest Open-source Speech Recognition System'] | recipes/models/self_training/librispeech/lm/generate_lm_raw_text.py recipes/models/self_training/librispeech/lm/filter_contractions.py recipes/models/seq2seq_tds/librispeech/prepare.py recipes/models/lexicon_free/utilities/compute_upper_ppl_kenlm.py recipes/models/conv_glu/librispeech/prepare.py recipes/models/lexicon_free/utilities/utils.py recipes/data/wsj/prepare.py recipes/models/sota/2019/lm_corpus_and_PL_generation/dump_title.py recipes/models/sota/2019/lm_analysis/shuffle_segments.py recipes/models/self_training/librispeech/lm/clean_lm_text.py recipes/models/utilities/prepare_librispeech_official_lm.py recipes/models/sota/2019/lm_corpus_and_PL_generation/postprocessing.py recipes/models/lexicon_free/utilities/compute_upper_ppl_convlm.py recipes/models/sota/2019/raw_lm_corpus/process_raw_text.py recipes/models/local_prior_match/librispeech/prepare.py recipes/models/self_training/librispeech/lm/prepare_wp_data.py recipes/models/self_training/pseudo_labeling/generate_synthetic_data.py recipes/models/sota/2019/lm_analysis/filter_segmentations.py recipes/models/utilities/convlm_serializer/save_pytorch_model.py recipes/models/local_prior_match/librispeech/prepare_unpaired.py recipes/data/librispeech/utils.py recipes/models/self_training/pseudo_labeling/combine_synthetic_lexicons.py recipes/models/conv_glu/wsj/prepare.py recipes/models/self_training/librispeech/lm/utils.py recipes/models/sota/2019/lm_corpus_and_PL_generation/generate_kenlm_vocab.py recipes/models/lexicon_free/librispeech/prepare.py recipes/models/self_training/pseudo_labeling/synthetic_lexicon_utils.py recipes/models/sota/2019/lm_corpus_and_PL_generation/dump.py recipes/models/sota/2019/lm_analysis/tts_forward.py recipes/models/sota/2019/raw_lm_corpus/get_titles.py recipes/models/self_training/librispeech/lm/sentence_ify.py recipes/models/sota/2019/lm_analysis/generate_shuffle_dev_other_tts.py recipes/models/sota/2019/lm/prepare_wp_data.py recipes/models/self_training/librispeech/lm/prepare_seq2seq_dict.py recipes/models/sota/2019/raw_lm_corpus/filter_distances.py recipes/models/sota/2019/lm_corpus_and_PL_generation/generate_uniq.py recipes/models/lexicon_free/utilities/compute_lower_ppl_kenlm.py recipes/models/sota/2019/rescoring/forward_lm.py recipes/data/wsj/utils.py recipes/models/self_training/pseudo_labeling/dataset_utils.py recipes/models/sota/2019/lm_corpus_and_PL_generation/skip_paragraph.py recipes/models/sota/2019/lm_corpus_and_PL_generation/generate_frequencies.py recipes/models/sota/2019/raw_lm_corpus/join_ids.py recipes/data/timit/prepare.py recipes/data/librispeech/prepare.py recipes/models/sota/2019/rescoring/rescore.py recipes/models/lexicon_free/utilities/compute_lower_ppl_convlm.py recipes/models/utilities/prepare_librispeech_wp_and_official_lexicon.py recipes/models/sota/2019/lm_corpus_and_PL_generation/preprocessing.py recipes/models/lexicon_free/utilities/convlm_utils.py recipes/models/lexicon_free/wsj/prepare.py recipes/models/sota/2019/raw_lm_corpus/get_gb_books_by_id.py recipes/models/learnable_frontend/prepare.py recipes/models/self_training/pseudo_labeling/generate_synthetic_lexicon.py recipes/models/sota/2019/lm_corpus_and_PL_generation/postprocessing_title.py parse_speakers_gender read_list transcript_to_list find_transcript_files copy_to_flac process_path ndx_to_samples convert_to_flac preprocess_word find_transcripts get_spelling compute_word_logprob compute_words_model_pdf_mass compute_ppl_lower_limit compute_denominator compute_word_logprob compute_words_model_pdf_mass compute_ppl_lower_limit compute_denominator compute_ppl_upper_limit_char_convlm compute_ppl_upper_limit_word_convlm compute_upper_limit_ppl_for_kenlm load_char_model_14B compute_new_state load_word_model decodeInputText load_char_model_20B build_token_index_correspondence convert_words_to_letters_asg_rep2 transform_asg_back prepare_vocabs_convlm transform_asg prepare_vocabs compare remap_words_with_same_spelling get_spelling load clean write eprint run_for_id run write_lm_books_to_file load_lm_books get_am_bookids remove_am_books_from_lm load findtranscriptfiles parse_speakers_gender transcript_to_list read_list run combine_lexicons write_transcript_list_to_file create_transcript_dict_from_listfile Transcript zip_datasets eprint TranscriptPrediction filter_transcripts create_transcript_set compute_ngrams pair_transcripts_with_existing_list run create_spellings generate_wp_selling generate order_lexicon run LexiconEntry read_spellings_from_file write_spellings_to_file count process tts run_tts eprint run main get_one_book eprint main get_one_title_from_cache get_one_title run main strip_header extract_one_book load_lm predict_batch score compute convert save_model endswith join walk append dirname join Transformer format remove replace duration system build dict set_output_format lower sub replace dict join walk setdefault sort join Transformer format remove duration strip system build set_output_format sub replace cuda max argsort sum compute_word_logprob compute_words_model_pdf_mass exp print strip set add append enumerate len list State BaseScore str append power State array BeginSentenceWrite BaseScore transform_asg_back split State exp format print cuda enumerate exp format print cuda enumerate dict items list load compute_new_state eval load_state_dict cuda load compute_new_state eval load_state_dict cuda load compute_new_state eval load_state_dict cuda append dict items list sorted defaultdict dict sub print str join replace print strip split append find join run_for_id append int append set endswith join walk append sorted word append keys combine_entries add_argument output write_spellings_to_file lexicon1 read_spellings_from_file lexicon2 ArgumentParser combine_lexicons parse_args list keys create_transcript_dict_from_listfile prediction ngram eprint warnings prediction warning sid print_filtered_results append split write_transcript_list_to_file viterbi filter_transcripts create_transcript_set distributed_decoding listpath pair_transcripts_with_existing_list input append items sorted list append keys split add_spelling sorted LexiconEntry keys str sorted inputlexicon inputhyp print create_spellings keys sorted_spellings generate append order_lexicon sorted append sorted keys pop join defaultdict print len append float enumerate split format time T format print generate synthesis cuda tts save_wav eprint join strip eprint str starmap add_argument ThreadPool ArgumentParser parse_args replace print map cachepath format write print strip_header from_pretrained print eval cuda split len append sum cuda enumerate items sorted enumerate len load | # wav2letter++ [](https://gitter.im/wav2letter/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) **Please use for now stable version at https://github.com/facebookresearch/wav2letter/tree/v0.2. We are restucturing and moving things to the [flashlight](https://github.com/facebookresearch/flashlight)** wav2letter++ is a fast, open source speech processing toolkit from the Speech team at Facebook AI Research built to facilitate research in end-to-end models for speech recognition. It is written entirely in C++ and uses the [ArrayFire](https://github.com/arrayfire/arrayfire) tensor library and the [flashlight](https://github.com/facebookresearch/flashlight) machine learning library for maximum efficiency. Our approach is detailed in this [arXiv paper](https://arxiv.org/abs/1812.07625). This repository also contains **pre-trained** models and implementations for various ASR results including: - [NEW] [Pratap et al. (2020): Scaling Online Speech Recognition Using ConvNets](recipes/models/streaming_convnets/) - [NEW SOTA] [Synnaeve et al. (2019): End-to-end ASR: from Supervised to Semi-Supervised Learning with Modern Architectures](recipes/models/sota/2019) - [Kahn et al. (2019): Self-Training for End-to-End Speech Recognition](recipes/models/self_training) - [Likhomanenko et al. (2019): Who Needs Words? Lexicon-free Speech Recognition](recipes/models/lexicon_free/) - [Hannun et al. (2019): Sequence-to-Sequence Speech Recognition with Time-Depth Separable Convolutions](recipes/models/seq2seq_tds/) | 2,447 |
jakerylandwilliams/partitioner | ['chunking'] | ['Boundary-based MWE segmentation with text partitioning'] | setup.py partitioner/__init__.py partitioner/tools.py tests/test.py partitioner test_uniformOneOff uniformStochasticPartition testPartitionTextAndFit informedOneOffPartition test_oneoff test_informed uniformOneOffPartition informedStochasticPartition test_preprocess preprocessENwiktionary test_uniformStochastic partitioner dumpqs preprocessENwiktionary print oneoff partition informedOneOffPartition print stochastic partition informedStochasticPartition print oneoff partition uniformOneOffPartition print stochastic partition uniformStochasticPartition sorted oneoff rsq print partitionText counts round range testFit | ## Synopsis This is the Python partitioner project. The partitioner module performs advanced NLP tasks essentially equivalent to tokenization (e.g., splitting texts into words), with generalizations into multiword expressions (MWE) segmentation. A definition for those unfamiliar with MWEs: “A group of tokens in a sentence that cohere more strongly than ordinary syntactic combinations.” Thus, partitioner may be used to split texts "phrases" of one or more words. ## Code Example To load the module, run: \>\>\> from partitioner.tools import partitioner Since the module comes with no data, running informed partitions will require acquiring the training data, which may be acquired by engaging the `.download()` method: \>\>\> pa = partitioner() \>\>\> pa.download() | 2,448 |
jambo6/generalised_shapelets | ['audio classification', 'time series'] | ['Generalised Interpretable Shapelets for Irregular Time Series'] | torchshapelets/src/torchshapelets/regularisation.py experiments/parse_results.py experiments/uea.py torchshapelets/setup.py torchshapelets/src/torchshapelets/__init__.py get_data/speech_commands.py experiments/speech_commands.py torchshapelets/src/torchshapelets/discrepancies.py torchshapelets/src/torchshapelets/shapelet_transform.py experiments/common.py get_data/uea.py torchshapelets/metadata.py save_results _train_loop assert_not_done _evaluate_model save_top_shapelets_and_minimizers upsample_minimizers_and_shapelets _get_sample_batch dataloader _evaluate_metrics _compute_multiclass_accuracy _TensorEncoder _AttrDict _compute_binary_accuracy main handle_seeds normalise_data LinearShapeletTransform get_discrepancy_fn _count_parameters get main _load_data invert comparison_test _get_sample get_data main hyperparameter_search_old _pad comparison_test missing_and_length_test get_data _subfolder hyperparameter_search_l2 main pendigits_interpretability _save_data _process_data _split_data main download main LogsignatureDiscrepancy CppDiscrepancy L2Discrepancy similarity_regularisation GeneralisedShapeletTransform seed manual_seed sum isdir unbind mean zip append std min len int defaultdict randn_like stack zip append dtype to sum size dtype sum size to argmax LogsignatureDiscrepancy int L2Discrepancy split data model zero_grad ReduceLROnPlateau clip_length _evaluate_metrics dtype list append to range format inf _AttrDict eval zip loss_fn deepcopy backward write accuracy tqdm parameters similarity_regularisation train step loss eval _evaluate_metrics int str copy mkdir save listdir max state_dict load str list format items argmin upsample_minimizers_and_shapelets load_state_dict save cat detach size argmin linspace append upsample_path range Tensor len save_results _train_loop _evaluate_model save_top_shapelets_and_minimizers full_like max Adam binary_cross_entropy_with_logits to cross_entropy size set_kmeans_shapelets lengths requires_grad_ int time register_buffer min parameters LinearShapeletTransform get_discrepancy_fn listdir values str list sorted name stdev add OrderedDict get format inf set mean listdir items print split len endswith str listdir load list listdir load_wav choice zeros_like zero_grad SGD ReduceLROnPlateau numpy linspace tensor _load_data MFCC squeeze argmin transpose shape load_state_dict get_discrepancy_fn append to cat format size item zip trange float empty load int backward print write LinearShapeletTransform bool step mse_loss find _load_data size TensorDataset linspace dataloader get_data main range handle_seeds assert_not_done tensor full randn tensor max values str load_from_tsfile_to_dataframe transpose OrderedDict randperm append train_test_split range cat concatenate reversed stack zip manual_seed normalise_data to_numpy print str main assert_not_done print str main assert_not_done print _subfolder str int print handle_seeds assert_not_done _subfolder main range print main handle_seeds train_test_split str list items save mkdir str urlretrieve exists load_wav listdir unbind mean _split_data stack zip append empty std detach _save_data download _process_data mkdir urlretrieve exists l2_discrepancy | <h1 align='center'> Generalised Interpretable Shapelets for Irregular Time Series<br> [<a href="https://arxiv.org/abs/2005.13948">arXiv</a>] </h1> <p align="center"> <img align="middle" src="./paper/images/new_pendigits.png" width="666" /> </p> A generalised approach to _the shapelet method_ used in time series classification, in which a time series is described by its similarity to each of a collection of 'shapelets'. Given lots of well-chosen shapelets, then you can now look at those similarities and conclude that "This time series is probably of class X, because it has a very high similarity to shapelet Y." We extend the method by: + Extending to irregularly sampled, partially observed multivariate time series. + Differentiably optimising the shapelet lengths. (Previously a discrete parameter.) + Imposing interpretability via regularisation. | 2,449 |
jamesHargreaves12/incremental_beam_manipulation | ['text generation'] | ['Incremental Beam Manipulation for Natural Language Generation'] | tmp2.py embedding_extractor.py optimization_run.py beam_search.py base_models.py optimize_length_norm_alpha.py train_seq2seq.py get_results.py train_beam_manipulator.py scorer_functions.py utils.py get_results_bleu_scores.py train_tgen_reranker.py optimization_controller.py flatten_multi_ref PairwiseReranker relative_logcosh_loss get_training_set_min_max_lp relative_absolute_error_loss TGEN_Model Regressor absolute_percentage_error_loss shuffle_data TrainableReranker TGEN_Reranker relative_mae_loss score_beams run_nucleus_sampling order_beam_acording_to_rescorer order_beam_after_greedy_complete score_beams_pairwise run_beam_search_with_rescorer _run_beam_search_with_rescorer TokEmbeddingSeq2SeqExtractor DAEmbeddingSeq2SeqExtractor do_nucleus_sampling do_beam_search test_res_official print_results get_length_normalised_score_func get_regressor_score_func get_score_function get_tgen_rerank_score_func get_power get_random_score_func get_learned_score_func get_oracle_score_func get_identity_score_func get_scores_ordered_beam count_lines get_features load_model_from_gpu tgen_postprocess RERANK get_section_cutoffs get_test_das get_abstss_train remove_strange_toks postprocess get_multi_reference_training_variables safe_get_w2v get_abstss_test get_texts_training get_section_value get_training_das_texts get_training_variables get_regression_vals get_das_texts_from_webnlg get_true_sents apply_absts fakeDAI normalise get_hamming_distance get_final_beam list shuffle append range len mean mean load format extend exists open append zip sorted defaultdict predict_order text_embedder setup_lps append array range enumerate len rescorer sum append len get_regression_vals sorted score_beams get_section_cutoffs extend score_beams_pairwise sum NotImplementedError enumerate len all beam_search_exapand order_beam_acording_to_rescorer copy max range time all beam_search_exapand print text_embedder reverse_embedding tqdm append end_embs da_embedder array range predict join sorted format all beam_search_exapand order_beam_acording_to_rescorer order_beam_after_greedy_complete write end_embs range load time format dump print len write text_embedder order_beam_acording_to_rescorer reverse_embedding tqdm split _run_beam_search_with_rescorer append da_embedder array predict open get join sorted format list apply_absts PairwiseReranker get_score_function print test_res_official makedirs safe_load run_beam_search_with_rescorer abspath choices open range pardir get join format apply_absts print run_nucleus_sampling makedirs abspath test_res_official pardir join BLEUScore score load_data zip append int join sorted argv print append listdir split pow get format BLEUScore load_model print text_embedder TGEN_Reranker TrainableReranker da_embedder TGEN_Model to_categorical open get_embeddings list sorted get_score_function get_section_cutoffs load_models append get format get_multi_reference_training_variables BLEUScore zip get_section_value enumerate load get_regression_vals print reshape extend tqdm run_beam_search_with_rescorer reset array load split append open join print pos_tag lower append split value match zip append compile read_das get_das_texts_from_webnlg read_das get_training_variables items list defaultdict zip append read_das pop format open append float split File layers load_weights_from_hdf5_group sub strip upper Regex sub enumerate | jamesHargreaves12/incremental_beam_manipulation | 2,450 |
jameshensman/VFF | ['gaussian processes'] | ['Variational Fourier features for Gaussian processes'] | experiments/banana/banana_plotting.py experiments/airline/airline_vff_additive.py experiments/increasing_dim/Exp_4/full.py experiments/increasing_dim/Exp_4/gen_data.py experiments/increasing_dim/Exp_4/sparse.py VFF/psi_statistics.py experiments/increasing_dim/Exp_2/plot.py VFF/kronecker_ops.py VFF/sfgpmc_kronecker.py experiments/increasing_dim/gen_data.py experiments/increasing_dim/Exp_1/kron.py experiments/increasing_dim/Exp_3/plot.py experiments/increasing_dim/Exp_1/vff.py experiments/increasing_dim/Exp_4/run_experiment.py experiments/increasing_dim/config.py experiments/increasing_dim/Exp_3/run_experiment.py testing/test_matrix_structures.py experiments/increasing_dim/vff.py experiments/increasing_dim/Exp_2/sparse.py experiments/increasing_dim/Exp_1/full.py experiments/increasing_dim/Exp_1/run_experiment.py experiments/increasing_dim/Exp_1/plot.py VFF/gpmc.py experiments/increasing_dim/sparse.py experiments/increasing_dim/Exp_3/gen_data.py VFF/vgp.py experiments/increasing_dim/plot.py experiments/simple_regression/figure.py experiments/increasing_dim/Exp_2/full.py experiments/mcmc_pines/run_pines.py experiments/increasing_dim/run_experiment.py experiments/increasing_dim/Exp_3/config.py experiments/setting_a_b_M/gpr_special.py experiments/increasing_dim/Exp_3/vff.py VFF/__init__.py experiments/airline/airline_naive_additive.py experiments/increasing_dim/Exp_1/gen_data.py experiments/increasing_dim/Exp_4/plot.py experiments/increasing_dim/Exp_3/full.py experiments/solar/solar.py experiments/increasing_dim/Exp_2/gen_data.py experiments/airline/airline_svigp_rbf.py experiments/increasing_dim/Exp_4/vff.py experiments/increasing_dim/Exp_2/vff.py experiments/increasing_dim/Exp_2/run_experiment.py experiments/increasing_dim/Exp_4/config.py testing/test_kronecker_ops.py experiments/mcmc_pines/plot_pines.py experiments/increasing_dim/Exp_2/config.py experiments/banana/ELBO_vs_M.py experiments/increasing_dim/Exp_3/sparse.py VFF/gpr.py experiments/increasing_dim/Exp_1/config.py VFF/ssgp.py experiments/airline/airline_naive_rbf.py experiments/increasing_dim/full.py VFF/spectral_covariance.py experiments/setting_a_b_M/make_figure.py VFF/matrix_structures.py experiments/airline/airline_additive_figure.py experiments/increasing_dim/Exp_1/sparse.py plot subset subset subset cb subset plot run_experiment randomize_and_optimize plot build_model prodkern prodkern plot_all prodkern prodkern prodkern plot_all prodkern prodkern plot_all plot_all_all prodkern prodkern plot_all plot_all_all prodkern prodkern plot_all plot_model getGrid getCounts build_model init_model plot_model set_priors getLocations GPR_1d plot plot plot TestKrons TestLogDetSum_np TestKVS TestLogDetSum_tf TestLRMat TestBlockMat TestDiagMats TestR1Mat kron_vec_sqrt_transpose GPMC_kron plot GPMC_1d GPR_1d GPR_additive GPRKron kron_mat_apply make_kvs kron_vec_apply kvs_dot_vec_specialfirst kvs_dot_vec_memhungry kron_mat_triangular_solve kron_vec_mul make_kvs_np kvs_dot_vec_loop kron_two log_det_kron_sum make_kvs_two_np kvs_dot_mat log_det_kron_sum_np kron make_kvs_two kron_vec_triangular_solve kron_mat_mul kvs_dot_vec LowRankMatNeg Rank1Mat BlockDiagMat Rank1MatNeg DiagMat BlockDiagMat_many LowRankMat psi2 uniform psi1 kron_vec_sqrt_transpose plot SFGPMC_kron make_Kuf_np make_Kuf_no_edges make_Kuf make_Kuf_np_with_edges make_Kuu SSGP VGP_kron_anyvar plot VGP_1d VGP_kron VGP_additive subplots set_title predict_components sqrt range permutation reshape mean std values len print compute_log_likelihood mean predict_y set_state flush T reshape set_xlim predict_y contour set_ylim VGP_kron arange optimize size set_state randn format subplots randomize_and_optimize plot build_model print savetxt savefig reset_default_graph range max zeros enumerate format subplots set_title plot inf set_xlabel semilogx merge legend read_csv enumerate subplot format inf set_title plot set_xlabel semilogx figure legend round read_csv enumerate merge iterrows value T set_parameter_dict predict_y mean imshow flipud append loadtxt histogramdd array linspace Gaussian Gamma plot set_state getLocations figure getCounts getGrid Poisson GPMC_kron Constant optimize value predict_f vlines format compute_log_likelihood float min max stack exp squeeze flatten ylim set_state figure stack stack stack stack stack reshape transpose matmul stack tile expand_dims while_loop zeros float_type constant reshape transpose matmul stack expand_dims sum prod mul ones float64 reduce add kron_vec_mul exp transpose cos pi sin exp reshape square pi expand_dims reshape cos square pi sin scatter isinstance Matern12 ones concat variance astype float32 pi where square sqrt shape lengthscales pow Matern52 Matern32 transpose cos pi sin cos pi where Matern52 abs Matern32 exp transpose shape sin Matern12 astype with_dependencies sqrt tile isinstance float32 logical_or lengthscales zeros T pi T value exp isinstance Matern12 pi sqrt Matern52 abs Matern32 Y X | # VFF Variational Fourier Features for Gaussian Processes By James Hensman, Nicolas Durrande and Arno Solin. Code accompanies this JMLR paper: http://www.jmlr.org/papers/v18/16-579.html ### Install VFF relies heavily on [GPflow](github.com/GPflow/GPflow). After installing GPflow, clone this repo and add the VFF directory to your PYTHONPATH. There are some examples in the `experiments` directory that replicate figures from the manuscript. Questions and comments are welcome via github issues on this repo. | 2,451 |
jamesmullenbach/caml-mimic | ['medical code prediction'] | ['Explainable Prediction of Medical Codes from Clinical Text'] | dataproc/concat_and_split.py dataproc/vocab_index_descriptions.py evaluation.py dataproc/extract_wvs.py persistence.py dataproc/build_vocab.py dataproc/prepare_qualitative_evaluation.py log_reg.py get_metrics_for_saved_predictions.py dataproc/word_embeddings.py learn/tools.py learn/training.py dataproc/get_discharge_summaries.py learn/interpret.py datasets.py constants.py learn/models.py load_code_descriptions Batch reformat load_description_vectors pad_desc_vecs load_vocab_dict data_generator load_full_codes load_lookups micro_precision print_metrics micro_recall micro_accuracy macro_f1 results_by_type recall_at_k macro_accuracy macro_recall precision_at_k metrics_from_dicts micro_f1 proc_f1 all_macro all_micro diag_f1 intersect_size auc_metrics inst_recall inst_precision union_size macro_precision inst_f1 all_metrics construct_X_Y read_bows write_bows main calculate_top_ngrams save_metrics write_preds save_everything save_params_dict build_vocab next_labels split_data next_notes concat_data build_matrix load_embeddings save_embeddings gensim_to_embeddings write_discharge_summaries main vocab_index_descriptions word_embeddings ProcessedIter important_spans make_windows save_samples VanillaRNN BOWPool ConvAttnPool VanillaConv BaseModel build_code_vecs make_param_dict pick_model train_epochs unseen_code_vecs train test init main early_stop one_epoch append max extend len set vocab load_code_descriptions set data_path load_description_vectors load_full_codes load_vocab_dict Y defaultdict load_code_descriptions set join startswith split defaultdict update recall_at_k all_micro precision_at_k auc_metrics ravel all_macro union_size intersect_size sum intersect_size sum intersect_size macro_precision macro_recall sum intersect_size sum intersect_size inst_recall inst_precision append float sum array enumerate len append float sum enumerate micro_recall micro_precision roc_curve mean append ravel range auc sorted defaultdict set intersection keys zeros tqdm enumerate len zeros tqdm enumerate len sorted set tqdm intersection zeros keys enumerate len print items list print_metrics calculate_top_ngrams str list defaultdict field_size_limit LogisticRegression shape append range predict write_preds replace set predict_proba mkdir save_metrics load_lookups maxsize keys int join print OneVsRestClassifier read_bows zeros all_metrics fit len len writer coef_ writerow close set zeros range open zip enumerate nanargmax print nanargmin save_params_dict save save_metrics cuda gpu state_dict join print write set open append int next reader int next reader load build_matrix replace set wv save_embeddings items list tqdm word_vec append zeros len array print load_code_descriptions RegexpTokenizer load_code_descriptions set join ProcessedIter print Word2Vec save train build_vocab important_spans str round join str write make_windows append numpy append items sorted list VanillaRNN BOWPool pool cell_type filter_size VanillaConv code_emb cuda rnn_dim ConvAttnPool test_model num_filter_maps rnn_layers load_state_dict embed_file dropout bidirectional embed_size load int lmbda gpu len append pad_desc_vecs list time train_epochs init print field_size_limit Adam parameters pick_model load_lookups make_param_dict maxsize batch_size abspath Y list defaultdict save_everything test_model quiet dirname samples append range one_epoch patience mkdir version n_epochs pick_model keys join criterion print data_path early_stop gpu str defaultdict print test set mean nan train keys len format model print backward zero_grad set difference mean tqdm data_generator cuda append step keys enumerate len build_code_vecs data model print_metrics zero_grad round cuda open data_generator append write_preds replace concatenate unseen_code_vecs close mean eval save_samples enumerate print extend tqdm sigmoid all_metrics numpy len | **Status:** Archived. Code is provided as-is with no updates expected. Unfortunately I don't have the personal time to dedicate to maintaining this repo/responding to issues, nor access to the MIMIC dataset anymore, though I hope the model code and data splits can still be of use to the community. # caml-mimic Code for the paper [Explainable Prediction of Medical Codes from Clinical Text](https://arxiv.org/abs/1802.05695). ## Dependencies * Python 3.6, though 2.7 should hopefully work as well * pytorch 0.3.0 * tqdm * scikit-learn 0.19.1 * numpy 1.13.3, scipy 0.19.1, pandas 0.20.3 * jupyter-notebook 5.0.0 | 2,452 |
jamespltan/pnn | ['time series'] | ['Simulating extrapolated dynamics with parameterization networks'] | main_PlotNNBifurDiag.py PNN.py main_TrainPNN.py Utilities.py Lyapunov.py LogisticMap.py main_PlotLogMapBifurDiag.py main_PlotLyap.py main_PlotPeriodDoubling.py GenerateTS BifurcationDiagram lyap PNN num_format SlidingWindows shuffle_mini_batch_indices PrintTimeUnit TimeScript is_iterable zeros range show plot ones xlabel rc axis ylabel tight_layout flatten savefig figure zeros enumerate arange rand abs log str coef_ len RANSACRegressor loadNN append range concatenate close float enumerate get_parameters print reshape PNN GenerateTS zeros array fit GenerateTS zeros range iter isinstance int arange shuffle copy zeros range print str round | # pnn | 2,453 |
jamesrobertlloyd/gp-structure-search | ['gaussian processes', 'time series'] | ['Structure Discovery in Nonparametric Regression through Compositional Kernel Search', 'Automatic Construction and Natural-Language Description of Nonparametric Regression Models'] | source/cblparallel/fear_put.py source/datasets/sea_level.py source/datasets/airline.py source/utils/profiler.py experiments/synthetic-SNR-1-13Feb.py experiments/synthetic-const-01-Mar-SNR-1.py source/cblparallel/config_example.py source/config_example.py source/mitparallel/util.py source/utils/psd_matrices.py source/demo.py source/datasets/methane.py examples/fast_example.py source/flexiblekernel.py experiments/synthetic-wiggles-SNR-1-13Feb.py experiments/gefcom_test_01.py experiments/synthetic-const-01-Mar-SNR-tenth.py source/mit_experiments/base.py data/raw/TSDL/standardise.py source/mitparallel/matlab.py source/cblparallel/__init__.py experiments/synthetic-12Feb.py source/testing/test_kernels.py experiments/multi-d-400-11Mar-no-const.py experiments/1d-ex-12Feb.py experiments/synthetic-const-28-Feb.py source/cblparallel/fear_get.py experiments/swiss-roll2-17May.py experiments/synthetic-now-with-const-26-Feb.py source/mitparallel/__init__.py source/cblparallel/util.py experiments/1d-ex-11Feb.py experiments/synthetic-const-28-Feb-SNR-1.py source/mitparallel/parallel.py experiments/run_solar.py experiments/synthetic-const-04-Mar-SNR-root-10.py source/cblparallel/pyfear.py source/datasets/solar.py data/raw/TSDL/processed/convert-to-mat.py source/utils/counter.py experiments/1d_no_RQ_test.py experiments/run_all_1d.py source/utils/misc.py experiments/synthetic-wiggles-13Feb.py experiments/synthetic-12Feb-local.py experiments/multi-d-350-28Feb.py source/datasets/ekg.py experiments/1d_scaling_test.py source/mit_job_controller.py source/experiment.py source/utils/latex.py source/job_controller.py sandpit/test_kernels.py experiments/debug_example.py source/testing/test_gpml.py source/datasets/__init__.py experiments/26-Feb-test.py source/postprocessing.py source/datasets/eeg.py experiments/multi-d-250-16Feb.py experiments/synthetic-13Feb-local.py source/gpml.py source/utils/fear.py source/grammar.py source/utils/gaussians.py experiments/1d-ex-9Feb.py source/sandpit.py examples/realistic_example.py source/utils/mkl_hack.py experiments/1d-ex-roger-15Feb-random.py experiments/synthetic-const-28-Feb-SNR-tenth.py experiments/synthetic-const-04-Mar-SNR-root-tenth.py experiments/1d-ex-roger-15Feb.py experiments/synthetic-13Feb.py source/mit_experiments/search_oneproc.py experiments/28-Feb-test.py experiments/multi-d-11Feb.py experiments/multi-d-400-11Mar.py experiments/synthetic-SNR-tenth-14Feb.py experiments/multi-d-6May.py parse_results generate_model_fits run_debug_kfold gen_all_datasets experiment_fields_to_str Experiment run_experiment_file remove_nan_scored_kernels perform_experiment perform_kernel_search calculate_model_fits remove_duplicates ScoredKernel BaseKernel PP3KernelFamily replace_defaults PP1KernelFamily MaskKernelFamily LinKernel SumKernel PP0Kernel distribute_products add_random_restarts_single_kernel PP3Kernel Kernel SqExpPeriodicKernel RQKernelFamily CubicKernelFamily SqExpKernelFamily paren_colors ProductKernelFamily ProductKernel test_kernels repr_string_to_kernel SqExpPeriodicKernelFamily QuadraticKernelFamily base_kernels test_kernel_families ChangeKernelFamily strip_masks ChangeKernel SqExpKernel RQKernel LinKernelFamily Carls_Mauna_kernel PP2Kernel QuadraticKernel colored break_kernel_into_summands KernelFamily PP0KernelFamily MaskKernel BaseKernelFamily CubicKernel SumKernelFamily MaternKernelFamily PP2KernelFamily shrink_below_tolerance base_kernel_families ConstKernelFamily add_random_restarts ConstKernel PP1Kernel MaternKernel sample_from_gp_prior OptimizerOutput posterior_mean read_outputs plot_kernel make_predictions load_mat optimize_params run_matlab_code plot_decomposition expand_single_tree OneDGrammar polish_to_kernel expand MultiDGrammar expand_kernels canonical remove_duplicates replace_all evaluate_kernels covariance_distance make_predictions compute_K_code make_predictions compute_K evaluate_kernel_code make_predictions_code evaluate_kernel fear_experiment load_mauna copy_to_fear fear_file_exists copy_from_fear sample_mauna_best debug_laplace call_gpml_test expand_test2 plot_gef_load_Z01 re_qsub fear_connect base_kernel_test full_gef_load_experiment fear_qdel_all plot_gef_load_Z01_raw plot_our_kernel fear_run_experiments load_mauna_original expand_test load_full_gef_load sample_Carls_kernel plot_gef_load_Z01_split_mean_temp main plot_Carls_kernel fear_expand_kernels kernel_test fear_command simple_gef_load_experiment simple_mauna_experiment load_simple_gef_load fear_rm qsub_matlab_code plot_gef_load_Z01_split_mean compare_kernels_experiment mkstemp_safe plot_gef_load_Z01_smooth_2d_mean fear_load_mat fear timeoutCommand mkstemp_safe run_batch_locally remove_temp_file setup create_temp_file run_batch_on_fear start_port_forwarding copy_to_remote gpml_path load_X_y data_file load_data WaveformInfo eeg_data_file load_all_channels channel_locs_file load_one_channel load_waveform_data load_channel_locs datset_url save_data dest_file record_url plot_examples temp_dir get_X_y load_data read_data datafile MonthlyStationInfo annual_matfile get_X_y read_monthly_data AnnualStationInfo read_annual_data monthly_matfile get_X_y irradiance_data_file add_wrapper run isint _status_path run_command _status_file parse_machines _run_job list_jobs run mkstemp_safe create_temp_file find_duplicates perform_search load_data remove_nan_scored_kernels SearchParams remove_duplicates Scheduler run load_mauna not_tet_matlab_runs not_tet_num_params not_tet_matlab_stops test_kernel_eval test_change_kernel_eval test_kernel_expand_multi_d test_kernel_decompose_1d test_kernel_expand main ProgressLine Progress Counter file_exists qstat_status qdel qdel_all job_running connect command job_terminated copy_to copy_from job_loading job_queued rm qsub Conditionals Distribution Potential clean table summarize_error resize my_inv broadcast _err_string transp match_shapes array_map process_slice min_abs_diff sample_truncated_normal set_all_random_seeds vdot extend_slice full_shape dot my_sum lstsq set_err_info summarize reset get_key profiled check_laplace_approx FullMatrix _x_QDQ_x proj_psd EigMatrix FixedEigMatrix laplace_approx_stable _QDQ_x BaseMatrix laplace_approx_no_prior laplace_approx DiagonalMatrix EyeMatrix parse_results generate_model_fits run_debug_kfold gen_all_datasets experiment_fields_to_str Experiment run_experiment_file remove_nan_scored_kernels perform_experiment perform_kernel_search calculate_model_fits remove_duplicates ScoredKernel BaseKernel PP3KernelFamily replace_defaults PP1KernelFamily MaskKernelFamily LinKernel SumKernel PP0Kernel distribute_products add_random_restarts_single_kernel PP3Kernel Kernel SqExpPeriodicKernel RQKernelFamily CubicKernelFamily SqExpKernelFamily paren_colors ProductKernelFamily ProductKernel test_kernels repr_string_to_kernel SqExpPeriodicKernelFamily QuadraticKernelFamily base_kernels test_kernel_families ChangeKernelFamily strip_masks ChangeKernel SqExpKernel RQKernel LinKernelFamily Carls_Mauna_kernel PP2Kernel QuadraticKernel colored break_kernel_into_summands KernelFamily PP0KernelFamily MaskKernel BaseKernelFamily CubicKernel SumKernelFamily MaternKernelFamily PP2KernelFamily shrink_below_tolerance base_kernel_families ConstKernelFamily add_random_restarts ConstKernel PP1Kernel MaternKernel sample_from_gp_prior OptimizerOutput posterior_mean read_outputs plot_kernel make_predictions load_mat optimize_params run_matlab_code plot_decomposition expand_single_tree OneDGrammar polish_to_kernel expand MultiDGrammar expand_kernels canonical remove_duplicates replace_all evaluate_kernels covariance_distance make_predictions compute_K_code compute_K evaluate_kernel_code make_predictions_code evaluate_kernel fear_experiment load_mauna copy_to_fear fear_file_exists copy_from_fear sample_mauna_best debug_laplace call_gpml_test expand_test2 plot_gef_load_Z01 re_qsub fear_connect base_kernel_test full_gef_load_experiment fear_qdel_all plot_gef_load_Z01_raw plot_our_kernel fear_run_experiments load_mauna_original expand_test load_full_gef_load sample_Carls_kernel plot_gef_load_Z01_split_mean_temp main plot_Carls_kernel fear_expand_kernels kernel_test fear_command simple_gef_load_experiment simple_mauna_experiment load_simple_gef_load fear_rm qsub_matlab_code plot_gef_load_Z01_split_mean compare_kernels_experiment mkstemp_safe plot_gef_load_Z01_smooth_2d_mean fear_load_mat fear timeoutCommand mkstemp_safe run_batch_locally remove_temp_file setup create_temp_file run_batch_on_fear start_port_forwarding copy_to_remote gpml_path load_X_y data_file load_data WaveformInfo eeg_data_file load_all_channels channel_locs_file load_one_channel load_waveform_data load_channel_locs datset_url save_data dest_file record_url plot_examples temp_dir get_X_y load_data read_data datafile MonthlyStationInfo annual_matfile get_X_y read_monthly_data AnnualStationInfo read_annual_data monthly_matfile irradiance_data_file add_wrapper run isint _status_path run_command _status_file parse_machines _run_job list_jobs mkstemp_safe create_temp_file find_duplicates perform_search load_data remove_nan_scored_kernels SearchParams remove_duplicates Scheduler run load_mauna not_tet_matlab_runs not_tet_num_params not_tet_matlab_stops test_kernel_eval test_change_kernel_eval test_kernel_expand_multi_d test_kernel_decompose_1d test_kernel_expand main ProgressLine Progress Counter file_exists qstat_status qdel qdel_all job_running connect command job_terminated copy_to copy_from job_loading job_queued rm qsub Conditionals Distribution Potential clean table summarize_error resize my_inv broadcast _err_string transp match_shapes array_map process_slice min_abs_diff sample_truncated_normal set_all_random_seeds vdot extend_slice full_shape dot my_sum lstsq set_err_info summarize reset get_key profiled check_laplace_approx FullMatrix _x_QDQ_x proj_psd EigMatrix FixedEigMatrix laplace_approx_stable _QDQ_x BaseMatrix laplace_approx_no_prior laplace_approx DiagonalMatrix EyeMatrix sorted covariance_distance min mean range len evaluate_kernels n_rand verbose nll rename remove_nan_scored_kernels log remove_duplicates alpha_heuristic list sorted laplace_nle base_kernels append use_constraints pretty_print range mean random_seed set_all_random_seeds use_min_period max_depth print lengthscale_heuristic sd expand_kernels add_random_restarts std bic_nle endswith sort splitext append walk split _fields zip join read list experiment_fields_to_str print gen_all_datasets data_dir system shuffle random_order eval results_dir perform_experiment makedirs join read list experiment_fields_to_str print gen_all_datasets data_dir system shuffle _replace random_order eval isfile results_dir calculate_model_fits makedirs join parse_results load_mat system make_predictions savemat results_dir perform_kernel_search join parse_results load_mat system make_predictions savemat results_dir run_experiment_file paren_colors base_kernel_families range range test_kernel_families SqExpKernel SqExpPeriodicKernel log RQKernel isinstance isinstance distribute_products isinstance read remove print close write mkstemp call open var remove print read_outputs close mkstemp savemat run_matlab_code log loadmat ravel remove param_vector close ravel mkstemp savemat run_matlab_code loadmat remove param_vector close mkstemp savemat run_matlab_code loadmat var remove close copy mkstemp savemat run_matlab_code loadmat log run_matlab_code join var print close mkstemp savemat dirname abspath break_kernel_into_summands run_matlab_code log loadmat list remove rules product type_matches dict polish_to_kernel zip append keys replace_all MaskKernel BaseKernel expand_single_tree isinstance SumKernel ProductKernel append operands enumerate MaskKernel BaseKernel isinstance SumKernel ProductKernel append operands append map print expand MultiDGrammar remove_duplicates pretty_print DISTANCE_CODE_COV remove_temp_file print create_temp_file DISTANCE_CODE_FOOTER_HIGH_MEM savemat copy_to_remote sub loadmat DISTANCE_CODE_HEADER enumerate var OPTIMIZE_KERNEL_CODE run_batch_locally from_matlab_output remove remove_temp_file print read_outputs family create_temp_file run_batch_on_fear savemat copy_to_remote sub OPTIMIZE_KERNEL_CODE_ZERO_MEAN log enumerate len remove_temp_file print PREDICT_AND_SAVE_CODE_ZERO_MEAN create_temp_file savemat copy_to_remote sub PREDICT_AND_SAVE_CODE loadmat join map param_vector var from_matlab_output remove read_outputs family create_temp_file savemat evaluate_kernel_code log run join map param_vector remove make_predictions_code run k_opt COMPUTE_K_CODE_HEADER join gpml_kernel_expression param_vector COMPUTE_K_CODE_FOOTER map enumerate remove compute_K_code create_temp_file savemat loadmat run MaskKernel gpml_kernel_expression param_vector print SqExpKernel pretty_print print SqExpPeriodicKernel SqExpKernel print OneDGrammar expand SumKernel remove_duplicates pretty_print MaskKernel SqExpPeriodicKernel SqExpKernel print expand MultiDGrammar SumKernel remove_duplicates pretty_print loadmat loadmat seed normal gpml_kernel_expression from_param_vector list sorted param_vector print load_mauna size draw semilogx SumKernel figure append optimize_params range pretty_print SqExpPeriodicKernel sample_from_gp_prior plot SqExpKernel title linspace figure sample_from_gp_prior plot Carls_Mauna_kernel title linspace figure SqExpPeriodicKernel gpml_kernel_expression from_param_vector param_vector SqExpKernel print load_mauna_original Carls_Mauna_kernel optimize_params pretty_print sorted print load_mauna_original range try_expanded_kernels pretty_print plot plot_kernel Carls_Mauna_kernel title linspace figure SqExpPeriodicKernel plot SqExpKernel plot_kernel title linspace figure loadmat loadmat sorted load_simple_gef_load print range try_expanded_kernels pretty_print sorted print range load_full_gef_load try_expanded_kernels pretty_print mkstemp close execute fear_connect close fear_connect close put get fear_connect close execute fear_connect close execute fear_connect close execute fear_connect close USERNAME fear_command join print write copy_to_fear close mkstemp_safe open print join fear_command copy_to_fear fear_file_exists copy_from_fear ravel log re_qsub fear_connect from_param_vector sleep append fear_qdel_all close enumerate var remove mkstemp_safe fear_rm print qsub_matlab_code savemat loadmat len loadmat print expand MultiDGrammar remove_duplicates pretty_print sorted fear_run_experiments print append range fear_expand_kernels fear_load_mat pretty_print show host_subplot plot get_color set_xlabel draw subplots_adjust set_ylabel twinx legend set_color fear_load_mat MaskKernel SqExpPeriodicKernel show posterior_mean host_subplot plot get_color SqExpKernel set_xlabel draw RQKernel subplots_adjust title set_ylabel twinx legend set_color fear_load_mat host_subplot show SqExpPeriodicKernel posterior_mean set_xlabel title twinx legend set_color plot SqExpKernel RQKernel get_color MaskKernel draw subplots_adjust set_ylabel figure fear_load_mat MaskKernel SqExpPeriodicKernel posterior_mean SqExpKernel reshape RQKernel repeat savemat linspace tile fear_load_mat MaskKernel SqExpPeriodicKernel sample_from_gp_prior plot SqExpKernel xlabel ylabel RQKernel title figure fear_load_mat fear_experiment from_matlab_output remove remove_temp_file print load_mat read_outputs create_temp_file family savemat repr_string_to_kernel copy_to_remote sub hessian call split remove print remove range len remove done all print len tick close isfile open sleep mkstemp_safe Progress enumerate poll open list map split data_file load_data ravel list map split append open astype eeg_data_file load_waveform_data concatenate astype eeg_data_file shape channel_locs_file times vstack load_waveform_data load_channel_locs zeros range dest_file join call temp_dir title plot load_data figure print close load_data open list arange readlines map len utcfromtimestamp int total_seconds strip open datafile append float array datetime split append ravel range MonthlyStationInfo AnnualStationInfo ravel range append dataflag height missing astype annual_matfile read_monthly_data zip append read_annual_data interpolated array monthly_matfile split float irradiance_data_file open join split communicate wait returncode add_wrapper Popen print gethostname close call _status_file open communicate join Popen join _status_path print SMTP close run_command call sendmail mkdir _status_file EMAIL quit open int int isint append range split readlines strip split mean sqrt zeros sum array range len normal find_duplicates compute_K qr evaluate_kernels restart_std remove_nan_scored_kernels proj_dim remove_duplicates open list base_kernels append range dump rel_cutoff num_subsample output_fname_fn print sort expand_kernels n_restarts add_random_restarts read_data get_X_y load_all_channels load_X_y load_one_channel loadmat perform_search TEMP_PATH load_data Scheduler default gpml_kernel_expression param_vector SqExpKernel load_mauna optimize_params run_matlab_code run_matlab_code loadmat remove repr_string_to_kernel pretty_print repr_string_to_kernel pretty_print Carls_Mauna_kernel expand_kernels base_kernels list expand_kernels strip_masks k_opt repr_string_to_kernel break_kernel_into_summands write flush str done Counter ProgressLine sleep Progress range tick execute close connect close connect put get close connect execute close connect execute close connect print join command execute close connect execute close USERNAME connect execute close USERNAME connect qstat_status qstat_status qstat_status qstat_status seed allclose append zip max any array where product tuple fn shape zeros max enumerate slice list enumerate len asarray ndim array isscalar append max range len pinv ndim array_map dtrtri dpotrf diag dtype int concatenate ANTIALIAS shape float array defaultdict append hasattr list sorted keys print T product full_shape shape dot zeros sum broadcast T product full_shape shape dot zeros broadcast eigh infty clip FullMatrix size from_moments_iso translate Potential zeros zeros size FullMatrix Potential T where dot eigh append sum log normal T dot uniform laplace_approx | This is part of the [automatic statistician](http://www.automaticstatistician.com/) project ======== Gaussian Process Structure Search =================== <img src="https://raw.githubusercontent.com/jamesrobertlloyd/gp-structure-search/master/logo.png" width="700"> Code for automatically searching through compositions of covariance functions for Gaussian process regression, described in [Structure Discovery in Nonparametric Regression through Compositional Kernel Search](http://arxiv.org/abs/1302.4922) by David Duvenaud, James Robert Lloyd, Roger Grosse, Joshua B. Tenenbaum, Zoubin Ghahramani ### Abstract: Despite its importance, choosing the structural form of the kernel in nonparametric regression remains a black art. We define a space of kernel structures which are built compositionally by adding and multiplying a small number of base kernels. We present a method for searching over this space of structures which mirrors the scientific discovery process. The learned structures can often decompose functions into interpretable components and enable long-range extrapolation on time-series datasets. Our structure search method outperforms many widely used kernels and kernel combination methods on a variety of prediction tasks. | 2,454 |
jamesrobertlloyd/gpss-research | ['gaussian processes', 'time series'] | ['Structure Discovery in Nonparametric Regression through Compositional Kernel Search', 'Automatic Construction and Natural-Language Description of Nonparametric Regression Models'] | experiments/2013-11-11-extrap-TCI.py experiments/2014-01-14-GPSS-full.py experiments/2013-08-20-time-series.py experiments/2013-08-30-armani.py experiments/2014-01-16-GPSS-full.py source/translation.py experiments/2013-09-30.py source/cblparallel/fear_put.py experiments/2013-08-20-bl.py experiments/2014-11-06-wells-all-ops.py experiments/2014-11-12-alexa-v1.py experiments/2014-06-28-prejudice.py experiments/2014-04-24-uci-regression-restart.py experiments/2014-03-21-interp-GPSS-orig.py source/datasets/sea_level.py source/cblparallel/counter.py source/datasets/airline.py experiments/2013-09-26.py experiments/2013-11-11-extrap-GPSS-old.py experiments/2013-09-03-time-series.py source/utils/profiler.py experiments/2014-04-14-class-pima.py data/scripts/make_interp_data.py experiments/2013-09-04-time-series-integrals.py experiments/2013-09-24-additive.py experiments/2013-08-16-IBM.py data/scripts/make_extrap_data.py experiments/2014-02-18-GPSS-add-pl2.py source/cblparallel/config_example.py experiments/2013-09-06.py source/config_example.py source/mitparallel/util.py experiments/debug/debug_bic.py source/utils/psd_matrices.py source/test_everything.py source/demo.py source/datasets/methane.py experiments/2013-09-28-solar-v2.py experiments/2013-09-05-time-series.py experiments/2013-08-29-time-series.py experiments/2013-12-17-interp-MKL.py experiments/2013-11-11-extrap-GPSS-nll.py experiments/2013-09-02-test1.py experiments/2013-09-30-solar-v2.py source/mit_experiments/base.py experiments/2014-02-19-GPSS-add-pl2.py experiments/2014-02-12-GPSS-add-KM-demo.py experiments/2013-12-17-interp-TCI.py experiments/2013-08-21-time-series.py source/cblparallel/__init__.py experiments/2013-08-15-time-series.py source/mitparallel/matlab.py source/testing/test_kernels.py experiments/debug/debug_changewindow.py experiments/debug/debug_bic_2.py experiments/2013-12-16-interp-GPSS-full.py experiments/2014-01-09-internet.py experiments/2013-08-27-time-series.py source/cblparallel/fear_get.py source/mitparallel/__init__.py experiments/2013-12-18-telescope-add.py experiments/2013-11-11-extrap-MKL.py experiments/2013-09-03-time-series-subset.py experiments/2014-01-28-extrap-LN.py experiments/2014-04-21-motorcycle.py source/cblparallel/util.py experiments/2013-10-01-pure-lin.py experiments/2013-10-17.py experiments/2013-10-08.py source/test_slow.py source/mitparallel/parallel.py experiments/2013-08-31-time-series.py experiments/2013-12-18-telescope.py experiments/2014-11-06-wells.py experiments/2013-11-14-extrap-GPSS-full.py source/cblparallel/pyfear.py experiments/2013-10-18.py experiments/2013-11-11-extrap-SP-nll.py experiments/debug/debug_all.py experiments/2013-12-10-extrap-GPSS.py source/datasets/solar.py experiments/2013-09-04-subset-integral.py experiments/2013-09-08.py experiments/2013-09-03-time-series-integrals.py experiments/2013-08-30-time-series.py experiments/2014-04-14-class-breast.py experiments/debug/debug_example.py experiments/2013-08-19-time-series.py experiments/2014-01-28-interp-LN.py experiments/2014-04-14-class-liver.py source/utils/counter.py experiments/2013-11-14-extrap-GPSS-full-no-RQ.py experiments/2013-09-28-solar.py experiments/2014-02-06-hadcrut4-median-add.py source/utils/misc.py experiments/2013-12-19-quebec-add.py experiments/2013-09-07.py experiments/2013-09-09.py experiments/2014-04-21-uci-regression.py source/datasets/ekg.py experiments/2014-04-16-class-liver-aic.py source/mit_job_controller.py experiments/2014-05-28-prejudice-simple.py experiments/2013-11-11-extrap-lin.py experiments/2014-01-16-GPSS-add.py experiments/2014-04-14-class-heart.py source/experiment.py source/utils/latex.py experiments/2014-04-14-debug-class.py source/job_controller.py experiments/debug/debug_changepoint.py experiments/2014-01-09-radio.py source/flexible_function.py source/testing/test_gpml.py experiments/2013-12-17-extrap-SP-bic.py experiments/2013-08-19-step-burst.py experiments/2013-11-11-extrap-FT.py experiments/2013-11-11-extrap-CP.py experiments/2013-09-02-time-series.py experiments/2013-12-10-interp-GPSS.py experiments/debug/debug_changewindow_2.py source/datasets/__init__.py experiments/2013-12-17-interp-SP-bic.py source/postprocessing.py source/datasets/eeg.py experiments/2014-01-28-interp-SE.py experiments/2014-01-28-extrap-SE.py experiments/2014-11-10-gefcom-revisited.py experiments/2014-03-19-extrap-GPSS-orig.py experiments/2013-12-16-extrap-GPSS-full.py source/gpml.py experiments/2013-08-21-test1.py experiments/2013-08-20-solar.py source/utils/fear.py source/grammar.py experiments/2013-08-16-CP.py experiments/2014-11-11-gefcom-revisited-hint.py experiments/debug/debug_pl2.py source/utils/gaussians.py experiments/2014-01-14-GPSS-add.py experiments/2013-09-04-time-series-subset.py experiments/2013-09-30-solar-v3.py experiments/2013-08-26-test1.py source/sandpit.py source/utils/mkl_hack.py experiments/2014-04-14-class-sonar.py experiments/2014-04-17-class-liver-brackets.py experiments/2013-09-01-time-series.py experiments/2013-09-27.py experiments/2014-01-15-GPSS-add.py experiments/2013-12-17-interp-CP.py experiments/2014-11-11-gefcom-revisited-v2.py experiments/2013-10-19.py experiments/2014-02-17-GPSS-add-pl2.py experiments/2013-08-28-time-series.py experiments/2013-12-17-interp-SP-nll.py experiments/2013-09-28.py experiments/2014-01-15-GPSS-full.py experiments/2013-11-08-extrap-GPSS.py experiments/2013-08-22-time-series.py experiments/2013-08-16-spectral.py experiments/debug/debug-bic-master.py source/mit_experiments/search_oneproc.py experiments/2013-09-30-solar-v1.py experiments/2013-09-25-noise.py experiments/synth/synth.py experiments/2013-08-21-test2.py parse_results run_debug_kfold gen_all_datasets experiment_fields_to_str Experiment run_experiment_file repeat_predictions perform_experiment perform_kernel_search remove_nan_scored_models add_random_restarts add_jitter_k PeriodicKernel add_random_restarts_single_l ZeroKernel SpectralKernel GPModel SumKernel base_kernels_without_dimension FunctionWrapper remove_duplicates Kernel add_jitter ChangePointKernel LikGauss PeriodicKernelOLD ProductKernel ChangeWindowKernel NoiseKernel base_kernels Likelihood MeanConst MeanFunction SqExpKernel LinearKernel add_random_restarts_single_k RQKernel MeanZero LinearKernelOLD LikErf add_random_restarts_single_m add_random_restarts_k ConstKernel repr_to_model NoneKernel OptimizerOutput read_outputs load_mat order_by_mae checking_stats standardise_and_save_data run_matlab_code component_stats expand_models expand_single_tree polish_to_kernel expand MultiDGrammar expand_kernels replace_all evaluate_models make_predictions compute_K_code make_predictions compute_K evaluate_kernel_code make_predictions_code evaluate_kernel compare_mse classification_accuracy gen_all_results make_all_1d_figures debug_descriptions fear_experiment load_mauna copy_to_fear fear_file_exists copy_from_fear sample_mauna_best debug_laplace call_gpml_test expand_test2 plot_gef_load_Z01 re_qsub fear_connect base_kernel_test full_gef_load_experiment fear_qdel_all plot_gef_load_Z01_raw plot_our_kernel fear_run_experiments load_mauna_original expand_test load_full_gef_load sample_Carls_kernel plot_gef_load_Z01_split_mean_temp main plot_Carls_kernel fear_expand_kernels kernel_test fear_command simple_gef_load_experiment simple_mauna_experiment load_simple_gef_load fear_rm qsub_matlab_code plot_gef_load_Z01_split_mean compare_kernels_experiment mkstemp_safe plot_gef_load_Z01_smooth_2d_mean fear_load_mat misc_testcase ff_testcase grammar_testcase experiment_testcase experiment_testcase main ProgressLine Progress Counter fear timeoutCommand mkstemp_safe string_is_int run_batch_locally remove_temp_file setup create_temp_file run_batch_on_fear start_port_forwarding copy_to_remote gpml_path load_X_y data_file load_data WaveformInfo eeg_data_file load_all_channels channel_locs_file load_one_channel load_waveform_data load_channel_locs datset_url save_data dest_file record_url plot_examples temp_dir get_X_y load_data read_data datafile MonthlyStationInfo annual_matfile get_X_y read_monthly_data AnnualStationInfo read_annual_data monthly_matfile get_X_y irradiance_data_file add_wrapper run isint _status_path run_command _status_file parse_machines _run_job list_jobs run mkstemp_safe create_temp_file find_duplicates perform_search load_data remove_nan_scored_kernels SearchParams remove_duplicates Scheduler run load_mauna not_tet_matlab_runs not_tet_num_params not_tet_matlab_stops test_kernel_eval test_change_kernel_eval test_kernel_expand_multi_d test_kernel_decompose_1d test_kernel_expand main ProgressLine Progress Counter file_exists qstat_status qdel qdel_all job_running connect command job_terminated copy_to copy_from job_loading job_queued rm qsub Conditionals Distribution Potential clean table summarize_error my_inv broadcast _err_string paren_colors transp match_shapes array_map colored process_slice min_abs_diff format_if_possible sample_truncated_normal set_all_random_seeds vdot extend_slice full_shape dot my_sum lstsq set_err_info summarize reset get_key profiled check_laplace_approx FullMatrix _x_QDQ_x proj_psd EigMatrix FixedEigMatrix laplace_approx_stable _QDQ_x BaseMatrix laplace_approx_no_prior laplace_approx laplace_approx_stable_no_prior DiagonalMatrix EyeMatrix parse_results run_debug_kfold gen_all_datasets experiment_fields_to_str Experiment run_experiment_file repeat_predictions perform_experiment perform_kernel_search remove_nan_scored_models add_random_restarts add_jitter_k PeriodicKernel add_random_restarts_single_l ZeroKernel SpectralKernel GPModel SumKernel base_kernels_without_dimension FunctionWrapper remove_duplicates Kernel add_jitter ChangePointKernel LikGauss PeriodicKernelOLD ProductKernel ChangeWindowKernel NoiseKernel base_kernels Likelihood MeanConst MeanFunction SqExpKernel LinearKernel add_random_restarts_single_k RQKernel MeanZero LinearKernelOLD LikErf add_random_restarts_single_m add_random_restarts_k ConstKernel repr_to_model NoneKernel OptimizerOutput read_outputs load_mat order_by_mae checking_stats standardise_and_save_data run_matlab_code component_stats expand_models expand_single_tree polish_to_kernel expand MultiDGrammar expand_kernels replace_all evaluate_models make_predictions compute_K_code compute_K evaluate_kernel_code make_predictions_code evaluate_kernel compare_mse classification_accuracy gen_all_results make_all_1d_figures debug_descriptions fear_experiment load_mauna copy_to_fear fear_file_exists copy_from_fear sample_mauna_best debug_laplace call_gpml_test expand_test2 plot_gef_load_Z01 re_qsub fear_connect base_kernel_test full_gef_load_experiment fear_qdel_all plot_gef_load_Z01_raw plot_our_kernel fear_run_experiments load_mauna_original expand_test load_full_gef_load sample_Carls_kernel plot_gef_load_Z01_split_mean_temp main plot_Carls_kernel fear_expand_kernels kernel_test fear_command simple_gef_load_experiment simple_mauna_experiment load_simple_gef_load fear_rm qsub_matlab_code plot_gef_load_Z01_split_mean compare_kernels_experiment mkstemp_safe plot_gef_load_Z01_smooth_2d_mean fear_load_mat misc_testcase ff_testcase grammar_testcase experiment_testcase main ProgressLine Progress Counter fear timeoutCommand mkstemp_safe string_is_int run_batch_locally remove_temp_file setup create_temp_file run_batch_on_fear start_port_forwarding copy_to_remote gpml_path load_X_y data_file load_data WaveformInfo eeg_data_file load_all_channels channel_locs_file load_one_channel load_waveform_data load_channel_locs datset_url save_data dest_file record_url plot_examples temp_dir get_X_y load_data read_data datafile MonthlyStationInfo annual_matfile get_X_y read_monthly_data AnnualStationInfo read_annual_data monthly_matfile irradiance_data_file add_wrapper run isint _status_path run_command _status_file parse_machines _run_job list_jobs mkstemp_safe create_temp_file find_duplicates perform_search load_data remove_nan_scored_kernels SearchParams remove_duplicates Scheduler run load_mauna not_tet_matlab_runs not_tet_num_params not_tet_matlab_stops test_kernel_eval test_change_kernel_eval test_kernel_expand_multi_d test_kernel_decompose_1d test_kernel_expand main ProgressLine Progress Counter file_exists qstat_status qdel qdel_all job_running connect command job_terminated copy_to copy_from job_loading job_queued rm qsub Conditionals Distribution Potential clean table summarize_error my_inv broadcast _err_string paren_colors transp match_shapes array_map colored process_slice min_abs_diff format_if_possible sample_truncated_normal set_all_random_seeds vdot extend_slice full_shape dot my_sum lstsq set_err_info summarize reset get_key profiled check_laplace_approx FullMatrix _x_QDQ_x proj_psd EigMatrix FixedEigMatrix laplace_approx_stable _QDQ_x BaseMatrix laplace_approx_no_prior laplace_approx laplace_approx_stable_no_prior DiagonalMatrix EyeMatrix expand_models n_rand score jitter_sd warn bic nll rename max remove_duplicates log sorted add_jitter add_jitter_to_models append pretty_print Inf range debug evaluate_models aic shuffle mean kernel eval additive_form random_seed set_all_random_seeds max_depth print min pl2 sd lik add_random_restarts std remove_nan_scored_models endswith sort splitext append walk split _fields zip join read list experiment_fields_to_str print gen_all_datasets data_dir system shuffle random_order eval results_dir perform_experiment makedirs join read list parse_results experiment_fields_to_str print gen_all_datasets data_dir load_mat make_predictions eval savemat isfile results_dir join parse_results print load_mat system make_predictions savemat results_dir perform_kernel_search run_experiment_file is_thunk range copy base_kernels_without_dimension append initialise_params range copy append initialise_params range copy append initialise_params range copy add_random_restarts_single_l add_random_restarts_single_k copy kernel likelihood mean add_random_restarts_single_m zip append normal param_vector load_param_vector read remove print close write mkstemp call open loadmat ravel mkstemp savemat join print close ravel dirname abspath standardise_and_save_data run_matlab_code loadmat join print close dirname abspath standardise_and_save_data run_matlab_code loadmat join print close dirname abspath standardise_and_save_data run_matlab_code loadmat loadmat Kernel isinstance list remove rules product type_matches dict polish_to_kernel zip append keys replace_all expand_single_tree product copy append operands enumerate MultiDGrammar remove_duplicates expand append nan copy expand_kernels OPTIMIZE_KERNEL_CODE run_batch_locally from_matlab_output remove remove_temp_file print read_outputs create_temp_file run_batch_on_fear savemat copy_to_remote sub enumerate len remove_temp_file print create_temp_file savemat copy_to_remote sub PREDICT_AND_SAVE_CODE loadmat join map param_vector var from_matlab_output remove read_outputs family create_temp_file savemat evaluate_kernel_code log run join map param_vector remove make_predictions_code run k_opt COMPUTE_K_CODE_HEADER join gpml_kernel_expression param_vector COMPUTE_K_CODE_FOOTER map enumerate remove compute_K_code create_temp_file savemat loadmat run join list T inf median gen_all_datasets ones print ravel mean sqrt set_printoptions isfile power loadmat enumerate join list sum gen_all_datasets print set_printoptions isfile loadmat enumerate endswith join sorted parse_results gen_all_datasets produce_summary_document break_into_summands translate_additive_component order_by_mae list load_mat append operands pretty_print update canonical zip component_stats join print sub checking_stats isfile ravel makedirs MaskKernel gpml_kernel_expression param_vector print SqExpKernel pretty_print print SqExpPeriodicKernel SqExpKernel print OneDGrammar expand SumKernel remove_duplicates pretty_print MaskKernel SqExpPeriodicKernel SqExpKernel print expand MultiDGrammar SumKernel remove_duplicates pretty_print loadmat loadmat seed normal gpml_kernel_expression from_param_vector list sorted param_vector print load_mauna size draw semilogx SumKernel figure append optimize_params range pretty_print SqExpPeriodicKernel sample_from_gp_prior plot SqExpKernel title linspace figure sample_from_gp_prior plot Carls_Mauna_kernel title linspace figure SqExpPeriodicKernel gpml_kernel_expression from_param_vector param_vector SqExpKernel print load_mauna_original Carls_Mauna_kernel optimize_params pretty_print sorted print load_mauna_original range try_expanded_kernels pretty_print plot plot_kernel Carls_Mauna_kernel title linspace figure SqExpPeriodicKernel plot SqExpKernel plot_kernel title linspace figure loadmat loadmat sorted load_simple_gef_load print range try_expanded_kernels pretty_print sorted print range load_full_gef_load try_expanded_kernels pretty_print mkstemp close execute fear_connect close fear_connect close put get fear_connect close execute fear_connect close execute fear_connect close execute fear_connect close USERNAME fear_command join print write copy_to_fear close mkstemp_safe open print join fear_command copy_to_fear fear_file_exists copy_from_fear ravel log re_qsub fear_connect from_param_vector sleep append fear_qdel_all close enumerate var remove mkstemp_safe fear_rm print qsub_matlab_code savemat loadmat len loadmat print expand MultiDGrammar remove_duplicates pretty_print sorted fear_run_experiments print append range fear_expand_kernels fear_load_mat pretty_print show host_subplot plot get_color set_xlabel draw subplots_adjust set_ylabel twinx legend set_color fear_load_mat MaskKernel SqExpPeriodicKernel show posterior_mean host_subplot plot get_color SqExpKernel set_xlabel draw RQKernel subplots_adjust title set_ylabel twinx legend set_color fear_load_mat host_subplot show SqExpPeriodicKernel posterior_mean set_xlabel title twinx legend set_color plot SqExpKernel RQKernel get_color MaskKernel draw subplots_adjust set_ylabel figure fear_load_mat MaskKernel SqExpPeriodicKernel posterior_mean SqExpKernel reshape RQKernel repeat savemat linspace tile fear_load_mat MaskKernel SqExpPeriodicKernel sample_from_gp_prior plot SqExpKernel xlabel ylabel RQKernel title figure fear_load_mat fear_experiment from_matlab_output remove remove_temp_file print load_mat read_outputs create_temp_file family savemat repr_string_to_kernel copy_to_remote sub hessian print Carls_Mauna_kernel english write flush str done Counter ProgressLine sleep Progress range tick int call split remove print remove range len remove done all print len tick close isfile open sleep mkstemp_safe Progress enumerate Popen poll open list map split data_file load_data ravel list map split append open astype eeg_data_file load_waveform_data concatenate astype eeg_data_file shape channel_locs_file times vstack load_waveform_data load_channel_locs zeros range dest_file join call temp_dir title plot load_data figure print close load_data open list arange readlines map len utcfromtimestamp int total_seconds strip open datafile append float array datetime split append ravel range MonthlyStationInfo AnnualStationInfo ravel range append dataflag height missing astype annual_matfile read_monthly_data zip append read_annual_data interpolated array monthly_matfile split float irradiance_data_file open join split communicate wait returncode add_wrapper Popen print gethostname close call _status_file open communicate join Popen join _status_path print SMTP close run_command call sendmail mkdir _status_file EMAIL quit open int int isint append range split readlines strip split mean sqrt zeros sum array range len normal sorted find_duplicates compute_K qr evaluate_kernels restart_std remove_nan_scored_kernels proj_dim remove_duplicates open list base_kernels append range dump rel_cutoff num_subsample output_fname_fn print sort expand_kernels n_restarts add_random_restarts read_data get_X_y load_all_channels load_X_y load_one_channel loadmat perform_search TEMP_PATH load_data Scheduler default gpml_kernel_expression param_vector SqExpKernel load_mauna optimize_params run_matlab_code run_matlab_code loadmat remove repr_string_to_kernel pretty_print repr_string_to_kernel pretty_print Carls_Mauna_kernel expand_kernels base_kernels list expand_kernels strip_masks k_opt repr_string_to_kernel break_kernel_into_summands execute close connect close connect put get close connect execute close connect execute close connect print join command execute close connect execute close USERNAME connect execute close USERNAME connect qstat_status qstat_status qstat_status qstat_status seed allclose append zip max any array where product tuple fn shape zeros max enumerate slice list enumerate len asarray ndim array isscalar append max range len pinv ndim array_map dtrtri dpotrf diag paren_colors defaultdict append hasattr list sorted keys print T product full_shape shape dot zeros sum broadcast T product full_shape shape dot zeros broadcast eigh infty clip FullMatrix size from_moments_iso translate Potential zeros zeros size FullMatrix Potential T where dot eigh append sum log pi where eigh nan append sum log normal T dot uniform laplace_approx | This is part of the [automatic statistician](http://www.automaticstatistician.com/) project ======== Automatic Bayesian Covariance Discovery ===================== <img src="https://raw.githubusercontent.com/jamesrobertlloyd/gpss-research/master/logo.png" width="700"> This repo contains the source code to run the system described in the paper [Automatic Construction and Natural-Language Description of Nonparametric Regression Models](http://arxiv.org/pdf/1402.4304.pdf) by James Robert Lloyd, David Duvenaud, Roger Grosse, Joshua B. Tenenbaum and Zoubin Ghahramani, appearing in [AAAI 2014](http://www.aaai.org/Conferences/AAAI/aaai14.php). ### Abstract | 2,455 |
jamie-murdoch/ContextualDecomposition | ['sentiment analysis'] | ['Beyond Word Importance: Contextual Decomposition to Extract Interactions from LSTMs'] | train_model/sent_util.py train_model/model.py train_model/train.py LSTMSentiment get_batches decomp_tanh_two get_args get_sst CD evaluate_predictions get_model decomp_three makedirs print load splits build_vocab Field print init_epoch seed enumerate load init_epoch splits model print Field label enumerate build_vocab data tanh decomp_tanh_two state_dict size dot sigmoid hidden_dim zeros numpy decomp_three range split activation parse_args add_argument ArgumentParser | # Contextual decomposition Demonstration of the methods introduced in "Beyond Word Importance: Contextual Decomposition to Extract Interactions from LSTMs" ([ICLR 2018 Oral](https://arxiv.org/abs/1801.05453))  # Follow-up work This repo is no longer actively maintained, but some of these related works are actively maintaining / extending the ideas here. - ACD (ICLR 2019 [pdf](https://openreview.net/pdf?id=SkEqro0ctQ), [github](https://github.com/csinva/hierarchical-dnn-interpretations)) - extends CD to CNNs / arbitrary DNNs, and aggregates explanations into a hierarchy - CDEP (ICML 2020 [pdf](https://arxiv.org/abs/1909.13584), [github](https://github.com/laura-rieger/deep-explanation-penalization)) - penalizes CD / ACD scores during training to make models generalize better - TRIM (ICLR 2020 workshop [pdf](https://arxiv.org/abs/2003.01926), [github](https://github.com/csinva/transformation-importance)) - using simple reparameterizations, allows for calculating disentangled importances to transformations of the input (e.g. assigning importances to different frequencies) - DAC (arXiv 2019 [pdf](https://arxiv.org/abs/1905.07631), [github](https://github.com/csinva/disentangled-attribution-curves)) - finds disentangled interpretations for random forests - PDR framework (PNAS 2019 [pdf](https://arxiv.org/abs/1901.04592)) - an overarching framewwork for guiding and framing interpretable machine learning | 2,456 |
jan-dufek/emily-tracker | ['visual localization'] | ['Visual Servoing of Unmanned Surface Vehicle from Small Tethered Unmanned Aerial Vehicle'] | visual_navigation.py close_socket close | # Visual Navigation of Unmanned Surface Vehicle from Unmanned Aerial Vehicle to Safe Drowning Victims This project uses the video from a small unmanned aerial system (UAS) to navigate an unmanned surface vehicle (USV) covered in a flotation jacket to reach drowning victims. The teleoperated [EMILY](https://www.emilyrobot.com/) USV has been used by the Hellenic Coast Guard since January of 2016 to allow lifeguards to rapidly deploy flotation to refugees attempting to cross the Mediterranean Sea. While EMILY has been credited with the successful rescue of at least one boat load of refugees, there are three problems. First, teleoperation takes lifeguard time and energy that would be better spent on directly rescuing high risk victims. Second, the lifeguards have trouble teleoperating the USV because their viewing angle of the USV heading away from them is unfavorable; as a result the USV often fish-tails and takes a sub-optimal path. Third, the lifeguards quickly lose depth perception and may accidentally hit the victim with the USV. This project addresses these deficiencies by using the output from a small UAS to direct the USV. The implementation relies on a robust vision-based algorithm for position and orientation estimation of the USV based on the CamShift algorithm. The CamShift algorithm is applied to the USV’s histogram backprojection to estimate the position and projection of the USV’s trajectory filtered by Douglas-Peucker algorithm to estimate the orientation. Rudder and throttle control signals for the USV to reach the target selected in the video are computed using the line-of-sight and PID control. Current work is enabling the operator to select victims in the video feed provided by a tethered UAS called a [Fotokite Pro](https://fotokite.com/fotokite-pro/) and the system then navigates the USV to the victims autonomously. The Fotokite can operate from a shore or from a boat without the need to worry about the control. The UAS controlling the USV was tested with several first responder agencies such as United States Cost Guard, Italian Cost Guard, Los Angeles County Fire Department Lifeguards, and Department of Homeland Security during several exercises. A tracking error, progression of error angle to the target, distance to the target, and cross track error were measured. The mean tracking error was 0.3 %. The mean cross track error for the latest version was 1 m. The experimental results indicated feasibility of the system. The results are expected to be made available to lifeguards in Greece and the Frontex agencies assisting with the rescues. ## Publications Details about the project can be found in the following publications: [Visual pose estimation of USV from UAV to assist drowning victims recovery](http://ieeexplore.ieee.org/document/7784291/) (IEEE SSRR 2016) [Visual navigation of USV from UAS to save drowning victims](http://www.dufek.me/research/publications/VisualNavigationOfUSVFromUASToSaveDrowningVictims.pdf) (AUVSI XPONENTIAL 2017) [UAV assisted USV visual navigation for marine mass casualty incident response](http://ieeexplore.ieee.org/document/8206510/) (IEEE/RSJ IROS 2017) [Visual servoing of unmanned surface vehicle from small tethered unmanned aerial vehicle](https://arxiv.org/abs/1710.02932) (ArXiv) [Visual pose stabilization of tethered small unmanned aerial system to assist drowning victim recovery](http://ieeexplore.ieee.org/document/8088149/) (IEEE SSRR 2017) | 2,457 |
janelia-flyem/DVIDSparkServices | ['electron microscopy image segmentation', 'semantic segmentation'] | ['Large-Scale Electron Microscopy Image Segmentation in Spark'] | DVIDSparkServices/workflows/IngestGrayscale.py DVIDSparkServices/io_util/brainmaps.py integration_tests/test_seg_multicut/checkoutput.py DVIDSparkServices/workflows/GrayscaleBenchmark.py DVIDSparkServices/reconutils/morpho.py DVIDSparkServices/workflows/SamplePoints.py DVIDSparkServices/dvid/convert_stats.py DVIDSparkServices/reconutils/plugins/ilastik_multicut.py DVIDSparkServices/sparkdvid/CompressedNumpyArray.py unit_tests/test_morpho.py DVIDSparkServices/reconutils/plugins/NeuroProofAgglom.py integration_tests/test_meshes_subset/checkoutput.py DVIDSparkServices/dvid/ingest_label_indexes.py DVIDSparkServices/reconutils/metrics/overlap.py DVIDSparkServices/io_util/volume_service/generic_schemas/geometry.py DVIDSparkServices/io_util/labelmap_utils.py DVIDSparkServices/sparkdvid/Subvolume.py DVIDSparkServices/sparkdvid/sparkdvid.py DVIDSparkServices/workflows/DVIDCheckSegmentation.py unit_tests/test_scaled_volume_service.py unit_tests/reconutils/unit_tests/test_downsample.py DVIDSparkServices/spark_launch_scripts/janelia_lsf/lsf_utils.py DVIDSparkServices/workflows/CreateMeshes.py DVIDSparkServices/reconutils/misc.py DVIDSparkServices/workflows/IngestLabelIndices.py DVIDSparkServices/reconutils/metrics/plugins/orphans_stat.py unit_tests/test_subprocess_decorator.py integration_tests/test_seg_replace/checkoutput.py DVIDSparkServices/workflow/workflow.py DVIDSparkServices/io_util/volume_service/transposed_volume_service.py DVIDSparkServices/workflows/Ingest3DVolume.py DVIDSparkServices/io_util/partitionSchema.py scripts/init-bucket.py DVIDSparkServices/workflows/EvaluateSeg.py unit_tests/test_misc.py DVIDSparkServices/reconutils/metrics/plugins/vi_stat.py DVIDSparkServices/skeletonize_array.py unit_tests/reconutils/test_morpho.py DVIDSparkServices/workflows/CreatePyramid.py setup.py unit_tests/io_util/test_partitionSchema.py DVIDSparkServices/util.py unit_tests/io_util/test_imagefileSrc.py integration_tests/test_seg_simple_predict/checkoutput.py DVIDSparkServices/workflows/ExportSlices.py DVIDSparkServices/reconutils/metrics/plugins/count_stat.py DVIDSparkServices/workflows/ComputeGraph.py DVIDSparkServices/spark_launch_scripts/janelia_lsf/sparklaunch_janelia_lsf_int.py DVIDSparkServices/reconutils/metrics/Evaluate.py DVIDSparkServices/workflows/ConnectedComponents.py DVIDSparkServices/json_util.py DVIDSparkServices/reconutils/plugins/two_stage_voxel_predictions.py DVIDSparkServices/graph_comparison.py DVIDSparkServices/io_util/volume_service/labelmapped_volume_service.py DVIDSparkServices/reconutils/metrics/comptype.py DVIDSparkServices/sparkdvid/CompressedSerializerLZ4.py DVIDSparkServices/spark_launch_scripts/janelia_lsf/sparklaunch_janelia_lsf.py DVIDSparkServices/reconutils/downsample.py DVIDSparkServices/__init__.py DVIDSparkServices/workflow/logger.py unit_tests/test_util.py DVIDSparkServices/segstats.py unit_tests/test_sparkdvid_utils.py integration_tests/test_convertgray/checkoutput.py DVIDSparkServices/io_util/volume_service/scaled_volume_service.py DVIDSparkServices/reconutils/plugins/__init__.py DVIDSparkServices/reconutils/metrics/plugins/rand_stat.py integration_tests/launch_tests.py unit_tests/test_n5_volume_service.py DVIDSparkServices/reconutils/Segmentor.py DVIDSparkServices/subprocess_decorator.py integration_tests/test_seg_wsdt/checkoutput.py DVIDSparkServices/reconutils/SimpleGraph.py scripts/copy-meshes.py integration_tests/test_exportslices_from_n5/checkoutput.py DVIDSparkServices/io_util/volume_service/n5_volume_service.py scripts/create_body_tarball_from_sv_tarball.py unit_tests/test_slice_files_volume_service.py DVIDSparkServices/workflows/CreateTiles2.py DVIDSparkServices/rddtools.py DVIDSparkServices/workflows/CreateStitchedMeshes.py DVIDSparkServices/io_util/dvidSrc.py DVIDSparkServices/workflow/dvidworkflow.py DVIDSparkServices/reconutils/plugins/ilastik_predict_with_array.py DVIDSparkServices/workflows/CopySegmentation.py DVIDSparkServices/reconutils/metrics/plugins/connectivity_stat.py DVIDSparkServices/reconutils/plugins/create_supervoxels_with_wsdt.py unit_tests/test_transposed_volume_service.py DVIDSparkServices/io_util/brick.py integration_tests/test_seg_ilastik_two_stage/checkoutput.py DVIDSparkServices/io_util/volume_service/volume_service.py DVIDSparkServices/reconutils/plugins/precomputedpipeline.py DVIDSparkServices/workflows/CreateSegmentation.py DVIDSparkServices/workflows/ComputeEdgeProbs.py DVIDSparkServices/reconutils/metrics/segstats.py DVIDSparkServices/io_util/volumeSrc.py integration_tests/test_ingest/checkoutput.py integration_tests/test_copyseg_remapped/checkoutput.py DVIDSparkServices/io_util/imagefileSrc.py DVIDSparkServices/workflows/CreateSkeletons.py DVIDSparkServices/reconutils/metrics/plugins/autapse_stat.py unit_tests/io_util/test_brick.py DVIDSparkServices/io_util/volume_service/brainmaps_volume_service.py DVIDSparkServices/workflow/launchworkflow.py DVIDSparkServices/reconutils/metrics/plugins/stat.py DVIDSparkServices/reconutils/metrics/tests/test_connectivity.py integration_tests/test_seg_with_roi/checkoutput.py integration_tests/test_seg_ilastik/checkoutput.py DVIDSparkServices/io_util/volume_service/generic_schemas/volumes.py DVIDSparkServices/io_util/brickwall.py DVIDSparkServices/reconutils/plugins/IlastikSegmentor.py DVIDSparkServices/workflows/ConvertGrayscaleVolume.py DVIDSparkServices/reconutils/__init__.py unit_tests/test_auto_retry.py integration_tests/test_copyseg/checkoutput.py DVIDSparkServices/io_util/volume_service/dvid_volume_service.py DVIDSparkServices/workflows/CreateTiles.py integration_tests/test_samplepoints/checkoutput.py unit_tests/io_util/test_dvidSrc.py DVIDSparkServices/auto_retry.py DVIDSparkServices/io_util/volume_service/slice_files_volume_service.py unit_tests/dvid/test_metadata.py DVIDSparkServices/dvid/labelops_pb2.py DVIDSparkServices/reconutils/plugins/DefaultGrayOnly.py DVIDSparkServices/io_util/volume_service/__init__.py DVIDSparkServices/dvid/metadata.py DVIDSparkServices/reconutils/metrics/synoverlap.py unit_tests/test_compressed_numpy_array.py DVIDSparkServices/reconutils/plugins/ilastik_simple_predict.py integration_tests/test_exportslices/checkoutput.py DVIDSparkServices/reconutils/metrics/plugins/edit_stat.py scripts/nglink-pretty.py auto_retry extract_edges compute_split_merge_stats load_and_normalize_merge_table load_supervoxel_sizes compute_comparison_mapping_table compute_component_table frequencies_by_size_thresholds validate extend_with_default json_dumps inject_defaults NumpyConvertingEncoder ExtendedEncoder validate_and_inject_defaults json_dump extend_with_default_without_validation flow_style Dict foreach better_hash flat_map map zip_with_index map_partitions filter persist_and_execute unpersist partition_by group_by_key get_num_partitions tuple_with_hash map_values frugal_group_by_key values aggregate_segment_stats_from_bricks stats_df_from_brick merge_stats_dfs stats_df_from_rows aggregate_segment_stats_from_rows _concatenate_coordinate_lists write_stats copy_ndarray_to_zstack skeletonize_array view_zstack_as_ndarray ZStackKind make_skeletonizer _test_helper stdout_redirected _ChildStreamLoggingThread _subproc_inner_wrapper _ForkedProcessLogHandler fileno execute_in_subprocess _ChildLogEchoThread SysExcInfo flush get_localhost_ip_address _TimerResult dense_roi_mask_for_subvolume persist_and_execute RoiMap Timer runlength_encode nonconsecutive_bincount join_many _is_still_running_after_delay kill_if_running block_mask_to_px_mask cpus_per_worker runlength_decode_from_ranges _try_kill box_intersection select_item choose_pyramid_depth num_worker_nodes reverse_dict mask_roi is_process_running mkdir_p unicode_to_str replace_default_entries _runlength_encode zip_many default_dvid_session bb_as_tuple bb_to_slicing unpersist line_number MemoryWatcher coordlist_to_boolmap blockwise_boxes _install_thread_excepthook connect_debugger setup_faulthandler cleanup_faulthandler _log_exception pause_faulthandler initialize_excepthook export_body_stats _export_csv main export_supervoxel_stats _convert_coords_to_block_indexes _encode_block_id process_batch _overwrite_body_id_column _check_instance group_sums_presorted main_impl load_stats_h5_to_records LoggedProgressIndicator generate_stats_batches sort_block_stats main ingest_mapping StatsBatchProcessor ingest_label_indexes set_sync create_rawarray8 DataInstance create_keyvalue_instance reload_server_metadata Compression is_datainstance is_node_locked update_extents is_dvidversion extend_list_value has_sync get_blocksize create_label_instance fetch_subvol_data BrainMapsVolume NumpyConvertingEncoder fetch_json generate_bricks_from_volume_source Brick realign_bricks_to_new_grid clip_to_logical pad_brick_data_from_volume_source assemble_brick_fragments apply_label_mapping split_brick apply_labelmap_to_bricks BrickWall dvidSrc imagefileSrc mapping_from_edges mapping_from_groups find_leaf_nodes_for_group erode_leaf_nodes groups_from_edges segment_to_body_mapping_from_edge_csv edges_for_group _mapping_from_edges_gt _mapping_from_edges_nx compare_mappings equivalence_mapping_to_csv find_all_leaf_nodes load_labelmap volumePartition partitionSchema volumeSrc BrainMapsVolumeServiceReader DvidVolumeService LabelmappedVolumeService N5VolumeServiceReader ScaledVolumeService SliceFilesVolumeServiceWriter determine_stack_attributes SliceFilesVolumeServiceReader split_slice_fmt TransposedVolumeService VolumeServiceReader VolumeServiceWriter VolumeService downsample_box flat_mode downsample_raw flat_binary_mode flat_mode_except_zero _flat_mode make_blockwise_reducer_3d downsample_3Dlabels seeded_watershed vigra_bincount compute_vi normalize_channels_in_place noop_agglomeration naive_membrane_predictions select_channels find_large_empty_regions contingency_table seeded_watershed stitch object_masks_for_labels assemble_masks split_disconnected_bodies Segmentor SimpleGraph ComparisonType Evaluate OverlapTable SubvolumeStats SynOverlapTable autapse_stat connectivity_stat count_stat edit_stat orphans_stat rand_stat StatType vi_stat Testconnectivity create_supervoxels_with_wsdt DefaultGrayOnly ilastik_multicut ilastik_predict_with_array ilastik_simple_predict _prepare_lazyflow_config _init_logging neuroproof_agglomerate precomputedpipeline two_stage_voxel_predictions run_ilastik_stage reduce_ndarray_compressed CompressedNumpyArray deserialize_uint64_blocks reconstruct_ndarray_from_compressed serialize_uint64_blocks activate_compressed_numpy_pickling CompressedSerializerLZ4 sparkdvid retrieve_node_service Subvolume Bjob get_hostgraph_url get_job_hostname wait_for_job_start parse_bsub_output nice_check_call get_job_submit_time nice_call kill_job setup_environment launch_driver_job main launch_spark_cluster main send_exit_email DVIDWorkflow main WorkflowLogger Workflow WorkflowError ComputeEdgeProbs ComputeGraph ConnectedComponents ConvertGrayscaleVolume write_brick CopySegmentation block_stats_from_brick CreateMeshes compute_segment_masks _get_mesh_name post_meshes_to_dvid generate_mesh convert_dtype_inplace combine_masks fillna_inplace _get_group_name CreatePyramid CreateSegmentation skeletonize_in_subprocess _get_mesh_name CreateSkeletons is_combined_object_large_enough generate_mesh post_meshes_to_dvid combine_masks skeletonize body_masks post_swcs_to_dvid combine_masks_in_subprocess _get_group_name generate_mesh_in_subprocess CreateStitchedMeshes _get_group_name _get_mesh_name post_meshes_to_dvid CreateTiles CreateTiles2 DVIDCheckSegmentation EvaluateSeg ExportSlices compute_stats GrayscaleBenchmark Ingest3DVolume Ingest3DVolumeDirect IngestGrayscale IngestLabelIndices SamplePoints init_test_files init_dvid_database run_test run_tests get_output_vol find_diff_files copy_meshes copy_key read_body_ids main copy_tarballs_for_body main create_body_tarball_from_sv_tarball main get_toml_text pseudo_json_to_data main replace_commas TestAutoRetry TestCompressedNumpyArray test_normalize_channels_in_place test_select_channels test_find_large_empty_regions TestMemoryUsage _load_grayscale Test_assemble_masks TestSplitDisconnectedBodies Test_object_masks_for_labels TestContingencyTable TestN5VolumeService TestScaledVolumeService TestSliceFilesVolumeServiceWriter TestSliceFilesVolumeServiceReader Test_get_union_block_mask_for_bodies MessageCollector TestSubprocessDecorator generate_segfault c_sleep TestTransposedVolumeService test_runlength_encode test_blockwise_boxes test_unicode_to_str test_nonconsecutive_bincount test_empty_runlength_encode Testmetadata TestBrickFunctionsWithHalo TestBrickFunctions TestdvidSrc writeImages TestimagefileSrc TestPartitionSchema TestVolumePartition TestSplitDisconnectedBodies Testdownsample TestRecuderFunctions load copy view sort_index info uint64 DataFrame astype agg agg query load dump seek StringIO extend_with_default check_schema validator_for validate validate check_schema validator_for dict CommentedMap extend_with_default_without_validation isinstance isinstance isinstance isinstance isinstance isinstance isinstance append defaultdict isinstance isinstance isinstance isinstance isinstance builtin_map reduce isinstance info is_cached isinstance chain list lexsort array agg concat arange value_counts volume logical_box drop DataFrame values downsample_binary_3d_suppress_zero list transpose apply shape int64 append box_intersection physical_box asarray astype set nonzero zip float32 LabelMapper taggedView extractRegionFeatures zeros array len list DataFrame zip sum getLogger update int itemsize reshape as_array cast array8 prod shape view_zstack_as_ndarray ZStack ZStackSkeletonizer setLengthThreshold setDistanceThreshold setRebase copy validate_and_inject_defaults setMinObjSize setDownsampleInterval setKeepingSingleObject uint8 copy_ndarray_to_zstack view makeSkeleton _print make_skeletonizer clear getLogger addHandler _ForkedProcessLogHandler wait close send flush stdout fileno fflush print sleep ident getpid int max MEMORY_ONLY socket close connect AF_INET SOCK_DGRAM timedelta time _TimerResult info deepcopy list items isinstance tolist ndarray isinstance minimum maximum empty_like asarray ndarray isinstance tolist where array enumerate makedirs join cmdline format warn info _try_kill Process kill pid children append is_process_running sleep Process kill pid waitpid max list asarray min zeros array shape array zeros view_as_blocks roi_blocksize intersecting_blocks border block_mask_to_px_mask coordlist_to_boolmap array lexsort asarray reshape range len reshape range len minimum ndindex asarray maximum int asarray log2 ceil float max dense_roi_mask_for_subvolume value_counts list keys values map zip join map get stdin enable Popen makedirs enable disable stdin enable wait close write unlink disable exists _install_thread_excepthook print_exception format name error getvalue StringIO run list print filter settrace append exists view load_stats_h5_to_records _export_csv _overwrite_body_id_column load_stats_h5_to_records load_edge_csv _export_csv DataFrame unlink exists delimiter add_argument output_csv agglomeration_mapping export_body_stats stats_h5 ArgumentParser parse_args export_supervoxel_stats info setLevel INFO info load_stats_h5_to_records agglomeration_mapping abspath sort_block_stats supervoxel_block_stats_h5 split DataInstance tqdm LoggedProgressIndicator sort_values Session len _check_instance tqdm LoggedProgressIndicator generate_stats_batches info StatsBatchProcessor Pool len DataInstance blockshape_zyx view min apply LabelMapper range values len uint64 print zeros count_groups DVIDNodeService str DVIDNodeService str get_typeinfo get default_dvid_session raise_for_status get join raise_for_status post join value format POST DVIDConnection info encode make_request value format POST DVIDConnection info encode make_request post default_dvid_session format raise_for_status get minimum format json debug default_dvid_session dumps copy maximum post raise_for_status any info array get list format json debug default_dvid_session set post raise_for_status DVIDNodeService str get_typeinfo DVIDNodeService str POST custom_request encode DVIDNodeService str get_typeinfo request dumps request boxes_from_grid partitionBy max values list map clipped_boxes_from_grid cpus_per_worker ceil sum asarray num_worker_nodes info zip parallelize enumerate int filter len physical_box box_intersection logical_box physical_box all offset volume_accessor_func volume ndim copy block_shape overwrite_subvol append zeros array range apply_label_mapping unpersist load_labelmap map_partitions persist_and_execute partial flat_map filter group_by_key map_values extract_subvol physical_box Brick compress tuple volume block_shape boxes_from_grid set_hash hash box_as_tuple append tuple_with_hash box_intersection dtype list asarray physical_box Brick compress volume box_intersection overwrite_subvol any zeros array destroy join info check_call normpath startswith split add_edges_from connected_components sorted list Graph mapping_from_edges equivalence_mapping_to_csv load_edge_csv _mapping_from_edges_gt _mapping_from_edges_nx sort_values sort_index Graph Series min label_components add_edge_list DataFrame merge add_edges_from connected_components Graph reshape Series min unique list reshape map sum values DataFrame copy set index query unique agg sort_values eval DataFrame range find_all_leaf_nodes add_edges_from Graph query node_connected_component DataFrame edges_for_group value_counts int sorted format all glob convert shape split_slice_fmt array match groups append range zoom dtype list items astype shape append range zeros_like reshape reshape ones sort argmax diff ndindex shape vigra_bincount all logical_not shape zeros labelVolumeWithBackground getLogger min astype float32 info max view reshape astype float32 uint32 uint8 vigra_bincount getLogger astype logical_not taggedView watershedsNew info bool labelVolumeWithBackground info getLogger calculate_vi Stack float64 astype OverlapTable append find_overlaps sum sorted ndarray issubdtype integer type enumerate sum where dtype uint64 contingency_table arange duplicated view sum apply_inplace tolist astype copy LabelMapper dict label sort_values max values agg DataFrame reset_index bincount ravel watershed view CompressedNumpyArray astype float32 empty_like taggedView extractRegionFeatures relabelConsecutive array range append max int asarray downsample_box min power array downsample_func zip zeros prod select_item uint64 list collect groupByKey flatMap extend set add zip reduceByKey keys values broadcast dedent wsDtSegmentation getLogger astype logical_not info bool str dtype format print run_export node cpu_count process_name parse_known_args shape total taggedView OrderedDict splitext uuid1 main cpu_count normalize_channels_in_place str dtype run_export node parse_known_args shape OrderedDict uuid1 format value splitext info main isinstance print process_name getLane taggedView total stop select_channels str dtype format reset_thread_pool print load_and_predict node taggedView shape _prepare_lazyflow_config _init_logging normalize_channels_in_place splitext uuid1 select_channels int getLogger BOTH init get str dtype format remove print endswith name astype float32 NamedTemporaryFile shape agglomerate rename uint32 retrieve_node_service split str dtype format print mkdtemp shape normalize_channels_in_place run_ilastik_stage info str value isinstance run_export node cpu_count process_name getLane parse_known_args total taggedView OrderedDict splitext uuid1 main setValue ndarray pickle __subclasses__ compress view_as_blocks copy shape ndindex any append zeros encode_label_block array decompress asarray view_as_blocks any ndindex empty array decode_label_block enumerate str dtype format hasattr __dict__ getLogger debug shape type str dtype format view getLogger debug shape deserialize DVIDNodeService str get nice_call int get_job_submit_time timestamp match format decode strip decode strptime get_job_hostname sleep nice_check_call str executable abspath submit Bjob get_hostgraph_url print cpus_per_worker print Bjob format submit setup_environment format job_log_dir num_spark_workers now config_file launch_spark_cluster job_name launch_driver_job driver_slots workflow_name driver_node_type driver_queue max_hours communicate config_or_callback_address abspath Popen exit post dirname iter StringIO readline startswith flush time __file__ write dumps kill_master_on_exit gethostname getuser SMTP sendmail MIMEText as_string quit list_workflows workflow run list basename map dump_schema schema getattr dump_default_yaml glob import_module dump_default_json print workflow_cls dump_default_verbose_yaml default_config update deepcopy lower OptionsSchema max asarray volume view_as_blocks write_subvolume shape array block_width update deepcopy OptionsSchema physical_box value_counts append concat astype boxes_from_grid int32 Grid uint32 DataFrame box_intersection values update deepcopy OptionsSchema copy list asarray assemble_masks zip mesh_from_array ResourceManagerClient BytesIO default_dvid_session write_mesh getbuffer _get_group_name write_tar int str int str columns fillna columns astype setdefault update OptionsSchema copy update deepcopy OptionsSchema copy list zip WARN setLevel func getLogger WARN setLevel func getLogger deepcopy join format json_dumps now encode default_dvid_session ResourceManagerClient write_swc WARN setLevel func getLogger update deepcopy OptionsSchema copy str append update deepcopy lower OptionsSchema update OptionsSchema copy sum prod update OptionsSchema copy update OptionsSchema copy join time basename format replace decode print glob makedirs print File copy taggedView create_dataset writeImage enumerate makedirs decode create_grayscale8 check_call loads create_roi put_gray3D str transpose exit append DVIDNodeService gaussianSmoothing nonzero post_roi print write system zeros array split items list format print OrderedDict run_test DVIDNodeService str get_labels3D list exit values from_uuid tarball_type addHandler copy_meshes from_instance body_list_csv to_server StreamHandler read_body_ids parallelism stdout from_server to_uuid to_instance InstanceInfo error_mode get list tqdm zip Pool enumerate copy_key get post raise_for_status create_body_tarball_from_sv_tarball tqdm body_ids serialize str chdir fetch_key check_call info from_directory makedirs repo_description sleep bucket_name strip check_call repo_name create_bucket items list replace isinstance loads replace unquote read pseudo_json_to_data split reshape frombuffer ones_like copy find_large_empty_regions zeros select_channels zeros normalize_channels_in_place sleep print string_at sleep runlength_encode transpose array nonzero runlength_encode unicode_to_str list array blockwise_boxes asarray nonconsecutive_bincount fromarray name NamedTemporaryFile shape save append range split | # Spark Implemented EM Reconstruction Workflows [](http://www.janelia.org) This package provides python Spark utilities for interacting with EM data stored in [DVID](https://github.com/janelia-flyem/dvid). Several workflows are provided, such as large-scale image segmentation, region-adjacency-graph building, and evaluating the similarity between two image segmentations. DVIDSparkServices provides an infrastructure for custom workflow and segmentation plugins and a library for accessing DVID through Spark RDDs. The primary goal of this package is to better analyze and manipulate large EM datasets used in Connectomics (such as those needed for the [the Fly EM project](https://www.janelia.org/project-team/fly-em)). Other applications that leverage DVID might also benefit from this infrastructure. Please consult the corresponding wiki for more details on the implemented plugins and other architectural discussions: [https://github.com/janelia-flyem/DVIDSparkServices/wiki](https://github.com/janelia-flyem/DVIDSparkServices/wiki) ## Installation To simplify the build process, we now use the [conda-build](http://conda.pydata.org/docs/build.html) tool. The resulting binary is uploaded to the [flyem binstar channel](https://binstar.org/flyem), and can be installed using the [conda](http://conda.pydata.org/) package manager (instructions below). The installation will install all of the DVIDSparkServices dependencies including python. | 2,458 |
janelia-flyem/NeuroProof | ['superpixels', 'art analysis', 'semantic segmentation'] | ['Focused Proofreading: Efficiently Extracting Connectomes from Segmented EM Images', 'A Context-aware Delayed Agglomeration Framework for Electron Microscopy Segmentation'] | integration_tests/test1.py integration_tests/testragscript.py focusedproofreading/extract_paths.py integration_tests/test2.py integration_tests/testpyagglom.py python/neuroproof/Classifier/__init__.py python/neuroproof/FocusedProofreading/__init__.py focusedproofreading/smallseg.py integration_tests/testpriority_manual.py python/neuroproof/Agglomeration/__init__.py integration_tests/neuroproof_test_compare.py integration_tests/test3.py integration_tests/test5.py integration_tests/test4.py integration_tests/testpriority.py focusedproofreading/proofreading_work.py compare_outputs compare_outputs compare_outputs decode read replace communicate print makedirs write exit len close open range Popen split | # NeuroProof [](http://www.janelia.org) ##Toolkit for Graph-based Image Segmentation and Analysis [](https://anaconda.org/flyem/neuroproof) [](https://circleci.com/gh/janelia-flyem/NeuroProof) The NeuroProof software is an image segmentation tool currently being used in [the FlyEM project at Janelia Farm Research Campus](http://janelia.org/team-project/fly-em) to help reconstruct neuronal structure in the fly brain. This tool provides routines for efficiently agglomerating an initial volume that is over-segmented. It provides several advances over Fly EM's previous, but actively maintained tool, [Gala](https://github.com/janelia-flyem/gala): * Faster implementation of agglomeration (written in C++ instead of Python) | 2,459 |
janelia-flyem/gala | ['superpixels', 'active learning'] | ['Machine learning of hierarchical clustering to segment 2D and 3D images'] | benchmarks/bench_gala.py gala/app_logger.py gala/agglo2.py gala/features/base.py gala/features/io.py gala/session_manager.py gala/features/squiggliness.py tests/test_watershed.py tests/test_gala.py tests/test_server.py gala/__init__.py gala/features/convex_hull.py tests/test_imio.py doc/conf.py gala/evaluate.py gala/filters.py tests/test_optimized.py gala/features/__init__.py gala/dtypes.py gala/classify.py gala/util.py tests/example-data/example.py gala/viz.py gala/segmentation_stitch.py gala/option_manager.py tests/test_agglo.py gala/mergequeue.py gala/serve.py gala/valprob.py gala/iterprogress.py gala/imio.py gala/stitch.py gala/features/default.py gala/features/orientation.py tests/test_defaults.py tests/test_evaluate.py gala/features/graph.py tests/_util/generate-test-results.py gala/sparselol.py gala/segmentation_pipeline.py gala/auto.py gala/morpho.py gala/agglo.py gala/pixel.py gala/features/inclusion.py tests/test_features.py setup.py gala/test_package.py gala/ncut.py doc/logo/logo.py gala/stack_np.py tsdata trgraph bench_suite tsgraph_queue timer print_bench_results classifier trexamples policy tsgraph trdata Mock _split_img_horizontal logo_iterate is_mito_boundary is_mito oriented_boundary_mean random_priority best_possible_segmentation conditional_countdown classifier_probability no_mito_merge boundary_mean_ladder mito_merge compute_local_vi_change get_edge_coordinates compute_true_delta_rand compute_true_delta_vi approximate_boundary_mean boundary_mean_plus_sem Rag boundary_mean expected_change_vi batchify ordered_priority expected_change_rand make_ladder boundary_median compute_local_rand_change best_segmentation Rag sparse_boundaries edge_matrix fast_rag AppLogger find_gt_bodies process_edge entrypoint create_auto_options auto_proofread image_stack_verify2 auto graph_file_verify load_graph_json image_stack_verify VigraRandomForest save_training_data_to_disk concatenate_data_elements load_classifier load_training_data_from_disk read_rf_info save_classifier unique_learning_data_elements default_classifier_extension sample_training_data DefaultRandomForest get_classifier split_vi special_points_evaluate make_synaptic_functions split_vi_threshold fm_index calc_entropy adj_rand_index xlogx vi get_stratified_sample adapted_rand_error split_vi_mem rand_by_threshold wiggle_room_precision_recall nzcol divide_columns vi_pairwise_matrix rand_index sem vi_statistics divide_rows pixel_wise_boundary_precision_recall rand_values sorted_vi_components make_synaptic_vi vi_tables _mindiff merge_contingency_table contingency_table csrRowExpandableCSR vi_by_threshold reduce_vi edit_distance raw_edit_distance split_components assignment_table nd_sobel_magnitude read_cremi read_mapped_segmentation_raw raveler_to_labeled_volume read_image_stack write_h5_stack write_cremi write_image_stack write_ilastik_batch_volume write_png_image_stack write_vtk raveler_body_annotations write_ilastik_project write_to_raveler raveler_serial_section_map serial_section_map read_prediction_from_ilastik_batch write_mapped_segmentation extract_segments raveler_rgba_to_int write_json segs_to_raveler ucm_to_raveler raveler_output_shortcut pil_to_numpy apply_segmentation_map read_h5_stack compute_sp_to_body_map read_multi_page_tif read_mapped_segmentation read_vtk with_progress NoProgressBar MergeQueue pipeline_compact_watershed _euclid_dist raveled_steps_to_neighbors watershed get_neighbor_idxs _is_container split_exclusions pad morphological_reconstruction smallest_int_dtype relabel_connected juicy_center orphans hminima minimum_seeds manual_split watershed_sequence _thin_seeds complement remove_merged_boundaries non_traversing_segments undam regional_minima build_levels_dict multiscale_seed_sequence hollowed compact_watershed surfaces impose_minima damify build_neighbors_array multiscale_regular_seeds seg_to_bdry ncutW OptionConfig OptionNamespace OptionManager entrypoint image_stack_verify ilp_file_verify gen_pixel_verify create_pixel_options gen_pixel_probabilities temp_dir_verify pixelprob_file_verify np_verify entrypoint output_raveler inclusion_removal flow_perform_agglomeration classifier_verify gen_supervoxels_verify supervoxels_file_verify grab_boundary gen_supervoxels gen_agglomeration_verify prediction_file_verify synapse_file_verify create_segmentation_pipeline_options agglomeration run_segmentation_pipeline grab_pred_seg regions_file_verify entrypoint classifier_verify create_stitching_options update_filename find_close_tbars grab_extant run_stitching examine_boundary main Solver proofread Session extents SparseLOL get_prob_handle Stack is_one_to_one_mapping crop_probs_and_ws EvalAction write_segmentation_pipeline_json make_dir make_temp_dir find_gt_bodies process_edge entrypoint create_valprob_options auto_proofread image_stack_verify2 valprob graph_file_verify load_graph_json image_stack_verify plot_decision_function imshow_rand display_3d_segmentations imshow_grey plot_seeds add_nats_to_plot show_multiple_images plot_vi_breakdown plot_split_vi plot_vi_breakdown_panel imshow_magma add_opts_to_plot plot_vi draw_seg Null _compute_delta_vi Mock Composite Manager snemi3d paper_em Manager Manager create_fm Manager compute_bounding_box Manager test_mean_agglo_fast_rag dummy_data test_float_watershed test_thin_fragment_agglo2 test_set_ground_truth test_agglomeration test_no_dam_agglomeration test_split_vi test_mito test_best_possible_segmentation test_manual_agglo_fast_rag test_mask test_empty_rag test_ladder_agglomeration test_2_connectivity test_traverse test_snemi test_paper_em test_are test_contingency_table test_vi test_2channel_moment_features test_2channel_histogram_features test_2channel_composite_feature test_1channel_composite_feature run_matched test_1channel_moment_features test_1channel_histogram_features assert_equal_lists_or_arrays list_of_feature_arrays test_convex_hull test_1channel_squiggliness_feature feature_profile dummy_data_source test_generate_gala_examples_fast_updateedges dummy_data test_generate_flat_learning_edges test_segment_with_gala_classifer test_generate_gala_examples tar_extract test_generate_lash_examples test_generate_lash_examples_fast test_split_vi test_generate_flat_learning_edges_fast test_generate_gala_examples_fast dummy_data_fast test_cremi_roundtrip test_vtk_roundtrip test_flood_fill_with_no_hits test_flood_fill_pipes test_despeckle_stack _despeckle_example test_flood_fill_with_coordinates test_despeckle_not_in_place _flood_fill_example test_flood_fill_basic test_flood_fill_whole test_despeckle_in_place test_flood_fill_multiple_acceptable data test_server_long id_serve test_server_with_id_service dummy_data test_server_with_periodic_send test_server_imperfect_fragments test_server dummy_data2 test_watershed_plateau_performance time_me test_watershed_seeded test_watershed_seeded_nodams test_watershed_images test_watershed test_watershed_nodams test_watershed_saddle_basin process_time append join read_h5_stack join read_h5_stack Rag trdata tsdata Rag join trgraph read_h5_stack learn_agglomerate trexamples DefaultRandomForest fit classifier_probability DefaultRandomForest policy tsgraph rebuild_merge_queue tsdata asizeof Rag OrderedDict classifier_probability trdata print label2rgb uint8 permutations product _split_img_horizontal astype shape zeros next imsave count max zeros_like pred float enumerate len classifier_probability sum classifier_probability sum make_ladder fromiter list map atleast_2d rand inf len boundary pop shape unravel_index append range Rag tocsc merge_subgraph concatenate ndim coo_matrix generate_binary_structure ravel max flatnonzero data tocsr arange ravel extents len tocsr ones from_scipy_sparse_matrix edge_matrix broadcast_to shape seed merge_subgraph Rag indptr range tocsc len create_option load append open items list ndenumerate setdefault get_next_edge get_edge_val extend set_edge_result add body_pair open str list set_body_mode initialize_priority_scheduler append range process_edge readlines set info float items int print system write set_orphan_mode set_synapse_mode split find_gt_bodies items list test_stack print File read_image_stack create_dataset ragprob_file gt_stack info append load_graph_json array options AppLogger session_location get_logger auto Session isinstance load load_from_disk VigraRandomForest save_to_disk dump isinstance lower startswith File itemsize view debug concatenate_data_elements unique bincount len sample list range len File close zip append File array float sum grey_dilation setdiff1d ndim iterate_structure precision_recall_curve unique generate_binary_structure ravel binary_dilation unique len best_possible_segmentation contingency_table sum tocsr ones shape zeros bool ravel data contingency_table toarray csr_matrix eliminate_zeros indptr copy repeat _mindiff diff sort concatenate min diff contingency_table csrRowExpandableCSR data asarray nonzero copy list partial raveler_synapse_annotations_to_coords chain array vi_tables astype pdist array squareform Pool map len len adj_rand_index zeros enumerate rand_index data contingency_table size ravel items list float items list sorted setdefault print calc_entropy unique ravel range len tocsr copy indices take nonzero tocsc tocsr copy indices take nonzero tocsc contingency_table ravel shape zeros float sum argsort relabel_sequential vi_tables T ravel sum rand_values rand_values rand_values list tuple File zeros double enumerate ravel zeros_like ones astype ndim float32 sqrt float sobel enumerate endswith raveler_to_labeled_volume split_path dtype join_path shape read_prediction_from_ilastik_batch expanduser imread get fnfilter listdir enumerate join read_h5_stack isdir sort extend read_multi_page_tif any isfile zeros write_vtk endswith write_h5_stack expanduser write_png_image_stack reshape squeeze append tell seek open uint8 frombytes uint16 new astype tostring shape swapaxes save expanduser uint32 enumerate zeros enumerate shape join list str size write map close tobytes encode zeros open append reshape startswith open expanduser File array close astype expanduser File close create_dataset apply_segmentation_map read_mapped_segmentation_raw zeros dtype max expanduser File array close items list File close create_dataset expanduser str list info concatenate debug len raveler_serial_section_map repeat unique zip append ravel enumerate serial_section_map list map zip raveler_body_annotations join call savetxt non_traversing_segments mkdir write_json write_png_image_stack orphans makedirs segs_to_raveler write_to_raveler extend join_path sum load join zeros_like loadtxt min read_image_stack open raveler_rgba_to_int watershed zeros max enumerate items list reshape File close map shape array zip max enumerate reshape write_h5_stack shape get squeeze read_h5_stack items list write_h5_stack update start set_title len grey_dilation grey_erosion ndim copy generate_binary_structure max minimum grey_dilation ndim generate_binary_structure max complement min unique max zeros_like astype grey_dilation arange concatenate ndim copy generate_binary_structure bincount max len grey_dilation ndim copy shape generate_binary_structure zeros max range queue max remove_small_connected_components pad generate_binary_structure popleft hminima astype unique binary_opening regional_minima build_levels_dict StandardProgressBar enumerate with_progress ndim extend impose_minima build_neighbors_array ravel NoProgressBar all regular_grid _thin_seeds shape zeros shape all range copy hessian_matrix shape multiscale_regular_seeds zip zeros hessian_matrix_eigvals max concatenate reshape shape array flatnonzero pop inf zeros_like _euclid_dist min astype raveled_steps_to_neighbors copy shape pad unravel_index zeros ravel array push MergeQueue watershed list concatenate cumsum map copy repeat swapaxes zip max zip min ndim copy generate_binary_structure max binary_dilation watershed zeros_like ndim empty_like nonzero unique generate_binary_structure label len max list ones min ndim shape zeros ravel array range len range swapaxes ndim ndim copy swapaxes append range ndim copy append defaultdict ravel enumerate size arange list T product extend append ravel array range shape raveled_steps_to_neighbors array isscalar list hollowed zip label unique_rows array flatnonzero copy ndim generate_binary_structure concatenate reshape shape ravel distance_transform_cdt sum diags ones eigs kmeans2 shape sqrt real append ravel full range endswith image_stack glob gen_pixel make_dir temp_dir create_option join format image_stack system exit temp_dir rmtree info make_temp_dir gen_pixel_probabilities debug str volume_synapse_view read_image_stack raveler_synapse_annotations_to_coords synapse_dilation remove_small_connected_components bound_channels watershed open str dtype transpose seed_val shape split_exclusions append debug astype close mask_file copy info uint8 seed_size grab_boundary synapse_file split number_of_nodes h5_output write_image_stack abspath open str sorted basename inclusion_removal new_vlen len write_plaza_json shape dirname write_mapped_segmentation agglomerate info border_size load int get_segmentation segmentation_thresholds File synapse_file dumps write compute_sp_to_body_map sub create_dataset findall hexdigest makedirs str remove_inclusions number_of_nodes info write_to_raveler rmtree warning info segs_to_raveler exists create_fm volume_synapse_view raveler_synapse_annotations_to_coords loads warning classifier classifier_probability bound_channels str inclusion_removal use_neuroproof load_classifier shape expected_vi agglomeration Stack Rag feature_description info expected_change_vi grab_boundary synapse_file array supervoxels_name image_stack flow_perform_agglomeration transpose gen_supervoxels read_image_stack gen_pixel_probabilities h5_output supervoxels_file gen_pixel write_image_stack info gen_agglomeration pixelprob_file raveler_output synapse_file gen_agglomeration create_option create_pixel_options info run_segmentation_pipeline str list File extend set add sqrt loads utcnow grab_extant append union int str rstrip sub findall transpose read_mapped_segmentation read_image_stack grab_pred_seg dilate_edges run_watershed transpose min remove_small_connected_components add shape load_disjoint_bodies build_border unique info append zeros max range watershed number_of_nodes read_image_stack regions build_partial update_filename loads utcnow classifier abspath agglomerate_border border_weight_factor open str list set_overlap_max overlap_threshold argv set_saved_probs write_plaza_json load_classifier add append examine_boundary set_overlap_cutoff range aggressive_stitch Stack copy set_border_weight set feature_description info set_overlap_min load grab_pred_seg join tbar_proximity already_examined makedirs segmentation_threshold extend write dumps File find_close_tbars create_dataset findall array hexdigest len regions create_option run_stitching str socket list PAIR check_random_state best_segmentation send_json print zip recv_json connect shuffle unique sleep fast_rag range tocsc listen read_cremi add_argument ArgumentParser parse_args input_file Solver intp arange as_strided ones csr_matrix size astype empty_like copy bincount ravel extents_count dict ravel zip add isinstance makedirs join hex make_dir create_option find_gt_bodies auto_proofread test_stack print read_image_stack ragprob_file gt_stack info append float load_graph_json size_threshold range valprob subplots subplots random subplots ListedColormap concatenate set_title imshow_rand print imshow_grey imshow figure imshow_magma range len zeros_like mean any nonzero unique subplot list imshow_rand imshow_grey figure imshow_magma combinations_with_replacement range enumerate len plot get_segmentation vi xlabel ylabel figure unique append len arange plot xlabel min ylabel ylim scatter title xlim max subplot arange xlabel ylabel xlim vi_tables title ylim figure plot_vi_breakdown_panel legend ion max append cycle scatter zip append cycle scatter zip plot cycle scatter zip append show max subplots reshape set_yticks hstack astype viridis imshow set_xticks scatter linspace meshgrid zeros array imshow subplots plot sum xlogx Manager Manager append load_dict ones reshape min max len Rag boundary_mean assert_equal uint32 array Rag float32 boundary_mean assert_equal array nodes list Rag assert_equal vi get_segmentation Rag boundary_mean agglomerate assert_allclose vi get_segmentation Rag boundary_mean agglomerate assert_allclose agglomerate_ladder vi get_segmentation Rag boundary_mean agglomerate assert_allclose vi get_segmentation Rag boundary_mean agglomerate no_mito_merge rebuild_merge_queue mito_merge assert_allclose array Rag array Rag array Rag best_possible_segmentation array int32 set_ground_truth array Rag set_ground_truth array Rag split_vi reshape array Rag zoom list merge_nodes range merge_subgraph agglomerate feat Rag assert_allclose paper_em concatenate Rag feat snemi3d assert_allclose contingency_table todense array assert_equal vi array assert_equal assert_almost_equal adapted_rand_error array append f copy feature_profile extend zip merge_nodes int assert_approx_equal assert_allclose assert_equal assert_equal_lists_or_arrays Rag list_of_feature_arrays run_matched join run_matched join run_matched join run_matched join run_matched join run_matched join run_matched join Rag chull Manager array assert_allclose call remove basename glob reshape Mock array Rag Rag zoom learn_flat learn_flat seed print pred learn_agglomerate fpred assert_allclose fit seed print pred learn_agglomerate fpred assert_allclose fit seed pred fpred learn_agglomerate assert_allclose fit seed Rag pred learn_agglomerate fpred assert_allclose fit seed pred fpred learn_agglomerate assert_allclose fit seed Rag agglomerate classifier_probability learn_agglomerate fit load join read_h5_stack vstack assert_allclose sort ndim assert_equal randint range list astype choice assert_equal integer issubdtype randint keys range set _flood_fill_example flood_fill assert_equal set _flood_fill_example flood_fill assert_equal flood_fill tolist map set assert_equal _flood_fill_example set _flood_fill_example flood_fill assert_equal flood_fill assert_equal zeros sum len flood_fill assert_equal randint sum len array _despeckle_example despeckle_watershed assert_equal _despeckle_example despeckle_watershed assert_equal _despeckle_example transpose despeckle_watershed assert_equal socket send_json bind REP Context Mock Mock join Thread proofread start Solver join Thread proofread start Solver rsplit Thread join proofread start start Thread rsplit proofread sorted list map imread listdir join Thread proofread start Solver zip enumerate assert_array_equal array watershed assert_array_equal array watershed assert_array_equal array watershed assert_array_equal array watershed assert_array_equal array watershed ones time_me assert_array_less watershed | # gala: segmentation of nD images [](http://janelia.org/) Gala is a Python library for performing and evaluating image segmentation, distributed under the open-source, BSD-like [Janelia Farm license](http://janelia-flyem.github.io/janelia_farm_license.html). It implements the algorithm described in [Nunez-Iglesias *et al*.](http://arxiv.org/abs/1303.6163), PLOS ONE, 2013. If you use this library in your research, please cite: > Nunez-Iglesias J, Kennedy R, Plaza SM, Chakraborty A and Katz WT (2014) > [Graph-based active learning of agglomeration (GALA): a Python library to > segment 2D and 3D | 2,460 |
janinethoma/learning1M | ['image retrieval'] | ['Geometrically Mappable Image Features'] | prepare_data/003_split_images.py prepare_data/007_set_aside_queries.py evaluate/001_build_pca_lists.py prepare_data/010_get_scale_factor.py prepare_data/013_cluster_linear.py train/train.py evaluate/004_any_grad_cam.py evaluate/000_build_eval_lists.py prepare_data/002_interpolate_image_xy.py util/cv.py evaluate/005_save_movie.py util/io.py util/meta.py prepare_data/012_shuffle.py evaluate/002_call_inference.py prepare_data/005_parametrize_path.py prepare_data/009_plot_statistics.py evaluate/006_call_tsne.py evaluate/007_quantitative_table.py model/losses.py evaluate/003_call_top-n.py util/sge.py prepare_data/011_fix_localization_ref.py util/helper.py evaluate/005_save_movie_frames.py prepare_data/006_merge_parametrized.py prepare_data/008_clean_parametrization.py evaluate/008_plot_roc.py evaluate/003_any_top-n.py model/nets.py util/plot.py prepare_data/014_presample_anchors.py train/call_training.py prepare_data/001_downsize_images.py model/grad_nets.py util/sampling.py evaluate/002_any_inference.py prepare_data/004_merge_and_clean.py evaluate/004_call_grad_cam.py evaluate/006_any_tsne.py img_path get_t_x_y_a_from_path parse_file_list img_path parse_cold_folder build_inference_model infer load_images create_array_job gpu_thread cpu_thread restore_weights log get_top_n log save_cam add_text build_inference_model load_images gpu_thread cpu_thread get_grad_cam save_thread log restore_weights get_placement get_placement get_top_n log log compile_table plot_roc log vgg16Netvlad vgg16 distance_triplet_loss residual_det_loss _pairwise_squared_distances _min_eigenvalue _best_distance distance_quadruplet_loss worst_pos_distance _features2eigenvalues _scale_distances distance_loss huber_distance_loss _best_huber_distance evil_triplet_loss _max_eigenvalue evil_quadruplet_loss vgg16Netvlad vgg16 create_array_job main downsize_images create_array_job main interpolate_xy lin_ip create_array_job draw_grid get_splits main main clean merge_dates create_reference plot_results parametrize create_array_job lin_ip main merge_parametrized main set_aside_queries main find_and_remove_errors clean_parametrization main plot_statistics get_tags img_path get_greedy_fixed_localization_reference get_l_based_fixed_localization_reference shuffle cluster get_xy sample_anchors get_xy get_tuple load_images evaluate_localization_thread log evaluate_localization train_gpu_thread localization_cpu_thread train_one_epoch get_eval_loss extract_features localization_gpu_thread build_model eval_loss_gpu_thread get_learning_rate train_cpu_thread create_array_job img_path train restore_weights eval_loss_cpu_thread standard_size resize_img merge_images put_text mkdir fs_root flags_to_args flags_to_globals load_csv load_pickle load_img save_csv unzip save_txt save_img load_txt save_pickle get_xy dict_to_bar greedy get_qusub_script get_cpu_array_script get_cpu_qusub_script get_qusub_array_script run_one_job findall basename append get_t_x_y_a_from_path range len parse_file_list arange dict linspace get_recursive_file_list len print format write flush get time format print put load_images task_done get time format print put task_done run join resize_img load_img standard_size range len vgg16Netvlad placeholder dict flatten vgg16 trainable_variables restore print name Saver run global_variables_initializer ConfigProto GPUOptions Session _shared_name run_one_job load_csv load_pickle get_xy query exists save_pickle transpose argmin append range format KDTree mkdir join print fit PCA pairwise_distances min transform array len mean expand_dims sum get join uint8 format COLOR_BGR2RGB concatenate applyColorMap save_txt save_img print maximum float32 resize COLORMAP_JET task_done max cvtColor squared_difference reshape negative split uint8 format imwrite applyColorMap astype maximum float32 splitext resize COLORMAP_JET max clf max scatter savefig fit_transform float set_rasterized figure join load_pickle format defaultdict fs_root save_csv print len mean mkdir startswith append argmax array range enumerate load_pickle subplots fs_root arange set_text grid axis linspace max set_xlabel set_figheight savefig legend expand_dims range format replace plot set_xlim tight_layout mkdir startswith zip enumerate join print set_yticks min subplots_adjust cycle set_xticks set_ylabel set_figwidth get_legend_handles_labels array set_ylim svd slice subtract add reduce_prod tile reshape subtract maximum reduce_sum add worst_pos_distance reduce_mean tile fill zeros squared_difference reshape subtract maximum reduce_sum add worst_pos_distance reduce_mean tile fill zeros evil_triplet_loss squared_difference reduce_mean _scale_distances squared_difference _scale_distances distance_triplet_loss reshape subtract fill reduce_max maximum _best_distance add reduce_sum div reduce_mean tile _best_huber_distance zeros squared_difference reshape transpose eigh tensordot reshape transpose einsum _scale_distances squared_difference huber_loss _scale_distances reduce_sum div tile fill squared_difference load_csv join sorted format save_csv print save_txt range CameraModel array listdir max exists len log_dir max_side ins_root out_img_root out_root add_argument len task_id tar_root cams create_array_job downsize_images img_root ArgumentParser parse_args listdir range makedirs load_csv join sorted format save_csv print reshape KDTree mean query listdir array exists enumerate len interpolate_xy in_root zeros imwrite zip load_csv save_csv clf exists sorted list scatter savefig append imread format asarray zip listdir keys join print draw_grid array len grids get_splits load_csv join sorted format list save_csv print dict listdir keys len load_csv join percentile format save_csv dict_to_bar print dict clf hist savefig xticks sum array len merge_dates clean folds cols_to_keep load_csv join list format max save_csv min plot_results dict getattr array keys load_csv query_radius save_csv plot_results max list len getattr append range format KDTree zip lin_ip keys enumerate join print reshape min dict labels_ zeros array fit join format subplots append_axes make_axes_locatable set_text set_xlabel colorbar set_figheight clf scatter set_ylabel savefig set_figwidth array load_csv join format save_csv extend dict listdir len merge_parametrized load_csv join list format replace save_csv dict keys len print query_dates flags_to_args set_aside_queries load_csv join max format load_pickle list save_csv find_and_remove_errors extend keys dict ceil array save_pickle join norm format list save_csv max std min keys dict mean clf hist savefig median array clean_parametrization load_csv join list set dict listdir load_csv join list format int save_csv dict_to_bar fromkeys print Counter OrderedDict get_tags keys range plot_statistics tag_root load_csv save_csv save_txt query list squeeze format KDTree zip keys enumerate join int load_img reshape save_img tqdm dict img_path makedirs load_csv join format print save_txt greedy array len load_csv join list format permutation save_csv print dict range keys exists len load_csv load_pickle subplots save_csv get_xy clf save_pickle list set_figheight scatter getattr savefig append range format keys join print tqdm dict argsort set_figwidth array len load_csv join format query_radius save_csv subplots KDTree shuffle get_xy set_figheight clf scatter savefig set_figwidth array maximum get time format print put load_images task_done get time format print put task_done run load_csv join time format get print KDTree get_tuple get_xy load_images put task_done array get time format print put task_done run load_csv join time format get print KDTree get_tuple get_xy load_images put task_done array log get time format print add_summary task_done log run put_text clf Summary list basename ylabel add shape title savefig dirname legend range format plot choice mkdir xlim float empty auc join norm load_img xlabel sort reshape min text save_img merge_images add_summary img_path array len img_path log squeeze tolist add append update format setdiff1d concatenate reversed choice set copy time print reshape pairwise_distances extend array len triplet_loss lazy_quadruplet_loss flatten vgg16 residual_det_loss vgg16Netvlad get_collection placeholder evil_triplet_loss quadruplet_loss lazy_triplet_loss MomentumOptimizer distance_quadruplet_loss float evil_quadruplet_loss get_learning_rate distance_triplet_loss Variable reshape float32 dict AdamOptimizer UPDATE_OPS scalar split log load_csv join format basename arange concatenate print evaluate_localization get_xy put save get_eval_loss zeros sum array log len load_csv join list format arange clear reshape queue put mean add add_summary log Summary len load_csv join Thread format arange setDaemon KDTree get_xy query extract_features start zeros sum array len clear join list arange reshape queue put zip len float max max resize FONT_HERSHEY_SIMPLEX concatenate resize sorted format print upper keys print sorted format keys makedirs str asarray imwrite COLOR_RGB2BGR cvtColor str asarray COLOR_BGR2RGB imread cvtColor join list isinstance save_txt append keys range len extractall close open list close set_figheight clf bar figure savefig set_figwidth xticks keys range values len print KDTree tolist delete query argmax array join str basename print system copyfile rmtree dirname makedirs format format format format | # Learning Condition Invariant Features for Retrieval-Based Localization from 1M Images This repository contains the code for our papers [Learning Condition Invariant Features for Retrieval-Based Localization from 1M Images](https://arxiv.org/pdf/2008.12165.pdf) and [Geometrically Mappable Image Features](https://arxiv.org/abs/2003.09682). The corresponding models and training/testing image lists can be downloaded [here](https://www.dropbox.com/sh/xao2zjlp9tbkb1x/AABdGmJUvBcos0pU3JKJYlZVa?dl=0). This code was tested using TensorFlow 1.10.0 and Python 3.5.6. It uses the following git repositories as dependencies: - [netvlad_tf_open](https://github.com/uzh-rpg/netvlad_tf_open) - [pointnetvlad](https://github.com/mikacuy/pointnetvlad) - [robotcar-dataset-sdk](https://github.com/ori-mrg/robotcar-dataset-sdk) The training data can be downloaded using: - [RobotCarDataset-Scraper](https://github.com/mttgdd/RobotCarDataset-Scraper) | 2,461 |
janivanecky/Artistic-Style | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | style.py vgg.py gram_matrix load_image content_loss style_loss Vgg19 show int size array resize float crop open reshape transpose matmul reduce_sum to_float size reduce_sum gram_matrix zip float len | # Artistic-Style Very simple implementation of Neural Algorithm of the Artistic Style (Gatys <i>et al.</i> - http://arxiv.org/abs/1508.06576) in Tensorflow. I used VGG implementation from <a href="https://github.com/machrisaa/tensorflow-vgg">Chris</a> and modified it slightly, stripping away unnecessary layers. In the examples below I used content image as an initialization, it seems to provide more consistent image, but in the code, you can switch easily to noise initialization on line 109 in `style.py`. I used Adam for optimizer and let it run for 500 iterations. ### To run it, you're going to need: * Tensorflow * PIL/Pillow * This <a href="https://mega.nz/#!xZ8glS6J!MAnE91ND_WyfZ_8mvkuSa2YcA7q-1ehfSm-Q1fxOvvs">npy file</a> from <a href="https://github.com/machrisaa/tensorflow-vgg">Chris</a> | 2,462 |
janvainer/speedyspeech | ['speech synthesis'] | ['SpeedySpeech: Efficient Neural Speech Synthesis'] | code/melgan/model/identity.py code/melgan/inference.py code/utils/torch_stft.py code/melgan/hubconf.py code/speedyspeech.py code/melgan/trainer.py code/melgan/model/generator.py code/layers.py code/melgan/utils/stft.py code/melgan/model/multiscale.py code/extract_durations.py code/melgan/utils/audio_processing.py code/utils/augment.py code/functional.py code/melgan/utils/plotting.py code/melgan/utils/writer.py code/get_dataset_stats.py code/melgan/utils/hparams.py code/inference.py code/utils/transform.py code/melgan/utils/train.py code/utils/optim.py code/hparam.py code/melgan/utils/utils.py code/server/app.py code/utils/text.py code/melgan/preprocess.py code/utils/dynamic_time_warping.py code/losses.py code/stft.py code/melgan/datasets/dataloader.py code/melgan/model/discriminator.py code/pytorch_ssim/__init__.py code/utils/masked.py code/melgan/utils/validation.py code/datasets/AudioDataset.py code/melgan/model/res_stack.py code/duration_extractor.py ScaledDotAttention DurationExtractor ConvAudioDecoder ConvTextEncoder Collate ConvAudioEncoder save_alignments_as_fertilities fertilities_improper get_fertilities load_alignments is_non_decreasing fert2align smooth_fertilities display_spectr_alignment get_phoneme_durations idx_mask pad_batch scaled_dot_attention mask positional_encoding median median_mask HPStft HPFertility HPText HPDurationExtractor ScaledDotAttention ZeroTemporalPad ResidualBlock Pad FreqNorm Conv1d WaveResidualBlock l1_masked l1_dtw logit L1Masked GuidedAttentionLoss masked_mean binary_divergence_masked masked_huber guided_att masked_ssim Interpolate mask_durations round_and_mask expand_encodings Decoder DurationPredictor Encoder SpeedySpeech Collate expand_positional_encodings MySTFT dynamic_range_decompression nnls mel_to_stft_torch dynamic_range_compression AudioDataset melgan main main MelFromDisk create_dataloader Discriminator Generator Identity MultiScaleDiscriminator ResStack griffin_lim window_sumsquare dynamic_range_decompression dynamic_range_compression HParam Dotdict merge_dict load_hparam_str load_hparam plot_waveform_to_numpy save_figure_to_numpy TacotronSTFT STFT train read_wav_np get_commit_hash validate MyWriter create_window gaussian _ssim SSIM ssim home get_args SpeedySpeechInference synt add_random_noise replace_frames_with_random degrade_some random_patches frame_dropout plot_dtw_1d masked_sum MaskedBatchNorm1d masked_std masked_mean mask masked_max masked_var masked_min get_lr NoamScheduler TextProcessor window_sumsquare STFT StandardNorm Transform Pad MinMaxNorm Clamp Normalize map_to_tensors smooth_fertilities fertilities_improper unique_consecutive ones append argmax enumerate append sum copy enumerate arange astype repeat append zeros sum len dropout transpose matmul masked_fill softmax float cos arange sin FloatTensor cumsum to median float device to float device to as_tensor device len as_tensor T subplots suptitle concatenate plot tight_layout imshow set_ticks_position argmax stack max ndim len join list dirname abspath Identity n_mel ReLU Sigmoid n_mel ReLU to device cpu zip fastdtw exp float shape device to sum exp logit device to log1p to device to device list from_iterable long positional_encoding append sum max round mask_durations float clip_grad_norm_ matmul pinverse LBFGS step range Generator eval load_state_dict load_state_dict_from_url load config checkpoint_path HParam eval load_hparam_str load_state_dict cuda join replace glob mel_spectrogram tqdm data_path pad unsqueeze save read_wav_np TacotronSTFT MelFromDisk get_window normalize pad_center zeros range exp angle Variable squeeze rand astype float32 pi from_numpy transform range HParam remove items load_all list dict open items list __setitem__ __delitem__ __getitem__ __setitem__ __delitem__ __getitem__ reshape tostring_rgb fromstring transpose list subplots plot xlabel draw close ylabel tight_layout ylim save_figure_to_numpy range len zero_grad shuffle_mapping set_description warning save cuda count get_commit_hash Adam load_state_dict rep_discriminator range detach zip info item model_d log_training load join backward error tqdm parameters any step check_output read astype float32 generator log_validation tqdm eval discriminator zip dataset numpy cuda len Tensor Variable contiguous unsqueeze pow conv2d create_window size type_as get_device cuda is_cuda parse_args add_argument ArgumentParser make_response BytesIO synthesize sample_rate write close getvalue int list sample range len int to enumerate device show arange plot title range len ndim tuple tuple masked_sum masked_mean tuple masked_sum pow max | # SpeedySpeech [[Paper link]](https://arxiv.org/pdf/2008.03802.pdf) While recent neural sequence-to-sequence models have greatly improved the quality of speech synthesis, there has not been a system capable of fast training, fast inference and high-quality audio synthesis at the same time. We propose a student-teacher network capable of high-quality faster-than-real-time spectrogram synthesis, with low requirements on computational resources and fast training time. We show that self-attention layers are not necessary for generation of high quality audio. We utilize simple convolutional blocks with residual connections in both student and teacher networks and use only a single attention layer in the teacher model. Coupled with a MelGAN vocoder, our model's voice quality was rated significantly higher than Tacotron2. | 2,463 |
jasonge27/picasso | ['sparse learning'] | ['Picasso: A Sparse Learning Library for High Dimensional Data Analysis in R and Python'] | python-package/pycasso/__init__.py profiling/benchmark.py python-package/setup.py python-package/pycasso/libpath.py python-package/pycasso/core.py tutorials/tutorial.py python-package/doc/source/conf.py python-package/setup-pip.py elnet_obj generate_sim_lognet generate_sim_elnet plot_lognet test_elnet lognet_obj plot_elnet test_lognet _load_lib Solver PycassoError PicassoLibraryNotFound find_lib_path test seed exp ones reshape dot sqrt uniform cholesky scale binomial zeros float diag seed normal ones reshape dot sqrt uniform cholesky scale zeros float diag shape dot shape time elnet_obj concatenate lasso_path generate_sim_elnet print train Solver time set_params generate_sim_lognet print lambdas copy LogisticRegression lognet_obj append train Solver fit show plot xlabel extend test_elnet ylabel title legend show plot xlabel extend ylabel title legend test_lognet LoadLibrary PycassoError find_lib_path print dirname startswith abspath expanduser print strip dirname | [](https://circleci.com/gh/jasonge27/picasso/1) <h1 align="center">PICASSO</h1> <h4 align="center">High Performance R and Python Library for Sparse Learning</h4> ___PICASSO___ (PathwIse CalibrAted Sparse Shooting algOrithm) implements a unified framework of pathwise coordinate optimization for a variety of sparse learning problems (e.g., sparse linear regression, sparse logistic regression, sparse Poisson regression and scaled sparse linear regression) combined with efficient active set selection strategies. The core algorithm is implemented in C++ with Eigen3 support for portable high performance linear algebra. Runtime profiling is documented in the [__Performance__](#performance) section. You can cite this work by ``` @article{ge2019picasso, title={Picasso: A Sparse Learning Library for High Dimensional Data Analysis in R and Python.}, author={Ge, Jason and Li, Xingguo and Jiang, Haoming and Liu, Han and Zhang, Tong and Wang, Mengdi and Zhao, Tuo}, | 2,464 |
javiribera/locating-objects-without-bboxes | ['object localization'] | ['Locating Objects Without Bounding Boxes'] | object-locator/argparser.py object-locator/models/__init__.py object-locator/logger.py object-locator/bmm.py scripts_dataset_and_results/spacing_stats_to_csv.py object-locator/data_plant_stuff.py object-locator/metrics.py object-locator/data.py object-locator/__main__.py object-locator/models/unet_model.py object-locator/models/unet_parts.py object-locator/__init__.py object-locator/losses.py object-locator/models/utils.py object-locator/paint.py object-locator/get_image_size.py object-locator/make_metric_plots.py object-locator/find_lr.py object-locator/locate.py object-locator/train.py scripts_dataset_and_results/generate_csv.py setup.py object-locator/metrics_from_results.py scripts_dataset_and_results/parseResults.py object-locator/utils.py CustomFormatter strictly_positive_int parse_command_args strictly_positive relerror ab_from_mv get_delta _get_values AccumHistogram1D estimate_mixture estimate get_weights get_initialization CSVDataset get_train_val_loaders ScaleImageAndLabel RandomVerticalFlipImageAndLabel hflip _is_pil_image vflip build_dataset RandomHorizontalFlipImageAndLabel csv_collator XMLDataset find_lr UnknownImageFormat Image get_image_size get_image_metadata Test_get_image_size main Logger cdist WeightedHausdorffDistance AveragedHausdorffLoss _assert_no_grad generaliz_mean averaged_hausdorff_distance Judge make_metric_plots Normalizer paint_circles threshold AccBetaMixtureModel RunningAverage overlay_heatmap cluster nothing UNet outconv up double_conv down inconv load_net save_net save_checkpoint processImg eval_plant_locations processCSV pop radii parse isinstance add_argument_group print add_argument exit imgsize taus resume ArgumentParser abspath append parse_args save float float mean var len _get_values linspace zeros sum range reshape logical_and pdf bpdf any zip zeros array count max list ab_from_mv get_delta dot get_weights sum range count estimate_mixture get_initialization len CSVDataset XMLDataset int reset_index isinstance print Compose DataLoader there_is_gt build_dataset round len append stack view backward Variable transpose step zero_grad tqdm stack log10 item append to forward len get_image_metadata getsize run_tests getLogger json_indent output_func verbose DEBUG to_str_row_verbose basicConfig add_option quiet parse_args to_str_row partial OptionParser json debug ERROR get_image_metadata pformat INFO to_str_json print error print_help len sqrt unsqueeze average min array pairwise_distances mean subplots grid axhline list sorted set_xlabel title scatter legend append get_position plot set_position close shuffle stack zip ioff print set_axisbelow argsort average set_ylabel any get_legend_handles_labels read_csv list squeeze inRange THRESH_BINARY THRESH_OTSU flatten estimate mean beta range max int concatenate reshape size min astype shuffle where array len transpose LINE_AA uint16 MARKER_TILTED_CROSS astype copy drawMarker moveaxis circle copyfile save average min array pairwise_distances concatenate reshape where inRange fit int eval_plant_locations print strip literal_eval processImg float range imread read_csv append len | # Locating Objects Without Bounding Boxes PyTorch code for "Locating Objects Without Bounding Boxes" , CVPR 2019 - Oral, Best Paper Finalist (Top 1 %) [[Paper]](http://openaccess.thecvf.com/content_CVPR_2019/html/Ribera_Locating_Objects_Without_Bounding_Boxes_CVPR_2019_paper.html) [[Youtube]](https://youtu.be/8qkrPSjONhA?t=2620) <img src="https://i.postimg.cc/bNcFr9Pf/collage3x3.png" width="500em"/> <img src="https://i.postimg.cc/xC32tbYF/convergence-cropped.gif" width="500em"/> ## Citing this work ``` @article{ribera2019, title={Locating Objects Without Bounding Boxes}, author={Javier Ribera and David G\"{u}era and Yuhao Chen and Edward J. Delp}, | 2,465 |
jayadevbhaskaran/gendered-sentiment | ['sentiment analysis'] | ['Good Secretaries, Bad Truck Drivers? Occupational Gender Stereotypes in Sentiment Analysis'] | src/analysis.py src/baseline.py src/utils.py src/bilstm.py src/config.py src/generate_corpus.py Config get_control_sentences get_sentences ttest glove2dict realpath join Path dirname int astype TSV_TEST_GENDER read_csv len get_sentences mean int ttest_rel len | # Good Secretaries, Bad Truck Drivers? Occupational Gender Stereotypes in Sentiment Analysis This repository contains the code for the following paper: ``` Good Secretaries, Bad Truck Drivers? Occupational Gender Stereotypes in Sentiment Analysis Jayadev Bhaskaran and Isha Bhallamudi ``` to appear at [ACL GeBNLP (Workshop on Gender Bias for NLP)](https://genderbiasnlp.talp.cat/) at ACL 2019, Florence, Italy. The final paper can be found here: [https://arxiv.org/abs/1906.1025](https://arxiv.org/abs/1906.10256) ## Repository Structure - *data/gender_corpus.tsv* - New corpus to evaluate occupational gender stereotypes in sentiment analysis models. | 2,466 |
jaydeepthik/kaggle-facial-expression-recognition | ['l2 regularization', 'facial expression recognition'] | ['Convolutional Neural Networks for Facial Expression Recognition'] | facial_expression.py generate_dataset generate_model array read_csv values | # kaggle-facial-expression-recognition This repository contains code for **"Challenges in Representation Learning: Facial Expression Recognition Challenge"** on kaggle # Execution 1. Tensorflow 2. Pandas # Dataset The dataset can be downloaded from : https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data The data consists of 48x48 pixel grayscale images of faces. The faces have been automatically registered so that the face is more or less centered and occupies about the same amount of space in each image. The task is to categorize each face based on the emotion shown in the facial expression in to one of seven categories (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral). train.csv contains two columns, "emotion" and "pixels". The "emotion" column contains a numeric code ranging from 0 to 6, inclusive, for the emotion that is present in the image. The "pixels" column contains a string surrounded in quotes for each image. The contents of this string a space-separated pixel values in row major order. test.csv contains only the "pixels" column and your task is to predict the emotion column. The training set consists of 28,709 examples. The public test set used for the leaderboard consists of 3,589 examples. The final test set, which was used to determine the winner of the competition, consists of another 3,589 examples. | 2,467 |
jaydeepthik/neural-style-transfer | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | nst_utils.py nst_tf.py nn_model gram_matrix content_cost layer_style_cost style_cost total_cost generate_noise_image reshape_and_normalize_image save_image CONFIG load_vgg_model as_list as_list layer_style_cost run reshape _conv2d_relu Variable zeros _avgpool loadmat astype reshape MEANS shape MEANS imsave astype | # neural-style-transfer artistic style transfer using cnn # basic 1. the code uses a pre trained VGG19 architecture for performing neural style transfer that can be downloaded from http://www.vlfeat.org/matconvnet/pretrained/ 2. the inspiration was taken from the paper A Neural Algorithm of Artistic Style (https://arxiv.org/pdf/1508.06576.pdf) 3. some tweaking of parameters in loss functions were done to gentrate a fairly good results. 4. the code is a tensorflow implementation that can run on a cuda enabled GPU (my specs : 2GB Nvidia 940MX) 5. in the VGG architecture the maxpooling is repaced by average pooling as it proved to be better according to above mentioned paper. # some results :  | 2,468 |
jayheo/IAL | ['time series'] | ['Cost-effective Interactive Attention Learning with Neural Attention Processes', 'Cost-effective Interactive Attention Learning with Neural Attention Process'] | hil_medical_annotator/utils/print_utils.py models/anno.py models/GenericNeuralNet.py Task/diabetes1_Info.py models/model.py train.py models/experiments.py models/py_utils.py models/experiments_ifif.py models/experiments_ut_counterfactual.py models/np.py models/metric.py models/hessians.py hil_medical_annotator/utils/feature_name.py retrain.py retrain_eval.py hil_medical_annotator/utils/preprocess.py hil_medical_annotator/main.py models/anno_load_data.py models/dataset.py models/experiments_counterfactual.py evaluation_after_retrain.py models/load_data.py Task/Cardiovascular1_Info.py disease_search button_year patient_search non_hide_func save_result read_non_hide main start_check cf_estimation preprocess_real_inputs preprocess_feature_contrib load_textboxes print_error_message print_warning_message print_info_message print_log_message get_curr_time_stamp Anno anno_load_data DataSet further_stage_Find_influential_training_input Find_influential_training_input Find_final_evaluation_input get_try_check further_stage_Find_influential_training_input Find_influential_training_input Find_final_evaluation_input get_try_check further_stage_Find_influential_training_input Find_influential_training_input Find_final_evaluation_input get_try_check further_stage_Find_influential_training_input Find_influential_training_input get_try_check GenericNeuralNet hessian_vector_product _AsList hessians Baseline_version_load_Data Load_Data ROC_AUC RMSE accuracy IAL_NAP NP plot_y_mat plot random_sleep cprint auto_exe_multi_exep plot_pos_neg_hist create_dir get_exclusive_colors Logger load_accounts send_mail plot_cluster_scatter task_info task_info get int list load_textboxes min tolist absolute copy array preprocess_real_inputs sum max range len non_hide_func non_hide_func non_hide_func get int list time load_textboxes min absolute copy array preprocess_real_inputs sum max range len save preprocess_real_inputs max str list load_textboxes sum range get copy lower int time join print min absolute array len get int list str load_textboxes min absolute copy array preprocess_real_inputs sum max range len get int list load_textboxes print min randint absolute copy array preprocess_real_inputs sum max range len append round range append int range join exists print get_curr_time_stamp format exit print get_curr_time_stamp format print get_curr_time_stamp format print get_curr_time_stamp format load join print ones Anno negative zeros open seed join sess var arange savez print load_checkpoint Collect_incorrect_test_indices makedirs labels mean Feature_contributions_for_chosen_instance get_influence_on_test_loss range zeros len seed join sess time arange var savez print retrain_load_checkpoint Collect_incorrect_test_indices makedirs labels mean Feature_contributions_for_chosen_instance get_influence_on_test_loss range zeros len var sess join arange print load_checkpoint mean Feature_contributions_for_chosen_instance mkdir zeros range len save get_feature_importance_with_counterfactual abs append random_floats get_feature_influence_on_test_loss std get_ut_from_trainingpoints save get_feature_importance_with_counterfactual get_ut_from_trainingpoints gradients len ndims _AsList enumerate print array DataSet print array append DataSet roc_curve auc print __str__ makedirs add_subplot axis clf linspace tick_params use set_title set_xlabel axvline savefig legend tight_layout mean set_yticks hist set_ylabel figure set_xticks fill_between use set_title set_xlabel set_yticks add_subplot axis tight_layout scatter clf figure legend set_ylabel set_xticks tick_params savefig enumerate use set_title set_xlabel set_yticks add_subplot axis tight_layout clf set_ylabel figure legend set_xticks savefig tick_params add_subplot axis clf tick_params use set_title set_xlabel savefig legend plot set_xlim tight_layout mean enumerate set_yticks set_ylabel set_xticks figure set_ylim len rand sleep join login ehlo sendmail SMTP_SSL quit Process join cprint start Queue append print | # Cost-Effective Interactive Attention Learning with Neural Attention Processes This is the **TensorFlow implementation** for the paper "Cost-Effective Interactive Attention Learning with Neural Attention Processes (**ICML 2020**) : https://arxiv.org/abs/2006.05419 ## Abstract <p align="center"> <image width="950", height="400" src="/images/ial_concept_figure.png"> We propose a novel interactive learning framework which we refer to as Interactive Attention Learning (IAL), in which the human supervisors interactively manipulate the allocated attentions, to correct the model's behaviour by updating the attention-generating network. However, such a model is prone to overfitting due to scarcity of human annotations, and requires costly retraining. Moreover, it is almost infeasible for the human annotators to examine attentions on tons of instances and features. We tackle these challenges by proposing a sample-efficient attention mechanism and a cost-effective reranking algorithm for instances and features. First, we propose Neural Attention Processes (NAPs), which is an attention generator that can update its behaviour by incorporating new attention-level supervisions without any retraining. Secondly, we propose an algorithm which prioritizes the instances and the features by their negative impacts, such that the model can yield large improvements with minimal human feedback. We validate IAL on various time-series datasets from multiple domains (healthcare, real-estate, and computer vision) on which it significantly outperforms baselines with conventional attention mechanisms, or without cost-effective reranking, with substantially less retraining and human-model interaction cost. __Contribution of this work__ - We propose a __novel interactive learning framework__ which iteratively updates the model by interacting with the human supervisor via the generated attentions. - To minimize the retraining cost, we propose a __novel probabilistic attention mechanism__ which sampleefficiently incorporates new attention-level supervisions on-the-fly without retraining and overfitting. | 2,469 |
jaykay233/EventExtraction | ['relation extraction'] | ['BERT-Based Multi-Head Selection for Joint Entity-Relation Extraction'] | data_process.py train_ee.py schema_process extract_result read_by_lines write_by_lines LabelDataset data_process NerDataset predict_data_process JointModel viterbi_decode DiceLoss MulticlassDiceLoss list append append startswith enumerate join list items extract_result read_by_lines set write_by_lines loads append sorted log append zeros range | # 百度事件抽取 Baidu lic 2020 event extraction joint extraction baseline(有机器可以尝试,我实在跑不动了) 事件联合抽取:BERT-Based Multi-Head Selection for Joint Entity-Relation Extraction https://arxiv.org/abs/1908.05908 ### requirements: torch==1.5 torchvision==0.6.0 pytorch-lightning==0.7.0 transformers>=2.8.0 | 2,470 |
jayleicn/TVCaption | ['moment retrieval', 'video retrieval'] | ['TVR: A Large-Scale Dataset for Video-Subtitle Moment Retrieval'] | baselines/multimodal_transformer/translator.py baselines/multimodal_transformer/transformer/model.py baselines/multimodal_transformer/build_vocab.py utils/basic_utils.py baselines/multimodal_transformer/translate.py baselines/multimodal_transformer/transformer/tvc_dataset.py standalone_eval/evaluate.py baselines/multimodal_transformer/transformer/decode_strategy.py baselines/multimodal_transformer/local_utils.py baselines/multimodal_transformer/train.py baselines/multimodal_transformer/transformer/optimization.py baselines/multimodal_transformer/transformer/beam_search.py load_transform_data main load_glove build_vocab_idx extract_glove merge_dicts set_lr sum_parameters save_parsed_args_to_json flat_list_of_lists save_json_pretty count_parameters save_json merge_json_files load_json get_args eval_language_metrics cal_performance train_epoch main train sort_res main get_data_loader run_translate Translator mask_tokens_after_eos tile BeamSearch DecodeStrategy length_penalty_builder BertIntermediate BertAttention BertEncoderNoMemoryUntied BertDecoderLayerNoMemoryUntied BertSelfAttention MMT BertEmbeddingsWithVideo gelu BertLayerNoMemoryUntied BertLMPredictionHead LabelSmoothingLoss PositionEncoding BertDecoderNoMemoryUntied BertOutput BertPredictionHeadTransform BertSelfOutput BertLayerNorm _LRSchedule EMA BertAdam WarmupCosineWithWarmupRestartsSchedule WarmupCosineSchedule WarmupCosineWithHardRestartsSchedule WarmupConstantSchedule WarmupLinearSchedule ConstantLR caption_collate step_collate prepare_batch_inputs process_single_vid_sub load_process_sub_meta TVCaptionDataset TVRCaptionEval save_json start_eval remove_nonascii load_jsonl merge_dicts load_pickle make_zipfile count_parameters save_lines mkdirp load_json convert_to_seconds load_jsonl save_pickle get_show_name flat_list_of_lists save_json get_video_name_from_url save_jsonl dissect_by_lengths l2_normalize_np_array get_ratio_from_counter AverageMeter read_lines items list format print set len load_json items list append list format print tqdm save zeros load_glove keys range len join train_path format flat_list_of_lists cache print add_argument raw_glove_path min_word_count dset_name save_json ArgumentParser parse_args load_jsonl build_vocab_idx extract_glove makedirs save_json_pretty vars save_json param_groups print sum format print sum format update range copy len merge_dicts save_json ne view eq item IGNORE ne set_detect_anomaly model backward debug clip_grad_norm_ zero_grad prepare_batch_inputs grad_clip tqdm parameters item zip train step IGNORE enumerate len format save_model replace save_jsonl reference_path call run_translate abspath load_json Translator save_model res_dir BertAdam save device log list len renames to range SummaryWriter format eval_language_metrics debug close info zip time train_epoch named_parameters n_epoch add_scalar join save_model res_dir debug add_argument res_root_dir save_json share_wd_cls_weight ArgumentParser device vars parse_args exists makedirs seed get_args hasattr info set_pretrained_embedding MMT word2idx train DataLoader pprint warning TVCaptionDataset EDict manual_seed vars float len list items sorted DataLoader TVCaptionDataset get_data_loader res_dir eval_split_name reference_path abspath call getattr run_translate __dict__ replace save_jsonl Translator setattr load list view size contiguous range len len range nonzero item items list isinstance dict Tensor to dict default_collate isinstance step_collate list flat_list_of_lists empty_like set floor ceil array values process_single_vid_sub items list tqdm TVRCaptionEval format eval_res evaluate submission_path print add_argument dumps reference_path output save_json ArgumentParser parse_args makedirs abspath append range len list keys values | TVCaption === PyTorch implementation of MultiModal Transformer (MMT), a method for multimodal (video + subtitle) captioning. [TVR: A Large-Scale Dataset for Video-Subtitle Moment Retrieval](https://arxiv.org/abs/2001.09099) [Jie Lei](http://www.cs.unc.edu/~jielei/), [Licheng Yu](http://www.cs.unc.edu/~licheng/), [Tamara L. Berg](http://tamaraberg.com/), [Mohit Bansal](http://www.cs.unc.edu/~mbansal/) ### TVC Dataset and Task We extended TVR by collecting extra captions for each annotated moment. This dataset, named TV show Captions (TVC), is a large-scale multimodal video captioning dataset, | 2,471 |
jayleicn/TVQA | ['video question answering'] | ['TVQA: Localized, Compositional Video Question Answering'] | preprocessing.py tvqa_dataset.py model/mlp.py model/bidaf.py test.py __init__.py model/rnn.py config.py model/__init__.py utils.py main.py model/tvqa_abc.py TestOptions BaseOptions train validate merge_list_dicts convert_ts find_nearest load_srt add_located tokenize_qa get_vidname2cnt_per_show get_located_sub_text add_srt clean_str interval2frame get_vidname2cnt_all tokenize_srt process_qa test get_acc_from_qid_dicts pad_collate Batch preprocess_inputs TVQADataset load_pickle merge_two_dicts save_json_pretty mkdirp save_json read_json_lines load_json files_exist save_pickle BidafAttn MLP RNNEncoder mean_along_time max_along_time ABC max_vcpt_l validate model set_grad_enabled zero_grad DataLoader max_vid_l save len append results_dir sum set_mode state_dict debug preprocess_inputs item float enumerate join criterion backward print tqdm step max_sub_l add_scalar max_vcpt_l criterion model debug set_grad_enabled len preprocess_inputs eval DataLoader max_vid_l item append float sum set_mode max_sub_l enumerate update range copy len glob join tqdm len join merge_list_dicts print get_vidname2cnt_per_show save_json append exists sub join milliseconds seconds list replace print glob text len tqdm save_json append minutes range exists open max asarray floor clip list print tqdm clean_str append keys print list keys tqdm deepcopy join list print tqdm range len argmin join asarray find_nearest extend append range len deepcopy list convert_ts print tqdm get_located_sub_text interval2frame range len add_located tokenize_qa save_json add_srt read_json_lines get_vidname2cnt_all max_vcpt_l merge_two_dicts model set_grad_enabled tolist preprocess_inputs tqdm enumerate DataLoader eval max_vid_l set_mode max_sub_l mode list asarray float sum keys len list get_batch LongTensor pad_sequences zip append pad_video_sequences enumerate clamp size min extend getattr to makedirs update copy | # TVQA PyTorch code accompanies our EMNLP 2018 paper: [TVQA: Localized, Compositional Video Question Answering](https://arxiv.org/abs/1809.01696) [Jie Lei](http://www.cs.unc.edu/~jielei/), [Licheng Yu](http://www.cs.unc.edu/~licheng/), [Mohit Bansal](http://www.cs.unc.edu/~mbansal/), [Tamara L. Berg](http://tamaraberg.com/) **Updates 2022-10-24:** Our original web server is down due to a hardware failure, please access data, website, and submission/leaderboard from this [new link](https://nlp.cs.unc.edu/data/jielei/tvqa/tvqa_public_html). ## Resources - Data: [TVQA dataset](http://tvqa.cs.unc.edu/download_tvqa.html) - Website: [http://tvqa.cs.unc.edu](http://tvqa.cs.unc.edu). - Submission/Leaderboard: [TVQA Leaderboard](http://tvqa.cs.unc.edu/leaderboard.html) | 2,472 |
jayleicn/recurrent-transformer | ['video captioning'] | ['MART: Memory-Augmented Recurrent Transformer for Coherent Video Paragraph Captioning'] | src/build_vocab.py src/rtransformer/recursive_caption_dataset.py src/train.py src/rtransformer/model.py src/rtransformer/optimization.py densevid_eval/coco-caption/pycocoevalcap/meteor/__init__.py densevid_eval/evaluate.py densevid_eval/coco-caption/pycocoevalcap/__init__.py densevid_eval/coco-caption/pycocoevalcap/cider/cider.py densevid_eval/merge_dicts_by_prefix.py densevid_eval/coco-caption/pycocoevalcap/meteor/meteor.py densevid_eval/coco-caption/pycocoevalcap/bleu/__init__.py src/translate.py densevid_eval/coco-caption/pycocoevalcap/eval.py src/translator.py densevid_eval/coco-caption/pycocoevalcap/cider/cider_scorer.py densevid_eval/coco-caption/pycocoevalcap/rouge/rouge.py src/rtransformer/masked_transformer.py densevid_eval/coco-caption/pycocoevalcap/tokenizer/ptbtokenizer.py densevid_eval/get_caption_stat.py densevid_eval/para-evaluate.py src/rtransformer/beam_search.py src/utils.py densevid_eval/coco-caption/pycocoevalcap/tokenizer/__init__.py src/rtransformer/decode_strategy.py densevid_eval/coco-caption/pycocoevalcap/bleu/bleu.py densevid_eval/evaluateRepetition.py densevid_eval/coco-caption/pycocoevalcap/bleu/bleu_scorer.py densevid_eval/coco-caption/pycocoevalcap/cider/__init__.py densevid_eval/evaluateCaptionsDiversity.py densevid_eval/coco-caption/pycocotools/coco.py densevid_eval/coco-caption/pycocoevalcap/rouge/__init__.py densevid_eval/coco-caption/pycocotools/__init__.py ANETcaptions main remove_nonascii activity_stats video_stats evaluateDiversity overall_stats getNgrams save_json_pretty get_ngrams save_json evaluate_main evaluate_repetition get_args get_sen_stat flat_list_of_lists save_json_pretty eval_cap load_json merge_dicts save_json_pretty load_json merge_main parse_sent main ANETcaptions parse_para COCOEvalCap Bleu precook BleuScorer cook_test cook_refs Cider precook CiderScorer cook_test cook_refs Meteor my_lcs Rouge PTBTokenizer COCO load_transform_data main load_glove build_vocab_idx extract_glove get_args eval_language_metrics cal_performance train_epoch main train eval_epoch sort_res main get_data_loader run_translate Translator mask_tokens_after_eos tile merge_dicts set_lr sum_parameters save_parsed_args_to_json flat_list_of_lists count_parameters save_json merge_json_files load_json BeamSearch DecodeStrategy length_penalty_builder DecoderLayer ResidualBlock FeedForward LayerNorm Decoder Encoder MTransformer MultiHead Attention positional_encodings_like EncoderLayer RelPartialLearnableDecoderLayer NonRecurTransformerUntied TransformerXL RelMultiHeadAttn RelPartialLearnableMultiHeadAttn BertEmbeddingsVideoUntied BertEncoder BertDecoderLayerNoMemoryUntied BertSelfAttention RecursiveTransformer BertEncoderWithMemory make_shifted_mask BertLayerNoMemoryUntied TransformerXLEncoder BertOutput BertPredictionHeadTransform BertAttention BertEncoderNoMemoryUntied BertEmbeddingsWithVideo gelu BertEncoderNoMemory BertLMPredictionHead NonRecurTransformer BertDecoderNoMemoryUntied BertLayer MemoryInitializer make_pad_shifted_mask make_video_only_mask MemoryUpdater BertIntermediate BertEmbeddingsTextUntied LabelSmoothingLoss PositionEncoding PositionwiseFF PositionalEmbeddingXL BertLayerWithMemory BertSelfOutput BertLayerNorm BertLayerNoMemory _LRSchedule EMA BertAdam WarmupCosineWithWarmupRestartsSchedule WarmupCosineSchedule WarmupCosineWithHardRestartsSchedule WarmupConstantSchedule WarmupLinearSchedule ConstantLR caption_collate single_sentence_collate step_collate prepare_batch_inputs RecursiveCaptionDataset dump scores evaluate print len output verbose open ANETcaptions float sum tious enumerate enumerate load activity_stats video_stats overall_stats open load replace print len lower split append enumerate open sum replace print len mean append float getNgrams enumerate split sum replace print len split append float getNgrams enumerate enumerate replace print get_ngrams len dict append float sum split load format print save_json_pretty add_argument dumps output ArgumentParser reference submission parse_args evaluate_repetition open add_argument ArgumentParser flat_list_of_lists set sum len load list format get_args get_sen_stat flat_list_of_lists print save_json_pretty output verbose reference submission values open update range copy len merge_dicts join format print glob template add_argument save_json_pretty output ArgumentParser parse_args len sub split replace items list defaultdict tuple split range len get items precook min append float sum max len items precook max range len items list format print set len load_json items list append list format print tqdm save zeros load_glove keys range len join train_path format flat_list_of_lists cache add_argument raw_glove_path min_word_count dset_name save_json ArgumentParser load_json parse_args build_vocab_idx extract_glove makedirs ne view eq item IGNORE set_detect_anomaly model clip_grad_norm_ zero_grad print_info prepare_batch_inputs grad_clip ne debug ema recurrent zip float enumerate backward add_scalar tqdm parameters train step IGNORE len eval merge_dicts format save_model replace call run_translate save_json abspath info Translator data save_model res_dir BertAdam assign save register log list ema_decay renames to range SummaryWriter format EMA save_parsed_args_to_json eval_language_metrics debug close resume info zip eval_epoch requires_grad time add_scalar train_epoch named_parameters n_epoch len join save_model mtrans res_dir debug res_root_dir untied recurrent xl xl_grad parse_args share_wd_cls_weight makedirs mtrans count_parameters MTransformer word_embeddings NonRecurTransformerUntied DataLoader warning EDict device TransformerXL seed hasattr RecursiveTransformer xl get_args RCDataset word2idx recurrent info NonRecurTransformer manual_seed vars set_pretrained_embedding dumps untied train list items sorted sort_res debug translate_batch prepare_batch_inputs tqdm recurrent zip append enumerate DataLoader recurrent RCDataset merge_dicts get_data_loader res_dir abspath call getattr run_translate __dict__ replace Translator setattr eval_splits load list view size contiguous range len len range nonzero item vars save_json param_groups print sum format print sum format merge_dicts save_json size cos get_device sin zeros float range cuda is_cuda shape new_ones tril new_zeros unsqueeze make_shifted_mask deepcopy items list isinstance dict Tensor to len dict default_collate isinstance deepcopy step_collate dict append range max IGNORE len step_collate | MART: Memory-Augmented Recurrent Transformer for Coherent Video Paragraph Captioning ===== PyTorch code for our ACL 2020 paper ["MART: Memory-Augmented Recurrent Transformer for Coherent Video Paragraph Captioning"](https://arxiv.org/abs/2005.05402) by [Jie Lei](http://www.cs.unc.edu/~jielei/), [Liwei Wang](http://www.deepcv.net/), [Yelong Shen](https://scholar.google.com/citations?user=S6OFEFEAAAAJ&hl=en), [Dong Yu](https://sites.google.com/site/dongyu888/), [Tamara L. Berg](http://tamaraberg.com/), and [Mohit Bansal](http://www.cs.unc.edu/~mbansal/) Generating multi-sentence descriptions for videos is one of the most challenging captioning tasks due to its high requirements for not only visual relevance but also discourse-based coherence across the sentences in the paragraph. Towards this goal, we propose a new approach called | 2,473 |
jaywalnut310/glow-tts | ['speech synthesis'] | ['HiFi-GAN: Generative Adversarial Networks for Efficient and High Fidelity Speech Synthesis'] | audio_processing.py train.py data_utils.py modules.py text/numbers.py text/__init__.py text/symbols.py text/cmudict.py stft.py models.py monotonic_align/setup.py text/cleaners.py utils.py init.py commons.py monotonic_align/__init__.py attentions.py MultiHeadAttention FFN CouplingBlock Encoder griffin_lim window_sumsquare dynamic_range_decompression dynamic_range_compression shift_1d fused_add_tanh_sigmoid_multiply sequence_mask maximum_path convert_pad_shape squeeze Adam mle_loss clip_grad_value_ duration_loss intersperse unsqueeze generate_path TacotronSTFT TextMelSpeakerLoader TextMelCollate TextMelLoader TextMelSpeakerCollate main FlowGenerator_DDI FlowSpecDecoder DurationPredictor FlowGenerator TextEncoder InvConvNear ConvReluNorm ActNorm LayerNorm WN STFT main train evaluate train_and_eval load_wav_to_torch plot_spectrogram_to_numpy get_hparams_from_dir check_git_hash get_hparams_from_file summarize load_checkpoint latest_checkpoint_path save_checkpoint get_hparams load_filepaths_and_text HParams get_logger plot_alignment_to_numpy maximum_path lowercase english_cleaners expand_abbreviations collapse_whitespace basic_cleaners convert_to_ascii transliteration_cleaners expand_numbers _parse_cmudict _get_pronunciation CMUDict normalize_numbers _expand_dollars _expand_ordinal _expand_decimal_point _expand_number _remove_commas text_to_sequence _clean_text _symbols_to_sequence _should_keep_symbol sequence_to_text _arpabet_to_sequence get_arpabet get_window normalize pad_center zeros range exp angle Variable squeeze rand astype float32 pi from_numpy transform range len ones_like exp pi sum log sum sigmoid tanh max arange dtype list arange to reshape astype float32 where reversed shape int64 device zeros bool numpy range dtype view cumsum shape device to norm list isinstance clamp_ Tensor float to size view to size view data generator model_dir DataLoader save_checkpoint cuda TextMelCollate seed Adam get_logger check_git_hash manual_seed info enumerate join learning_rate parameters training_files get_hparams train TextMelLoader device_count spawn data model_dir DataLoader save_checkpoint fp16_run cuda TextMelCollate seed initialize DDP set_device DistributedSampler Adam _update_learning_rate get_logger range SummaryWriter check_git_hash format init_process_group validation_files latest_checkpoint_path _optim manual_seed info join learning_rate evaluate load_checkpoint parameters training_files train epochs TextMelLoader len generator summarize zero_grad mle_loss clip_grad_value_ fp16_run dataset duration_loss master_params sum module update format _optim info item enumerate backward set_epoch parameters step len update format summarize eval info sum load items list format hasattr load_state_dict info state_dict format hasattr save info state_dict items list add_scalar add_histogram add_image glob join print sort subplots use getLogger WARNING xlabel tostring_rgb draw fromstring ylabel colorbar tight_layout reshape imshow close setLevel subplots use getLogger WARNING xlabel tostring_rgb draw fromstring ylabel colorbar tight_layout reshape imshow close setLevel read join config model add_argument loads ArgumentParser parse_args HParams makedirs join HParams loads HParams loads join read format write warn realpath getoutput dirname exists join setFormatter basename getLogger addHandler Formatter DEBUG setLevel FileHandler makedirs int32 maximum_path_c sub lowercase collapse_whitespace lowercase convert_to_ascii collapse_whitespace lowercase expand_abbreviations collapse_whitespace convert_to_ascii expand_numbers append _get_pronunciation sub split split group split int group sub lookup _clean_text _symbols_to_sequence group match startswith range len cleaner getattr | # Glow-TTS: A Generative Flow for Text-to-Speech via Monotonic Alignment Search ### Jaehyeon Kim, Sungwon Kim, Jungil Kong, and Sungroh Yoon In our recent [paper](https://arxiv.org/abs/2005.11129), we propose Glow-TTS: A Generative Flow for Text-to-Speech via Monotonic Alignment Search. Recently, text-to-speech (TTS) models such as FastSpeech and ParaNet have been proposed to generate mel-spectrograms from text in parallel. Despite the advantage, the parallel TTS models cannot be trained without guidance from autoregressive TTS models as their external aligners. In this work, we propose Glow-TTS, a flow-based generative model for parallel TTS that does not require any external aligner. By combining the properties of flows and dynamic programming, the proposed model searches for the most probable monotonic alignment between text and the latent representation of speech on its own. We demonstrate that enforcing hard monotonic alignments enables robust TTS, which generalizes to long utterances, and employing generative flows enables fast, diverse, and controllable speech synthesis. Glow-TTS obtains an order-of-magnitude speed-up over the autoregressive model, Tacotron 2, at synthesis with comparable speech quality. We further show that our model can be easily extended to a multi-speaker setting. Visit our [demo](https://jaywalnut310.github.io/glow-tts-demo/index.html) for audio samples. We also provide the [pretrained model](https://drive.google.com/open?id=1JiCMBVTG4BMREK8cT3MYck1MgYvwASL0). <table style="width:100%"> <tr> <th>Glow-TTS at training</th> <th>Glow-TTS at inference</th> | 2,474 |
jbaek080/unreasonable-word-vectors | ['word embeddings'] | ['Man is to Computer Programmer as Woman is to Homemaker? Debiasing Word Embeddings'] | global_settings.py vocab_generator.py sentences_generator.py save_embeddings.py algo.py analogy cos_similarity load_google_news_model load_embeddings similarity n_most_similar write_array_to_file save_embeddings GutenbergSentences ReutersSentences Sentences BrownSentences build_vocabulary generate_vocabulary_lookups get_negative_samples pretraining_batch_generator sentences_to_index_sequences subsample_sentence filter_vocabulary_based_on len range similarity cos_similarity set_trace range len print uniform load_word2vec_format array range append len str write item range len setdefault print train_words split len print vocab_size len dict sorted reversed list random train_words sqrt sample append list negative vocab_size sample range list subsample_sentence window_size split append array range len generate_inverse_vocabulary_lookup | #unreasonable-word-vectors Word vectors are competent at logical tasks: many word vector models easily beat human averages on the Reading section of the Scholastic Aptitude Test (SAT) (https://www.cs.princeton.edu/sites/default/files/uploads/eugene_tang.pdf). However, perhaps related to this rigidity, many models struggle with understanding metaphorical speech, and even exhibit racist and sexist tendencies (https://arxiv.org/abs/1607.06520). The goal of this project is to research and prototype new word vector models, called Unreasonable Word Vectors, which can mitigate some of these undesirable features by being flexible, creative, and inclusive. I have one specific model in mind: Many neural embeddings are trained on a value function paradigm that is perhaps too "reasonable": given a context, predict a word that fits that context, based on the corpus data. For example: "the cat ____ on the mat." The right answer, I suppose, is "sat", but that is not very interesting, precisely because the value function values predictable and uninteresting answers. So the idea is to use an "unreasonable", or metaphorical, value function: to the vanilla value function, add a regularizer function that insists that "crime" is equal to "disease" (https://web.stanford.edu/~jlmcc/papers/ThibodeauMcCBoroditsky09CogSciProc.pdf). Theoretically, this should have an effect, over the entire model, so that if "crime" and "disease" end up having similar embeddings in the model, perhaps "teacher" and "doctor" will, also: the goal is to make this unpredictable, but in an interesting way, that is, not random. | 2,475 |
jbarnesspain/targeted_blse | ['sentiment analysis', 'machine translation'] | ['Embedding Projection for Targeted Cross-Lingual Sentiment: Model Comparisons and a Real-World Study'] | case_study/Utils/utils.py case_study/Utils/kaf_parser.py case_study/aspect_muse.py case_study/Utils/kaf_baseline.py experiment_2/aspect_BLSE.py case_study/Utils/Representations.py experiment_2/aspect_MUSE.py case_study/aspect_MT.py experiment_2/Utils/usage_parser.py experiment_2/Utils/WordVecs.py case_study/Utils/semeval_baseline.py experiment_2/Utils/utils.py experiment_2/Utils/kaf_baseline.py experiment_2/Utils/Representations.py case_study/aspect_vecmap.py experiment_2/Utils/kaf_parser.py case_study/aspect_BLSE.py experiment_2/Utils/semeval_baseline.py case_study/Utils/Datasets.py case_study/majority_class_baseline.py case_study/Utils/usage_baseline.py experiment_2/aspect_vecmap.py experiment_2/aspect_MT.py case_study/Utils/WordVecs.py case_study/Utils/usage_parser.py experiment_2/aspect_barista.py experiment_2/Utils/Datasets.py experiment_2/Utils/usage_baseline.py aspect_BLSE mse_loss aspect_MT aspect_MUSE aspect_VecMap Spanish_Dataset Concat_Opener_Dataset Electronics_Dataset Kitchen_Dataset Amazon_Dataset Stanford_Sentiment_Dataset Sentence_Polarity_Dataset General_Dataset Book_Dataset Concat_Sentence_Polarity_Dataset DVD_Dataset Twitter_Sentiment_Dataset English_Dataset Catalan_Dataset get_opinions get_tag_idx get_opener_sentence_data get_opinions get_opener_data create_training_example words idx_vecs sum_vecs bow ave_vecs getMyData get_semeval_sentence_data get_usage_opinions create_usage_training_example get_usage_data get_usage_opinions create_usage_training_example get_usage_data per_class_f1 ProjectionDataset get_semeval_data open_dataset cos print_args print_prediction per_class_rec print_results to_array get_syn_ant str2bool get_best_run train_dev_split per_class_prec ConcatVecs GloveVecs WordVecs aspect_Barista aspect_BLSE mse_loss aspect_MT aspect_MUSE aspect_VecMap Spanish_Dataset Concat_Opener_Dataset Electronics_Dataset Kitchen_Dataset Amazon_Dataset Stanford_Sentiment_Dataset Sentence_Polarity_Dataset General_Dataset Book_Dataset Concat_Sentence_Polarity_Dataset DVD_Dataset Twitter_Sentiment_Dataset English_Dataset Catalan_Dataset get_opinions get_tag_idx get_opener_sentence_data get_opinions get_opener_data create_training_example words idx_vecs sum_vecs bow ave_vecs getMyData get_semeval_sentence_data get_usage_opinions create_usage_training_example get_usage_data get_usage_opinions create_usage_training_example get_usage_data per_class_f1 ProjectionDataset get_semeval_data open_dataset cos print_args print_prediction per_class_rec print_results to_array get_syn_ant str2bool get_best_run train_dev_split per_class_prec ConcatVecs GloveVecs WordVecs enumerate get join list text fromstring Counter dict getchildren encode get_tag_idx keys append get_opinions join listdir extend index join extend get_opinions append listdir create_training_example zeros vector_size array split len zeros vector_size array split append split zeros len append open parse text getchildren getroot append update int replace readlines Counter append split lower word_tokenize get_usage_opinions join extend append create_usage_training_example split print vars format getattr dirname makedirs join format learning_rate batch_size src_dataset epochs weight_decay dirname alpha trg_lang src_lang binary makedirs append join open split get int parse text getchildren getroot append split set to_array append f1_score range len set precision_score to_array append range len recall_score set to_array append range len int len CosineSimilarity min len int float listdir join | Targeted Cross-lingual Sentiment Analysis via Embedding Projection ============== This repository hosts the source code and data for our work on targeted cross-lingual sentiment analysis. The repository for experiment 1 can be found [here](https://github.com/jbarnesspain/blse). Requirements to run the experiments -------- - Python 3 - NumPy - sklearn [http://scikit-learn.org/stable/] | 2,476 |
jbkinney/14_maxent | ['density estimation'] | ['Unification of field theory and maximum entropy methods for learning probability densities'] | fig_3_calculate.py demo.py deft_nobc.py deft_utils.py fig_3_draw.py fig_4.py fig_2.py get_colormap maxent_1d get_cumulants derivative_matrix Results bilateral_laplacian get_moments label_subplot label_semilogx_subplot Args forceAspect Results label_image_sublot label_subplot Results label_semilogx_subplot forceAspect T ListedColormap interp1d linspace array ones diag ones range diag derivative_matrix array ones range shape sum get_moments exp minimize print Results linspace zeros sum range x len set_aspect get_images get_extent abs text get_ylim get_xlim exp text get_ylim get_xlim log text get_ylim get_xlim | 14_maxent ========= Written by by Justin B. Kinney, Cold Spring Harbor Laboratory Last updated on 23 March 2015 Reference: Kinney JB (2014) Unification of Field Theory and Maximum Entropy Methods for Learning Probability Densities. arXiv:1411.5371 [physics.data-an] http://arxiv.org/abs/1411.5371 Code: https://github.com/jbkinney/14_maxent | 2,477 |
jchibane/ndf | ['multi target regression'] | ['Neural Unsigned Distance Fields for Implicit Function Learning'] | configs/config_loader.py train.py dataprocessing/convert_to_scaled_off.py models/local_model.py models/training.py generate.py dataprocessing/create_split.py models/data/voxelized_data_shapenet.py dataprocessing/voxelized_pointcloud_sampling.py models/generation.py dataprocessing/boundary_sampling.py dataprocessing/preprocess.py gen_iterator get_config config_parser boundary_sampling HiddenPrints as_mesh to_off multiprocess create_grid_points_from_bounds voxelized_pointcloud_sampling init Generator convertSecs convertMillis NDF convertMillis convertSecs Trainer VoxelizedDataset format savez print tqdm generate_point_cloud normpath get_loader export exists enumerate makedirs add_argument add_mutually_exclusive_group ArgumentParser join format basename data_dir input_res sample_std_dev config_parser parse_args array sample_ratio load join format collect savez randn print copy dirname sample zeros abs exists Scene tuple isinstance concatenate join format print dirname exists join close Pool map load join packbits format savez print input_res num_points query dirname sample zeros exists len bb_min bb_max input_res KDTree create_grid_points_from_bounds meshgrid reshape linspace column_stack int int | # Neural Unsigned Distance Fields > Neural Unsigned Distance Fields for Implicit Function Learning <br /> > [Julian Chibane](http://virtualhumans.mpi-inf.mpg.de/people/Chibane.html), [Aymen Mir](http://virtualhumans.mpi-inf.mpg.de/people/Mir.html), [Gerard Pons-Moll](http://virtualhumans.mpi-inf.mpg.de/people/pons-moll.html)  [Paper](http://virtualhumans.mpi-inf.mpg.de/papers/chibane2020ndf/chibane2020ndf.pdf) - [Supplementaty](http://virtualhumans.mpi-inf.mpg.de/papers/chibane2020ndf/chibane2020ndf-supp.pdf) - [Project Website](http://virtualhumans.mpi-inf.mpg.de/ndf/) - [Arxiv](https://arxiv.org/abs/2010.13938) - Published in NeurIPS 2020. #### Citation | 2,478 |
jderiu/e2e_nlg | ['text generation'] | ['Syntactic Manipulation for Generating more Diverse and Interesting Texts'] | src/evaluation/generate_output.py src/architectures/custom_callbacks/output_text.py src/architectures/custom_layers/sem_recurrent.py src/data_processing/delexicalise_data.py src/architectures/sc_lstm_architecutre/semantic_classifiers.py src/architectures/custom_callbacks/output_callbacks.py src/demo/demo_utils.py src/data_processing/utils.py src/evaluation/rate_file_output.py src/architectures/custom_callbacks/custom_callbacks.py src/demo/console_demo.py src/training/train_classifiers.py src/data_processing/vectorize_data.py src/data_processing/surface_feature_vectors.py src/architectures/sc_lstm_architecutre/sclstm_vanilla_architecture.py src/demo/server.py src/architectures/custom_layers/recurrent_tensorflow.py src/demo/test_client.py src/architectures/custom_layers/word_dropout.py src/training/train_sclstm.py src/data_processing/generate_evaluation_data.py src/evaluation/rule_based_err.py MultiModelCheckpoint pretrain_discriminator TrainingCallback TerminateOnNaN StepCallback LexFeatureOutputCallbackVanilla output_predefined_feautres sc_tf_rnn expand_dims ctc_decode reverse SC_LSTM WordDropout generator_model sc_lstm_decoder get_classifier_architecture conv_block_layered get_semantic_classifier _get_vals_for_attr _delex_nlg_data _delexicalise _read_data _retrieve_mr_ontology _delex_single _parse_single_mr _parse_raw_mr _load_attributes _get_delex_fields _load_delex_fields _save_data _read_data _sample_features _sample_surface_features_for_mr _sample_surface_feautres _sample_formulation_for_feature _utt_fw_features _utterance_first_word_vocab _follow_sent_first_word_vocab _sentence_tok extract_surface_level_features _get_formulation_for_feature _follow_fw_features _save_delex_data _load_vectorized_data _load_delex_data convert2indices _save_vectorized_data _vectorize_mrs _compute_vector_length vectorize_data _create_pos_vocabulary _vectorize_single_mr isInt get_mr_from_user NLGModel main _print_full_output _lexicalise_output load_model get_discr_ratings prepare_input select_top_outputs get_discr_ratings_single sample_final_output generate_output _prepare_single_input _lexicalise_full_output _generate_output _generate_full_output _merge_str_ratings convert_idx2char get_discr_ratings_single attr_value_in_line train_discriminators load_discriminators last_one train_vanilla_model _get_lexicalize_dict _get_data normal ones randint vstack zeros fit items list format join replace write close zip append argmax enumerate predict open isinstance get_shape list constant read while_loop tuple transpose TensorArray expand_dims stack cast reverse step_function unstack bool range len ctc_beam_search_decoder to_int32 transpose ctc_greedy_decoder log SC_LSTM Model lstm items sorted list decoder sc_lstm_decoder concatenate Embedding one_hot_out_embeddings identity keys Model append Input max values len range conv_block_layered Model get_classifier_architecture Embedding one_hot_out_embeddings identity Model discriminator Input len append DictReader get open append _parse_single_mr strip find split append zip _delex_single list keys replace intersection tuple readlines dict open split items list defaultdict add _load_attributes join _get_delex_fields items list defaultdict sorted add enumerate join _delexicalise _read_data _load_attributes _parse_raw_mr _get_delex_fields append _sample_surface_features_for_mr list append tuple choice sample zeros _sample_formulation_for_feature max range values get items list concatenate tuple append zeros keys range len join dump format mkdir open _parse_raw_mr _sample_surface_feautres _vectorize_mrs _read_data get append zeros max values items list defaultdict get T append zeros max range values items list defaultdict append tokenize WordPunctTokenizer sent_tokenize load get list items concatenate tuple zip open zeros keys append len _utt_fw_features _get_formulation_for_feature _follow_fw_features info get ones len astype append max enumerate load join replace close open load join replace close open join dump format mkdir open join dump format mkdir open items list len zeros list items T list _compute_vector_length append keys _vectorize_single_mr update dict enumerate set _vectorize_mrs _load_delex_data info convert2indices max values int get items list format isInt int dict eval input len load config join NLGModel Flask run open items sorted list product tuple append list map _prepare_single_input zip append append predict tqdm load join append open items list map zip append argmax predict append get_discr_ratings_single enumerate tqdm append zip append max append choice get items list replace append _get_lexicalize_dict enumerate get items list replace append _get_lexicalize_dict enumerate load join load_discriminators format _compute_vector_length variable load_weights generator_model max open append join format close write _load_delex_fields join _print_full_output _lexicalise_output format get_discr_ratings prepare_input select_top_outputs sample_final_output generate_output _lexicalise_full_output mkdir writelines _generate_full_output _merge_str_ratings convert_idx2char open max zip load join list format items replace Adadelta zip name EarlyStopping fit mkdir get_semantic_classifier info ModelCheckpoint enumerate compile open load join list format items replace name load_weights get_semantic_classifier info open list items sorted append items list defaultdict variable TerminateOnNaN open LexFeatureOutputCallbackVanilla TensorBoard _get_data generator_model ceil _get_lexicalize_dict StepCallback _load_delex_fields info compile load join Adadelta summary ModelCheckpoint fit | # E2E NLG Code for the INLG 2018 conference paper [*Syntactic Manipulation for Generating more Diverse and Interesting Texts*](http://aclweb.org/anthology/W18-6503) # Setup & Requirements We assume an [Anaconda](https://www.anaconda.com/download/) installation. To install the Conda environment run: ``` $ conda env create -f environment.yml ``` This installs tensorflow-gpu==1.10.0, make sure that you have the CUDA environment installed accordingly. Refer to [this](https://www.tensorflow.org/install/install_sources#tested_source_configurations) for the compatibility. Next create some output directories, inside the main directory run the following commands: ``` | 2,479 |
jdigne/LPF | ['denoising'] | ['Sparse Geometric Representation Through Local Shape Probing'] | eigen3/debug/gdb/__init__.py eigen3/debug/gdb/printers.py eigen3/scripts/relicense.py EigenQuaternionPrinter lookup_function register_eigen_printers build_eigen_dictionary EigenMatrixPrinter update append strip_typedefs search tag target type | # Local Probing Fields Analysis Author: Julie Digne 2015-2020 julie 'dot' digne 'at' liris 'dot' cnrs 'dot' fr ## Description This code is an implementation of the paper: *Sparse Geometric Representation Through Local Shape Probing*, Julie Digne, Sébastien Valette, Raphaëlle Chaine, IEEE Transactions on Visualization and Computer Graphics, vol. 24, n. 7, pp2238-2250, July 2018. (The paper was presented at Symposium on Geometry Processing - SGP - 2018) * Project's webpage: https://perso.liris.cnrs.fr/julie.digne/articles/lpf.html * PDF paper: | 2,480 |
jeasung-pf/MORAN_v2 | ['scene text recognition'] | ['A Multi-Object Rectified Attention Network for Scene Text Recognition'] | tools/dataset.py demo.py models/moran.py models/morn.py test.py models/asrn_res.py inference.py tools/utils.py main.py create_dataset.py models/fracPickup.py createDataset writeCache checkImageIsValid Recognizer val trainBatch ResNet BidirectionalLSTM ASRN AttentionCell Attention Residual_block fracPickup MORAN MORN lmdbDataset randomSequentialSampler resizeNormalize averager loadData strLabelConverterForAttention get_torch_version imdecode fromstring IMREAD_GRAYSCALE join str print len writeCache range open data decode DataLoader max view add iter append encode next range cat BidirDecoder averager loadData size MORAN zip float criterion print min len criterion backward loadData MORAN zero_grad step encode next cat BidirDecoder copy_ get_torch_version split | # MORAN: A Multi-Object Rectified Attention Network for Scene Text Recognition  | <center>Python 2.7</center> | <center>Python 3.6</center> | | :---: | :---: | | <center>[](https://travis-ci.org/Canjie-Luo/MORAN_v2)</center> | <center>[](https://travis-ci.org/Canjie-Luo/MORAN_v2)</center> | MORAN is a network with rectification mechanism for general scene text recognition. The paper (accepted to appear in Pattern Recognition, 2019) in [arXiv](https://arxiv.org/abs/1901.03003), [final](https://www.sciencedirect.com/science/article/pii/S0031320319300263) version is available now. [Here is a brief introduction in Chinese.](https://mp.weixin.qq.com/s/XbT_t_9C__KdyCCw8CGDVA)  ## Recent Update - 2019.03.21 Fix a bug about Fractional Pickup. | 2,481 |
jeasung-pf/see | ['scene text detection', 'scene text recognition'] | ['SEE: Towards Semi-Supervised End-to-End Scene Text Recognition'] | utils/create_video.py chainer/insights/svhn_bbox_plotter.py chainer/functions/disable_shearing.py chainer/train_svhn.py datasets/fsns/transform_gt.py chainer/insights/lstm_per_step_plotter.py datasets/svhn/filter_large_images.py chainer/train_mnist.py chainer/metrics/svhn_ctc_metrics.py chainer/datasets/concatenated_dataset.py chainer/utils/crop_images.py chainer/metrics/ctc_metrics.py chainer/utils/baby_step_curriculum.py datasets/fsns/slice_fsns_dataset.py chainer/train_text_recognition.py datasets/fsns/download_fsns.py chainer/utils/dict_eval.py datasets/svhn/create_svhn_dataset.py datasets/fsns/extract_words.py datasets/svhn/create_svhn_csv_gt.py datasets/svhn/create_svhn_dataset_4_images.py chainer/text_recognition_demo.py datasets/svhn/prepare_svhn_crops.py chainer/insights/text_rec_bbox_plotter.py chainer/utils/logger.py chainer/commands/interactive_train.py datasets/fsns/swap_classes.py chainer/insights/fsns_bbox_plotter.py datasets/fsns/render_text_on_signs.py chainer/insights/visual_backprop.py datasets/svhn/svhn_dataextract_tojson.py chainer/metrics/softmax_metrics.py chainer/optimizers/multi_net_optimizer.py chainer/datasets/sub_dataset.py utils/show_progress.py chainer/metrics/lstm_per_step_metrics.py chainer/evaluation/evaluator.py chainer/utils/multi_accuracy_classifier.py chainer/models/fsns_resnet.py datasets/fsns/change_file_names.py chainer/functions/disable_translation.py chainer/utils/create_gif.py datasets/fsns/transform_back_to_single_line.py chainer/models/text_recognition.py chainer/insights/textrec_bbox_plotter.py chainer/utils/plotting.py chainer/models/fsns.py chainer/utils/train_utils.py chainer/train_fsns.py datasets/fsns/tfrecord_to_image.py chainer/functions/rotation_droput.py chainer/evaluate.py chainer/insights/bbox_plotter.py chainer/fsns_demo.py chainer/datasets/file_dataset.py chainer/metrics/loss_metrics.py chainer/metrics/textrec_metrics.py chainer/models/svhn.py chainer/metrics/svhn_softmax_metrics.py chainer/utils/datatypes.py chainer/utils/intelligent_attribute_shifter.py chainer/models/ic_stn.py strip_prediction extract_bbox get_class_and_module build_fusion_net create_network load_module build_recognition_net load_image build_localization_net strip_prediction extract_bbox get_class_and_module build_fusion_net create_network load_module build_recognition_net load_image build_localization_net log_postprocess mnist_accuracy mnist_loss log_postprocess log_postprocess InteractiveTrain open_interactive_prompt ConcatenatedDataset OpencvTextRecFileDataset TextRecFileDataset FileBasedDataset PaddableSubDataset split_dataset_random split_dataset_n split_dataset split_dataset_n_random SVHNEvaluator TextRecognitionEvaluator Evaluator FSNSEvaluator DisableShearing disable_shearing DisableTranslation disable_translation rotation_dropout RotationDropout BBOXPlotter FSNSBBOXPlotter LSTMPerStepBBOXPlotter SVHNBBoxPlotter TextRectBBoxPlotter TextRecBBOXPlotter VisualBackprop CTCMetrics LossMetrics PerStepLSTMMetric SoftmaxMetrics SVHNCTCMetrics SVHNSoftmaxMetrics TextRecCTCMetrics TextRectMetrics TextRecSoftmaxMetrics FSNSMultipleSTNLocalizationNet FSNSNet ResnetBlock FSNSRecognitionNet FSNSResnetReuseNet FSNSSoftmaxRecognitionNet FSNSSoftmaxRecognitionResNet FSNSSingleSTNLocalizationNet FSNSResNetLayers FSNSRecognitionResnet InverseCompositionalLocalizationNet SVHNRecognitionNet SVHNCTCRecognitionNet SVHNNet SVHNLocalizationNet TextRecognitionNet TextRecNet MultiNetOptimizer BabyStepCurriculum make_gif makedelta create_loop_header intToBin IntelligentAttributeShifter Logger Classifier LogPlotter AttributeUpdater get_definition_filepath EarlyStopIntervalTrigger add_default_arguments get_trainer FastEvaluatorBase get_concat_and_pad_examples concat_and_pad_examples TwoStateLearningRateShifter get_fast_evaluator get_definition_filename extract_words_from_gt get_image random_crop get_image_paths get_labels save_image find_font_size find_way_to_common_dir intersects intersects_bbox GaussianSVHNCreator intersection is_close overlap SVHNCreator BBox SVHNDatasetCreator get_images merge_bboxes enlarge_bbox DigitStructFile get_filter create_video make_video ProgressWindow ImageDataHandler ImageServer spec_from_file_location exec_module module_from_spec join format get_class_and_module model_dir eval build_fusion_net abspath load_module build_recognition_net to_gpu gpu build_localization_net append empty hstack reshape height clip width full update data reshape timesteps flatten shape get_array_module zip append split_axis separate softmax_cross_entropy data reshape accuracy timesteps flatten shape get_array_module zip append split_axis separate InteractiveTrain start Thread PaddableSubDataset len permutation len len permutation len int getdata write subtract_modulo copy getbbox crop join sorted print _make append compile snapshot observe_lr extend ProgressBar EarlyStopIntervalTrigger Trainer dump_graph Logger PrintReport add_argument join tqdm add split walk extend truetype multiline_textsize choice list height min choice width range join str format get_subdir save makedirs append extend len append split height width left overlap top height min extend width left label max top height width get_filter join extract_number list sorted ImageData print mkdtemp close NamedTemporaryFile path filter create_video append listdir max compile run join print close NamedTemporaryFile flush run | # SEE: Towards Semi-Supervised End-to-End Scene Text Recognition Code for the AAAI 2018 publication "SEE: Towards Semi-Supervised End-to-End Scene Text Recognition". You can read a preprint on [Arxiv](http://arxiv.org/abs/1712.05404) # Installation You can install the project directly on your PC or use a Docker container ## Directly on your PC 1. Make sure to use Python 3 2. It is a good idea to create a virtual environment ([example for creating a venv](http://docs.python-guide.org/en/latest/dev/virtualenvs/)) 3. Make sure you have the latest version of [CUDA](https://developer.nvidia.com/cuda-zone) (>= 8.0) installed 4. Install [CUDNN](https://developer.nvidia.com/cudnn) (> 6.0) 5. Install [NCCL](https://developer.nvidia.com/nccl) (> 2.0) [installation guide](https://docs.nvidia.com/deeplearning/sdk/nccl-archived/nccl_2212/nccl-install-guide/index.html) | 2,482 |
jeffheaton/t81_558_deep_learning | ['time series'] | ['Applications of Deep Neural Networks with Keras'] | py/mpg_server_1.py py/image_web_server_1.py py/image_server_1.py upload_image allowed_file send_index send_root upload_image allowed_file calc_mpg load preprocess_input read BytesIO img_to_array ANTIALIAS print secure_filename resize decode_predictions filename append expand_dims predict open json print append zeros float predict | # T81 558:Applications of Deep Neural Networks [Washington University in St. Louis](http://www.wustl.edu) Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/) **The content of this course changes as technology evolves**, to keep up to date with changes [follow me on GitHub](https://github.com/jeffheaton). * Section 1. Spring 2023, Monday, 2:30 PM, Location: TBD * Section 2. Spring 2023, Online # Course Description Deep learning is a group of exciting new technologies for neural networks. Through a combination of advanced training techniques and neural network architectural components, it is now possible to create neural networks that can handle tabular data, images, text, and audio as both input and output. Deep learning allows a neural network to learn hierarchies of information in a way that is like the function of the human brain. This course will introduce the student to classic neural network structures, Convolution Neural Networks (CNN), Long Short-Term Memory (LSTM), Gated Recurrent Neural Networks (GRU), General Adversarial Networks (GAN) and reinforcement learning. Application of these architectures to computer vision, time series, security, natural language processing (NLP), and data generation will be covered. High Performance Computing (HPC) aspects will demonstrate how deep learning can be leveraged both on graphical processing units (GPUs), as well as grids. Focus is primarily upon the application of deep learning to problems, with some introduction to mathematical foundations. Students will use the Python programming language to implement deep learning using Google TensorFlow and Keras. It is not necessary to know Python prior to this course; however, familiarity of at least one programming language is assumed. This course will be delivered in a hybrid format that includes both classroom and online instruction. # Textbook The complete text for this course is here on GitHub. This same material is also available in [book format](https://www.heatonresearch.com/book/applications-deep-neural-networks-keras.html). The course textbook is “Applications of Deep Neural networks with Keras“, ISBN 9798416344269. | 2,483 |
jeffkinnison/florin-iris | ['iris segmentation'] | ['Learning-Free Iris Segmentation Revisited: A First Step Toward Fast Volumetric Operation Over Video Samples'] | florin/get_params.py florin/utils.py segnet/timing.py osiris/timing.py florin/florin.py florin/timing.py setup_data.py florin/time_sweep.py osiris/write_imagelist.py main parse_args main parse_args main parse_args load_volume threshold_bradley_nd binarize imcomplement save_imgs summate integral_image add_argument ArgumentParser join basename format print output resize input parse_args imread walk imsave new_shape makedirs save_imgs tuple floor depth argmax binary_dilation regionprops all save_iris summate logical_and circle shape recover_parameters generate_binary_structure range asarray window_pupil concatenate integral_image astype t_iris copy label int uint8 load_volume t_pupil threshold_bradley_nd reshape window_iris min repeat save_pupil zeros binary_fill_holes parameter_file binary_erosion window cumsum arange max cumsum copy shape range len list asarray product reshape multiply reduce ravel shape meshgrid zeros sum array range len ones shape prod list asarray uint8 isinstance binarize reshape integral_image astype summate shape float round array join sorted glob squeeze copy zeros imread range len join imsave zfill range makedirs | # FLoRIN for Iris Segmentation This repository contains the code used in the paper "Learning-Free Iris Segmentation Revisited: A First Step Toward Fast Volumetric Operation Over Video Samples" published at the 2019 International Conference on Biometrics, Crete, Greece. Pre-print available at: https://arxiv.org/abs/1901.01575 ## Dependencies To run this code, the following dependencies must be met. ### FLoRIN - Python 3.4+ - numpy - scipy - scikit-image | 2,484 |
jejjohnson/uncertain_gps | ['gaussian processes'] | ['Accounting for Input Noise in Gaussian Process Parameter Retrieval', 'Disentangling Derivatives, Uncertainty and Error in Gaussian Process Models'] | scripts/numpyro_gp.py src/models/jaxgp/utils.py src/models/jaxgp/exact.py src/models/train_models.py src/models/jaxgp/loss.py src/models/jaxgp/kernels.py scripts/jax_gp.py scripts/luca_gp.py scripts/linearized_gp.py src/models/jaxgp/data.py setup.py src/models/pyro_zoo/pyro_zoo.py src/data/era5.py src/models/jaxgp/mean.py src/models/exact.py scripts/basic_gp.py src/models/gpy_zoo/gpy_zoo.py src/models/jaxgp/basic.py UploadCommand zero_mean ard_kernel soften softplus covariance_matrix marginal_likelihood rbf_kernel get_data exp_params nll_scratch gp_prior sqeuclidean_distance cholesky_factorization posterior main get_data main main optimize_hyperparams marginal_likelihood get_data SEkernel prior K plotPosterior posterior main cholfac mu model run_inference kernel get_data main predict main get_verify_data main GPRegressor train main get_data near_square_wave posterior predictive_variance gp_prior predictive_mean gram ard_kernel rq_kernel rbf_kernel manhattan_distance sqeuclidean_distance periodic_kernel marginal_likelihood zero_mean saturate cholesky_factorization get_factorizations main get_exactgp_model UploadCommand zero_mean ard_kernel soften softplus covariance_matrix marginal_likelihood rbf_kernel get_data exp_params nll_scratch gp_prior sqeuclidean_distance cholesky_factorization posterior main optimize_hyperparams marginal_likelihood get_data SEkernel prior K plotPosterior posterior cholfac mu model run_inference kernel predict get_verify_data GPRegressor train main get_data near_square_wave posterior predictive_variance gp_prior predictive_mean gram ard_kernel rq_kernel rbf_kernel manhattan_distance sqeuclidean_distance periodic_kernel marginal_likelihood zero_mean saturate cholesky_factorization get_factorizations main get_exactgp_model seed power linspace sin exp sqeuclidean_distance vmap cho_factor cho_solve T print cov_func mu_func dot gp_prior cholesky_factorization eye cho_solve cov_func mu_func eye cholesky_factorization cov_func mu_func eye subplots value_and_grad opt_init get_data posterior_vec list soften squeeze dloss sgd savefig partial plot tight_layout set sqrt vmap get_params print flatten jit train_step marginal_likelihood uniform range predict grad PRNGKey y_fun dict eye fill_between diag predictive_mean show rmsprop scatter trace legend predictive_variance pred_var_f hessian saturate T reshape dot near_square_wave pred_grad_f set_ylim vmap T size eye cholesky K solve_triangular mu solve_triangular K cholfac mu cholfac format inf print value_and_grad copy jit val_grad_fun range plot print squeeze gca scatter diagonal posterior fill_between optimize_hyperparams plotPosterior posterior prior power exp sample LogNormal MultivariateNormal kernel num_warmup time print num_samples MCMC NUTS print_summary run normal diag transpose inv matmul kernel sqrt clip percentile run_inference mean split retrieve Client get_verify_data optimize RandomState sort f rand fit mean_absolute_error r2_score mean_squared_error GPRegressor check_random_state randn sort f linspace diag get_factorizations dot cov_func get_factorizations T cov_func dot cho_solve diag get_factorizations mu_f cov_f logpdf reshape cov_func mu_func cholesky_factorization eye | # Input Uncertainty for Gaussian Processes * Author: J. Emmanuel Johnson * Email: [email protected] * Documentation: [jejjohnson.github.io/uncertain_gps](https://jejjohnson.github.io/uncertain_gps) * Repo: [github.com/jejjohnson/uncertain_gps](https://github.com/jejjohnson/uncertain_gps) --- <p> <center> <img src="docs/pics/gp_plot.png" width="400"/> <b>Caption</b>: A graphical model of a GP algorithm with the addition of uncertainty component for the input. | 2,485 |
jenniferbrennan/CountingDiscoveries | ['experimental design'] | ['Estimating the number and effect sizes of non-null hypotheses'] | sampling_utils.py FWER_utils.py otherEstimators.py estimator.py syntheticExperimentWrappers.py utils.py fit_KS estimateEntireLine_oneJob estimateEntireLine binarySearch KS_test estimateZeta_FWER estimateZeta_FWER_manyThresholds_parallel estimateZeta_FWER_manyThresholds mle boundNumberDiscoveries_DKW pValCalcNormal boundNumberDiscoveries_KR getSamples_binomial getSamples_gaussian getSamples_poisson getSamples_gaussianTwoSpike drawAndEstimate_continuousDist drawAndEstimate_GaussianTwoSpike construct_A_gaussian construct_A_gaussian_pdf get_counts construct_A_Bin construct_A_Poi append estimateEntireLine_oneJob seed binarySearch print exit log2 hypTest ceil fit_KS print get_counts sqrt log len Problem Minimize Variable cumsum print solve status norm_inf sum print sum len append estimateZeta_FWER Problem Minimize value Variable print solve shape range sort log floor range len sort sqrt floor range log len rvs list randn reshape min choice linspace max range len randn linspace choice rvs list reshape choice linspace max range poisson len rvs list print reshape choice linspace binomial range len seed construct_A_gaussian boundNumberDiscoveries_DKW getSamples_gaussianTwoSpike print construct_A_gaussian_pdf boundNumberDiscoveries_KR get_counts binarySearch mle sum max getSamples_binomial construct_A_gaussian arange print getSamples_gaussian estimateEntireLine construct_A_Bin construct_A_Poi max getSamples_poisson zeros sum range len cdf zeros range len zeros range pdf len cdf zeros range len cdf zeros range len | # Code for our paper, Estimating the Number and Effect Sizes of Non-Null Hypotheses This repository contains all the code to reproduce the figures in our paper, "Estimating the Number and Effect Sizes of Non-Null Hypotheses," including examples of its use on both real and synthetic data sets. Suppose you run an experiment and get many test statistics, with a known distribution (eg, perhaps the measurement noise is normal, or the measurements are binomial). The code in this repository can be used to estimate the fraction of effect sizes (true means) above a user specified threshold (or list of thresholds). The estimate returned by our algorithm is guaranteed not to exceed the true fraction with high probability (the user-specified `alpha`). We provide examples and code for Gaussian, binomial, and poisson test statistics. The estimator supports other single-parameter test statistics; you will need to add code for generating an appropriate matrix A into `utils.py` in order to support a new statistic. A note of caution: This estimator is sensitive to your specification of the test statistic distribution (gaussian, binomial, poisson, etc). Misspecifying the distribution, for example getting the wrong variance for the gaussian distribution, can produce very wrong answers. Be sure you examine your data to confirm that the hypothesized distribution is actually reasonable. ## Navigating this repository There is one Jupyter notebook for each figure in the paper. In addition, we provide the notebook `ComparingDiscretizations` to illustrate the time/accuracy tradeoffs when choosing how to discretize the real line for continuous test statistics. The code for our estimator is provided in `estimator.py`, with utility functions given in `utils.py`. There are several other Python files that implement baselines and provide scaffolding for synthetic experiments. ## Dependencies ### Python - python 3 | 2,486 |
jeromerony/augmented_lagrangian_adversarial_attacks | ['adversarial attack'] | ['Augmented Lagrangian Adversarial Attacks'] | attacks/original_fab.py plot_results_imagenet.py minimal_attack_cifar10.py models/imagenet.py minimal_attack_mnist.py plot_results_cifar10.py attacks/foolbox.py models/mnist.py compile_results.py minimal_attack_imagenet.py utils.py plot_results_mnist.py robust_accuracy_curve ead_attack FABAttack original_fab imagenet_model_factory IBP_large SmallCNN mean clone unique EADAttack PyTorchModel Misclassification norm clone attack_single_run_targeted flatten full_like float FABAttack range load normalize_model requires_grad_ eval load_state_dict Sequential Conv2d ReLU Flatten Linear | This repository contains the experiments for the paper "Augmented Lagrangian Adversarial Attacks" https://arxiv.org/abs/2011.11857. This **does not** contain the ALMA attack proposed in the paper, which is implemented in [adversarial-library](https://github.com/jeromerony/adversarial-library). ### Requirements - python 3.8 - matplotlib>=3.3 - pandas>=1.1 - pytorch>=1.6 - torchvision>=0.7 - tqdm - foolbox 3.2.1 - adversarial-library https://github.com/jeromerony/adversarial-library | 2,487 |
jeromerony/fast_adversarial | ['adversarial defense', 'adversarial attack'] | ['Decoupling Direction and Norm for Efficient Gradient-Based L2 Adversarial Attacks and Defenses'] | fast_adv/utils/visualization.py fast_adv/utils/__init__.py fast_adv/models/cifar10/wide_resnet.py fast_adv/models/mnist/small_cnn.py fast_adv/models/mnist/__init__.py fast_adv/defenses/cifar10.py examples/mnist_example.py fast_adv/attacks/ddn.py fast_adv/models/mnist/madry_tf.py fast_adv/defenses/cifar10_small.py fast_adv/attacks/deepfool.py fast_adv/attacks/__init__.py fast_adv/utils/utils.py fast_adv/models/cifar10/__init__.py fast_adv/attacks/deepfool_tf.py fast_adv/defenses/mnist.py fast_adv/attacks/carlini.py fast_adv/models/cifar10/small_cnn.py fast_adv/__init__.py fast_adv/models/cifar10/madry_tf.py setup.py fast_adv/attacks/ddn_tf.py CarliniWagnerL2 DDN cosine_distance quantization DDN_tf DeepFool DeepFoolTF Model SmallCNN wide_resnet BasicBlock NetworkBlock WideResNet Model SmallCNN NormalizedModel AverageMeter l2_norm requires_grad_ save_checkpoint squared_l2_norm VisdomLogger norm reduce_sum WideResNet list replace OrderedDict save cpu keys parameters view | ### Update 24-11-2020: the official implementation of DDN, compatible with more recent versions of PyTorch is now implemented in [adversarial-library](https://github.com/jeromerony/adversarial-library) ## About Code for the article "Decoupling Direction and Norm for Efficient Gradient-Based L2 Adversarial Attacks and Defenses" (https://arxiv.org/abs/1811.09600), to be presented at CVPR 2019 (Oral presentation) Implementation is done in PyTorch 0.4.1 and runs with Python 3.6+. The code of the attack is also provided on TensorFlow. This repository also contains an implementation of the C&W L2 attack in PyTorch (ported from Carlini's [TF version](https://github.com/carlini/nn_robust_attacks/blob/master/l2_attack.py)) For PyTorch 1.1+, check the pytorch1.1+ branch (`scheduler.step()` moved). ## Installation This package can be installed via pip as follows: ```pip install git+https://github.com/jeromerony/fast_adversarial``` ## Using DDN to attack a model ```python | 2,488 |
jerrylin1121/BCO | ['imitation learning'] | ['Behavioral Cloning from Observation'] | models/bco.py models/utils.py models/bco_cartpole.py BCO BCO_cartpole bias_initializer get_shuffle_idx weight_initializer append arange shuffle | # Behavioral Cloning from Observation [[Paper]](https://arxiv.org/abs/1805.01954) ## Update ### 2019/11/28: 1. Implement tensorflow 2.0 version and push to `tf2.0` branch ## Introduction This is an implementation of BCO in Tensorflow on [cartpole](https://gym.openai.com/envs/CartPole-v0/) environment. There are two phases in BCO: (1) Inverse dynamic model which experience in a self-supervised fashion. (2) Policy model which use behavioral cloning by observing the expert perform without actions and get the action by (1).  ## Algorithm As method above, there are two phases in BCO. In lines 5-9, phase 1, improving the inverse dynamic model. In lines 10-12, phase 2, improving the policy model by behavioral cloning. | 2,489 |
jerryspan/FacebookR | ['word embeddings'] | ['Social Emotion Mining Techniques for Facebook Posts Reaction Prediction'] | Scripts/data_types.py Scripts/mongodb.py Scripts/database_access.py DataStorage Post Comment Emotion Sentence MongodbStorage | # FacebookR ### Facebook Post Reactions dataset --- **Paper: Social Emotion Mining Techniques for Facebook Posts Reaction Prediction** (accepted at ICAART 2018) This dataset was created for a research project at the Department of Data Science and Knowledge Engineering (Maastricht University). The dataset contains facebook posts, their correlating comments, an emotion lexicon and labled sentences. ## Usage ### Database The database used in this project is **[MongoDB](https://www.mongodb.com/)**. The files in this repository are dump-files created by MongoDB. So, one can unzip the files, start MongoDB on your machine and use the following command to import the files in your MongoDB: ```bash mongorestore -d <name_of_the_database> <your_path_to_the_github_files> | 2,490 |
jessejhang/imv-lstm | ['time series'] | ['Exploring Interpretable LSTM Neural Networks over Multi-Variable Data'] | networks.py IMVFullLSTM IMVTensorLSTM | # IMV-LSTM Pytorch implementation of "Exploring Interpretable LSTM Neural Networks over Multi-Variable Data" https://arxiv.org/pdf/1905.12034.pdf # Content 1) Nasdaq dataset experiment 2) SML2010 dataset experiment 3) PM2.5 dataset experiment | 2,491 |
jessie0624/Automatic-Text-Summarization | ['text summarization'] | ['LCSTS: A Large Scale Chinese Short Text Summarization Dataset'] | 1_bertClassifcation.py simple_accuracy set_seed evaluate acc_and_f1 FaqProcessor convert_examples_to_features main train load_and_cache_examples join text_b InputFeatures encode_plus guid info append text_a enumerate len simple_accuracy f1_score recall_score precision_score seed manual_seed gradient_accumulation_steps model tuple clip_grad_norm_ zero_grad DataLoader max_grad_norm output_dir save list set_seed step logging_steps SummaryWriter format close save_pretrained num_train_epochs info trange max_steps enumerate int items join evaluate_during_training evaluate backward AdamW add_scalar makedirs RandomSampler tqdm parameters WarmupLinearSchedule load_and_cache_examples train_batch_size len argmax eval_batch_size update format join tuple len tqdm acc_and_f1 DataLoader eval numpy output_dir info append SequentialSampler load_and_cache_examples makedirs load join str format max_seq_length data_dir get_labels TensorDataset convert_examples_to_features save info tensor exists from_pretrained do_eval convert_one_example_to_features ArgumentParser device do_train output_dir save eval_all_checkpoints setLevel do_predict tensor basicConfig list set_seed len get_labels append parse_args to WARN range update _create_one_example save_pretrained info model_path checkpoint join evaluate print add_argument dict FaqProcessor train makedirs | # Automatic-Text-Summarization Now this task is on-going. I will update my progress here. - Step-1: Read text summarization paper and related blogs. The summary blog is on-going including seq2seq/pointer-generation and unilm.(WIP) - Step-2: Get Chinese text summarization data. (Done -- 11.29) LCSTS A Large Scale Chinese Short Text Summarization Dataset.You can get paper here: https://arxiv.org/abs/1506.05865. To get the data, you'd better sent application mail to the team. They are very nice, you will get data about 1 day later. - Step-3: Data process. (Done -- 12.03) I highly recommend you read the 'README_IMPORTANT.txt' and their paper, it will help you know well about the data. | 2,492 |
jessiedbq/Auto_Sci-master | ['time series'] | ['Fast Gaussian Process Based Gradient Matching for Parameter Identification in Systems of Nonlinear ODEs'] | auto_sci/examples/lotka_volterra.py auto_sci/experiments/simulation.py auto_sci/experiments/create_experiment.py DynamicalSystem LotkaVolterra | # Auto_Sci This repository contains code for the final project of Machine Learning @ NYU Spring 2019. Bingqian Deng [email protected] ## Paper The project aims to implement the algorithm FGPGM in the paper "Fast Gaussian Process Based Gradient Matching for Parameter Identification in Systems of Nonlinear ODEs" by Philippe Wenk, Alkis Gotovos, Stefan Bauer, Nico Gorbach, Andreas Krause and Joachim M. Buhmann. (http://arxiv.org/abs/1804.04378). ## Currently working Code Due to the difficulty of the project: system simulation + GP regression for time series + MCMC for Approximate Inference(consulted the author, he spent around 3 months to implement). Only GP regression for time series is finished. To run the GP regression for FHN system, just run the GP_FHN jupyter notebook in the the folder "examples" The code provided is written in Python 3.7.1, and relies on the following libraries: | 2,493 |
jewellsean/FastLZeroSpikeInference | ['time series'] | ['A log-linear time algorithm for constrained changepoint detection'] | python/FastLZeroSpikeInference/utils.py python/setup.py python/FastLZeroSpikeInference/fast.py examples/python/simple_example.py estimate_spike_paths estimate_spikes estimate_calcium get_cost update_path_stats arfpop_stats get_num_changepts POINTER c_int print data_as pointer ARFPOP_interface ascontiguousarray c_double maximum unique zeros c_bool POINTER c_int data_as FitSegmentModel_interface pointer ascontiguousarray c_double maximum zeros array update_path_stats print get_num_changepts estimate_spikes warn get_cost append append arfpop_stats | # FastLZeroSpikeInference: A package for estimating spike times from calcium imaging data using an L0 penalty  This package implements an algorithm for deconvolving calcium imaging data for a single neuron in order to estimate the times at which the neuron spikes. See [https://jewellsean.github.io/fast-spike-deconvolution/](https://jewellsean.github.io/fast-spike-deconvolution/) for tutorials and additional information. This algorithm solves the optimization problems ### AR(1) model <img src="math_figures/un-constr.png" alt="alt text" width="600" height="80"> for the global optimum, where y_t is the observed fluorescence at the tth timepoint. ### Constrained AR(1) model | 2,494 |
jeya-maria-jose/Derain_OUCD_Net | ['rain removal', 'single image deraining'] | ['Exploring Overcomplete Representations for Single Image Deraining using CNNs'] | train.py test.py val_data.py derain_mulcmp.py train_data.py utils.py print_filters.py perceptual.py OUCD OUCD_lite unet oucd_wo_msff_encoder LossNetwork kunetv2_morec TrainData validation to_psnr to_ssim_skimage print_log adjust_learning_rate save_image norm_ip norm_range ValData mse_loss split split clamp_ div_ to_psnr to_ssim_skimage len extend save_image sum enumerate format split range len print format print param_groups format | # Derain_OUCD_Net Official Pytorch Code for "Exploring Overcomplete Representations for Single Image Deraining using CNNs" - IEEE Journal of Selected Topics in Signal Processing [Paper](https://arxiv.org/pdf/2010.10661.pdf) ## Prerequisites - Python >= 3.6 - [Pytorch](https://pytorch.org/) >= 1.0 - Torchvision >= 0.2.2 - Numpy >= 1.14.3 <a href="https://pytorch.org/ "> Pytorch Installation </a> ### Datasets-Link: | 2,495 |
jeya-maria-jose/Overcomplete-Deep-Subspace-Clustering | ['medical image segmentation', 'semantic segmentation'] | ['KiU-Net: Towards Accurate Segmentation of Biomedical Images using Over-complete Representations'] | recon.py ORL/pretrain_orl_best.py ORL/ODSC-ORL.py COIL20/pretrain_coil20.py MNIST/pretrain_mnist.py MNIST/ODSC-mnist.py print_feat.py COIL20/ODSC-COIL20.py autoencoder default_list_reader rautoencoder train_ImageList train_loader add_noise to_img autoencoder custom_viz rautoencoder ConvAE newConvAE20 best_map post_proC err_rate thrC ConvAE orgConvAE20 test_face newConvAE20 overConvAE ae_feature_clustering overorgConvAE train_face next_batch newConvAE best_map post_proC err_rate ODSC thrC next_batch train_face test_facep test_face ae_feature_clustering ODSC train_face next_batch ConvAE test_face best_map post_proC err_rate thrC next_batch train_face newConvAE test_facep ConvAE test_face ae_feature_clustering overConvAE train_face next_batch newConvAE fromarray uint8 array img_augmentation open size view size randn list add_subplot tight_layout axis imshow set_size savefig figure range compute Munkres astype maximum shape unique zeros sum array range len sort astype argsort zeros abs range T fit dot sqrt eye SpectralClustering normalize abs max diag fit_predict svds best_map sum astype arange shuffle transform restore savemat dict save_model print reshape next_batch finetune_fit show subplot restore reconstruct tight_layout colorbar imshow title figure range min show subplot restore reconstruct print tight_layout colorbar shape imshow title figure range partial_fit max print squeeze min astype partial_fit initlization post_proC mean err_rate thrC median array append | # Overcomplete-Deep-Subspace-Clustering Official Tensorflow Code for the paper "Overcomplete Deep Subspace Clustering Networks" - WACV 2021 <a href="https://arxiv.org/abs/2006.04878"> Paper </a> # Introduction: Deep Subspace Clustering Networks (DSC) provide an efficient solution to the problem of unsupervised subspace clustering by using an undercomplete deep auto-encoder with a fully-connected layer to exploit the self expressiveness property. This method uses undercomplete representations of the input data which makes it not so robust and more dependent on pre-training. To overcome this, we propose a simple yet efficient alternative method - Overcomplete Deep Subspace Clustering Networks (ODSC) where we use overcomplete representations for subspace clustering. In our proposed method, we fuse the features from both undercomplete and overcomplete auto-encoder networks before passing them through the self-expressive layer thus enabling us to extract a more meaningful and robust representation of the input data for clustering. Experimental results on four benchmark datasets show the effectiveness of the proposed method over DSC and other clustering methods in terms of clustering error. Our method is also not as dependent as DSC is on where pre-training should be stopped to get the best performance and is also more robust to noise. <p align="center"> <img src="img/arch.png" width="800"/> </p> ## About this repo: | 2,496 |
jfc43/pixel-discretization | ['adversarial attack'] | ['Towards Evaluating the Robustness of Neural Networks'] | data-specific-discretization/GTSRB/generate_code.py data-specific-discretization/MNIST/pgd_attack.py data-specific-discretization/GTSRB/train_nat.py data-specific-discretization/MNIST/util.py data-specific-discretization/CIFAR-10/train_adv.py data-specific-discretization/MNIST/model.py color-depth-reduction/ImageNet/inception_resnet_v2.py data-specific-discretization/MNIST/generate_codes.py data-specific-discretization/Fashion-MNIST/CW_attack.py data-specific-discretization/ImageNet/util.py color-depth-reduction/Fashion-MNIST/eval.py data-specific-discretization/MNIST/train_nat.py color-depth-reduction/ImageNet/eval.py color-depth-reduction/GTSRB/train_nat.py color-depth-reduction/CIFAR-10/fetch_model.py data-specific-discretization/CIFAR-10/cifar10_input.py data-specific-discretization/GTSRB/eval.py color-depth-reduction/ImageNet/CW_attack.py data-specific-discretization/CIFAR-10/fetch_model.py color-depth-reduction/Fashion-MNIST/generate_codes.py data-specific-discretization/MNIST/CW_attack.py color-depth-reduction/ImageNet/input_data.py color-depth-reduction/CIFAR-10/pgd_attack.py color-depth-reduction/MNIST/generate_codes.py color-depth-reduction/GTSRB/train_adv.py data-specific-discretization/Fashion-MNIST/model.py color-depth-reduction/Fashion-MNIST/CW_attack.py data-specific-discretization/GTSRB/util.py data-specific-discretization/GTSRB/pgd_attack.py color-depth-reduction/CIFAR-10/train_adv.py data-specific-discretization/CIFAR-10/pgd_attack.py data-specific-discretization/GTSRB/CW_attack.py data-specific-discretization/CIFAR-10/eval.py data-specific-discretization/GTSRB/model.py data-specific-discretization/ImageNet/model.py color-depth-reduction/CIFAR-10/util.py data-specific-discretization/Fashion-MNIST/eval.py color-depth-reduction/CIFAR-10/cifar10_input.py color-depth-reduction/MNIST/train_nat.py color-depth-reduction/CIFAR-10/generate_code.py color-depth-reduction/MNIST/pgd_attack.py data-specific-discretization/MNIST/train_adv.py color-depth-reduction/GTSRB/eval.py data-specific-discretization/ImageNet/input_data.py color-depth-reduction/GTSRB/generate_code.py data-specific-discretization/ImageNet/inception_resnet_v2.py data-specific-discretization/CIFAR-10/train_nat.py data-specific-discretization/CIFAR-10/util.py data-specific-discretization/CIFAR-10/generate_code.py data-specific-discretization/Fashion-MNIST/train_adv.py color-depth-reduction/MNIST/eval.py color-depth-reduction/MNIST/util.py color-depth-reduction/Fashion-MNIST/model.py color-depth-reduction/GTSRB/util.py color-depth-reduction/Fashion-MNIST/util.py color-depth-reduction/Fashion-MNIST/train_nat.py color-depth-reduction/CIFAR-10/model.py data-specific-discretization/ImageNet/CW_attack.py color-depth-reduction/CIFAR-10/CW_attack.py data-specific-discretization/Fashion-MNIST/generate_codes.py color-depth-reduction/ImageNet/model.py data-specific-discretization/GTSRB/train_adv.py color-depth-reduction/Fashion-MNIST/pgd_attack.py data-specific-discretization/Fashion-MNIST/pgd_attack.py color-depth-reduction/GTSRB/model.py color-depth-reduction/ImageNet/util.py data-specific-discretization/CIFAR-10/model.py color-depth-reduction/CIFAR-10/eval.py data-specific-discretization/ImageNet/generate_codes.py color-depth-reduction/MNIST/CW_attack.py color-depth-reduction/GTSRB/pgd_attack.py data-specific-discretization/Fashion-MNIST/util.py data-specific-discretization/MNIST/fetch_model.py data-specific-discretization/GTSRB/gtsrb_input.py color-depth-reduction/MNIST/fetch_model.py data-specific-discretization/Fashion-MNIST/train_nat.py color-depth-reduction/GTSRB/gtsrb_input.py color-depth-reduction/GTSRB/CW_attack.py data-specific-discretization/MNIST/eval.py color-depth-reduction/MNIST/train_adv.py color-depth-reduction/MNIST/model.py color-depth-reduction/Fashion-MNIST/train_adv.py data-specific-discretization/ImageNet/eval.py color-depth-reduction/CIFAR-10/train_nat.py color-depth-reduction/ImageNet/generate_code.py data-specific-discretization/CIFAR-10/CW_attack.py data-specific-discretization/ImageNet/pgd_attack.py color-depth-reduction/ImageNet/pgd_attack.py DataSubset AugmentedCIFAR10Data CIFAR10Data AugmentedDataSubset CWAttack Model LinfPGDAttack preprocess CWAttack Model LinfPGDAttack preprocess CWAttack AugmentedGTSRBData AugmentedDataSubset GTSRBData DataSubset Model LinfPGDAttack preprocess CWAttack inception_resnet_v2_arg_scope inception_resnet_v2 inception_resnet_v2_base block8 block35 block17 load_dev_data load_test_data load_train_data Model LinfPGDAttack preprocess CWAttack Model LinfPGDAttack preprocess DataSubset AugmentedCIFAR10Data CIFAR10Data AugmentedDataSubset CWAttack KM KDEProximate Model LinfPGDAttack preprocess CWAttack KM KDEProximate Model LinfPGDAttack preprocess CWAttack KM KDEProximate AugmentedGTSRBData AugmentedDataSubset GTSRBData DataSubset Model LinfPGDAttack preprocess CWAttack KM KDEProximate inception_resnet_v2_arg_scope inception_resnet_v2 inception_resnet_v2_base block8 block35 block17 load_dev_data load_test_data load_train_data Model LinfPGDAttack preprocess CWAttack KM KDEProximate Model LinfPGDAttack preprocess reshape KDTree squeeze copy query shape append join astype append float open join int reader astype close append float next open join int reader astype close append float next open astype double kmedoids tolist norm ones append zeros argmax range | # Towards Understanding Limitations of Pixel Discretization Against Adversarial Attacks This project is for the paper [Towards Understanding Limitations of Pixel Discretization Against Adversarial Attacks](https://arxiv.org/pdf/1805.07816.pdf). Some codes are from [MNIST Challenge](https://github.com/MadryLab/mnist_challenge) and [CIFAR10 Challenge](https://github.com/MadryLab/cifar10_challenge). ## Preliminaries It is tested under Ubuntu Linux 16.04.1 and Python 3.6 environment, and requires tensorflow package to be installed: * [Tensorflow](https://www.tensorflow.org/install) * [scipy](https://github.com/scipy/scipy) * [sklearn](https://scikit-learn.org/stable/) * [numpy](http://www.numpy.org/) * [matlab-for-python](https://www.mathworks.com/help/matlab/matlab-engine-for-python.html) ## Downloading Datasets | 2,497 |
jfc43/robust-attribution-regularization | ['adversarial attack'] | ['Towards Evaluating the Robustness of Neural Networks'] | Fashion-MNIST/train_attribution.py Flower/flower_input.py Flower/ig_attack.py MNIST/simple_gradient_attack.py Flower/eval_attribution_attack.py GTSRB/pgd_attack.py Flower/train_nat.py Fashion-MNIST/model.py MNIST/ig_attack.py MNIST/train_nat.py Fashion-MNIST/eval_attribution_attack.py GTSRB/eval_attribution_attack.py GTSRB/simple_gradient_attack.py Fashion-MNIST/train_nat.py MNIST/utils.py Fashion-MNIST/pgd_attack.py MNIST/eval_pgd_attack.py GTSRB/gtsrb_input.py Fashion-MNIST/simple_gradient_attack.py Flower/eval_pgd_attack.py Flower/pgd_attack.py GTSRB/train_nat.py Flower/generate_data.py MNIST/train_attribution.py Flower/data_utils.py Flower/simple_gradient_attack.py Fashion-MNIST/eval_pgd_attack.py Fashion-MNIST/ig_attack.py Fashion-MNIST/utils.py Flower/model.py GTSRB/generate_data.py GTSRB/utils.py Flower/train_attribution.py Flower/utils.py MNIST/train_adv.py Flower/train_adv.py MNIST/model.py GTSRB/ig_attack.py MNIST/pgd_attack.py GTSRB/eval_pgd_attack.py GTSRB/train_adv.py Fashion-MNIST/train_adv.py MNIST/eval_attribution_attack.py GTSRB/model.py GTSRB/train_attribution.py IntegratedGradientsAttack Model LinfPGDAttack SimpleGradientAttack get_session dataReader plot softmax run_model compute_metrics integrated_gradients load_csv build_hdf5_image_dataset image_dirs_to_samples to_categorical random_sequence_from_string random_flip_leftright textfile_to_semi_redundant_sequences samplewise_std_normalization resize_image build_image_dataset_from_dir get_img_channel pad_sequences convert_color Preloader pil_to_nparray ImagePreloader load_image chars_to_dictionary featurewise_std_normalization get_std VocabularyProcessor string_to_semi_redundant_sequences directory_to_samples random_flip_updown shuffle LabelPreloader get_mean featurewise_zero_center samplewise_zero_center get_max image_preloader random_sequence_from_textfile DataSubset untar FlowerData reporthook load_data build_class_directories maybe_download translate_image projection_transform rotate_image augment_and_balance_data transform_image IntegratedGradientsAttack per_image_standardization Model LinfPGDAttack SimpleGradientAttack get_session dataReader plot softmax integrated_gradients translate_image projection_transform rotate_image augment_and_balance_data transform_image preprocess_data DataSubset GTSRBData image_brightness_normalisation IntegratedGradientsAttack per_image_standardization Model LinfPGDAttack SimpleGradientAttack get_session dataReader plot softmax integrated_gradients IntegratedGradientsAttack Model LinfPGDAttack SimpleGradientAttack get_session dataReader plot softmax run_model compute_metrics integrated_gradients exp max percentile set_bad arange astype axis rescale mean imshow xticks nan get_cmap abs yticks reshape read_data_sets labels expand_dims ConfigProto sum flatten intersect1d float abs len average loss_input_gradient output_input_gradient run asarray zeros max range len astype max enumerate len format print chars_to_dictionary append zeros range enumerate len lower read set randint len read directory_to_samples File size resize_image convert_color pil_to_nparray create_dataset load_image max range len load_image pil_to_nparray LabelPreloader directory_to_samples max ImagePreloader open save resize load list print directory_to_samples resize_image convert_color pil_to_nparray load_image enumerate load open bool getrandbits bool getrandbits list permutation array enumerate len range len range len mean std join sorted append next walk join build_image_dataset_from_dir maybe_download join untar urlretrieve print stat mkdir build_class_directories write join str rename mkdir range print extractall close open uniform rotate warpAffine uniform float32 estimate uniform ProjectiveTransform array warp translate_image shape projection_transform rotate_image list print reshape shape unique zip append empty full range ys xs FlowerData equalizeHist range image_brightness_normalisation len GTSRBData | # Robust Attribution Regularization This project is for the paper: [Robust Attribution Regularization](https://arxiv.org/abs/1905.09957). Some codes are from [MNIST Challenge](https://github.com/MadryLab/mnist_challenge), [CIFAR10 Challenge](https://github.com/MadryLab/cifar10_challenge), [Deep traffic sign classification](https://github.com/joshwadd/Deep-traffic-sign-classification), [tflearn oxflower17](https://github.com/tflearn/tflearn/blob/master/tflearn/datasets/oxflower17.py) and [Interpretation of Neural Network is Fragile](https://github.com/amiratag/InterpretationFragility). ## Introduction This project is to solve an emerging problem in trustworthy machine learning: train models that produce robust interpretations for their predictions. See the example below:  ## Preliminaries It is tested under Ubuntu Linux 16.04.1 and Python 3.6 environment, and requires some packages to be installed: * [Tensorflow](https://www.tensorflow.org/install) * [scipy](https://github.com/scipy/scipy) * [sklearn](https://scikit-learn.org/stable/) | 2,498 |
jhb86253817/tf-re-id | ['person re identification'] | ['Deep Person Re-Identification with Improved Embedding and Efficient Training'] | code/main.py code/process_viper.py utils/preprocess_market.py code/cnn.py code/train.py code/process_cuhk01.py utils/preprocess_cuhk01.py code/process_cuhk03.py cnn_fc_ic cnn_ic cnn_frw_ic max_pool conv2d cnn_i bias_variable cnn_iv center_loss generate_cuhk01 generate_cumarket flip trans generate_cuhk03 flip trans generate_cumarket flip trans generate_viper negative_batch negative_batch_ft train next_batch_single next_batch_ft_single eval next_batch_ft_pair positive_batch positive_batch_ft labels_statistics next_batch_pair constant reshape arg_max scatter_sub gather l2_loss softmax_cross_entropy_with_logits batch_norm reshape maximum matmul max_pool conv2d reduce_mean bias_variable l2_loss get_variable softmax_cross_entropy_with_logits batch_norm reshape maximum matmul max_pool center_loss conv2d reduce_mean bias_variable l2_loss get_variable softmax_cross_entropy_with_logits batch_norm reshape maximum matmul max_pool center_loss conv2d reduce_mean square bias_variable l2_loss get_variable softmax_cross_entropy_with_logits batch_norm reshape maximum matmul max_pool center_loss conv2d reduce_mean bias_variable l2_loss get_variable softmax_cross_entropy_with_logits batch_norm relu reshape maximum matmul max_pool conv2d reduce_mean bias_variable l2_loss get_variable copy randint copy concatenate sorted concatenate print reshape set mean array append imread listdir flip range trans len seed sorted list print reshape choice append imread listdir array range len load int seed sorted concatenate reshape len choice mean array append imread listdir flip range trans open seed sorted list print reshape choice append imread listdir array range list concatenate zeros choice append randint array range len positive_batch negative_batch concatenate list zeros choice append randint range len int list zeros choice append randint range len list concatenate choice append zeros array range positive_batch_ft negative_batch_ft concatenate list choice append zeros range int list choice append zeros range list reshape Counter argmax array list sorted range Saver exponential_decay generate_viper seed cnn_fc_ic cnn_frw_ic generate_cuhk03 placeholder cnn_ic generate_cuhk01 cnn_i minimize print Variable float32 AdamOptimizer int32 global_variables_initializer cnn_iv array generate_cumarket len | # Person Re-Identification in TensorFlow
This is code of the paper ["Deep Person Re-Identification with Improved Embedding and Efficient Training"](https://arxiv.org/abs/1705.03332).
## Datasets
- [cuhk03](http://www.ee.cuhk.edu.hk/~rzhao/)
- [cuhk01](http://www.ee.cuhk.edu.hk/~rzhao/)
- [viper](https://vision.soe.ucsc.edu/node/178)
- [market1501](http://www.liangzheng.org/Project/project_reid.html)(for pre-training, v15.09.15 is used in this paper)
| 2,499 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.