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
|
---|---|---|---|---|---|
breizhn/DTLN-aec | ['data augmentation'] | ['Acoustic echo cancellation with the dual-signal transformation LSTM network'] | run_aec.py process_file process_folder read replace concatenate get_input_details get_tensor get_output_details astype write invoke set_tensor zeros abs max range irfft len join replace endswith print len Interpreter process_file allocate_tensors range walk append makedirs | # DTLN-aec This Repostory contains the pretrained DTLN-aec model for real-time acoustic echo cancellation in TF-lite format. This model was handed in to the acoustic echo cancellation challenge ([AEC-Challenge](https://www.microsoft.com/en-us/research/academic-program/acoustic-echo-cancellation-challenge-icassp-2021/)) organized by Microsoft. The DTLN-aec model reached the 3rd place. The results of the AEC-Challenge can be found [here](https://www.microsoft.com/en-us/research/academic-program/acoustic-echo-cancellation-challenge-icassp-2021/results/). The model was trained on data from the [DNS-Challenge](https://github.com/microsoft/AEC-Challenge) and the [AEC-Challenge](https://github.com/microsoft/DNS-Challenge) reposetories. The arXiv preprint can be found [here](https://arxiv.org/pdf/2010.14337.pdf). Please cite: ```bitbtex @INPROCEEDINGS{westhausen21_dtln_aec, author={Westhausen, Nils L. and Meyer, Bernd T.}, booktitle={ICASSP 2021 - 2021 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)}, title={{Acoustic Echo Cancellation with the Dual-Signal Transformation LSTM Network}}, | 1,600 |
brejchajan/LandscapeAR | ['patch matching'] | ['LandscapeAR: Large Scale Outdoor Augmented Reality by Matching Photographs with Terrain Models Using Learned Descriptors'] | python/sfm/Matcher.py python/trainPatchesDescriptors.py python/flickr/FlickrPrefs.py python/setup.py python/plotComparison.py python/pose_estimation/PoseFinder.py python/pose_estimation/KeypointDetector.py python/pose_estimation/BundleAdjustment.py python/training/Architectures.py python/training/CachedMultimodalPatchesDataset.py python/flickr/getFlickrPhotosInfo.py python/sfm/FeatureExtractor.py python/plotTensorboardHist.py python/hpatches_extract.py python/pypnp/testapp.py python/exportONNX.py python/pose_estimation/eulerZYZ.py python/visualization/drawMatches.py python/findPose.py python/training/MultimodalPatchesDatasetAll.py python/pose_estimation/VideoPoseFinder.py python/gp3K_atm.py python/training/PositionalDatasetSampler.py python/flickr/Places365Classifier.py python/onnxToCoreML.py python/sfm/matching.py python/genPatchesDataset.py python/analyzeMatches.py python/training/MultimodalPatchesDataset.py python/getPoseResults.py python/export/ModelExporter.py python/render_panorama.py python/pose_estimation/patchSamplingDepth.py python/findPoseVideo.py python/training/LossesAdobetrips.py python/pypnp/p4pf.py python/ransac/LineEstimator.py python/pose_estimation/EstimatePose.py python/ransac/Ransac.py python/genSets.py python/pose_estimation/FUtil.py python/ransac/EPNPEstimator.py python/sfm/database.py python/pypnp/P4PfEstimator.py python/flickr/flickrAlbumDownload.py buildArgumentParser main buildArgumentParser main PatchesDatasetCreator generateSets main buildArgumentParser movePoseToCenter calculatePosErrAlongCameraAxis plotCumulativeHistogram getPoseCenter getResults getResultForImage getTimestampForImage getGPSPose buildArgumentParser getRenderedPose getGroundTruthPose angles_to_xml printPercentageBarPlot plotRotationErrorPlot plotDatasetMethodComparisonInliers plotTranslationErrorPlotRefinedAndBestPose plotDatasetMethodComparison plotTranslationErrorPlotNoisyPositions plotRotationErrorPlotRefinedAndBestPose plotRotationErrorTable plotDatasetMethodComparisonInliersMonth plotTranslationErrorPlot plotNoisyPercentage plotTranslationErrorTable findBestTFEvents plotHistogram plotHistogramsTFEvents convertHistogram buildArgumentParser renderPanorama checkImagesAlreadyRendered ModelExporter copyPhotosToReconstructionDir addItemsToDict getPhotosets classifyPhotos calculateStatistics showDatasetImagesLargerThanThreshold histoNumPhotosInAlbum putInformationToPhotosInSingleDataset downloadPhotos createSinglePhotoset getPhotoset histoFracOutdoorAndNatural getClassificationFileName showDatasetImagesLowerThanThreshold downloadExif putLocationToPhoto prepareDataForReconstruction searchAndDownloadPhotosInGeoCircle haversineDist purge downloadLocationDataForSingleDataset histoFractionPhotosWithGPSinAlbum getExifDataFileName histoLocationAccuracy main downloadLocationData getLocationForPhotoId searchAndDownloadPhotosInGeoCircleWithCount show_images histoAttributes getSuffixFileName putExifToPhoto writeCommandExiftool histoNumAlbumsUser getLocationFileName downloadPhoto putInformationToPhotosInPhotoset buildArgumentParser searchPhotos FlickrPrefs buildArgumentParser main getInfoForPhotos printLicenses Places365Classifier bundle_adjustment_sparsity fun bundleAdjustment rotate project solveP4PfRansac poseFrom2D3DWithFOV poseFrom2D3DWithFOVEPNPOurRansac poseEPNPBAIterative poseFrom2D3D poseFrom2D3DP4Pf poseFromMatches solveEPNPRansac inZero2Pi rotationZ angles rotationY matrix rot_matrix rotationX vec intrinsicsToFov loadMatrixFromFile projectiveToFOV fromTwoCameras projectiveToIntrinsics getRotScale fovToIntrinsics KeypointDetector getSizeFOV project genRandomCorrespondingPoints2D unproject_image getPatches findIndicesOfCorresponding3DPoints projectWithIntrinsics calculateDistances3D savePointCloudToPly generatePatchesFast generatePatchesFastImg unproject loadDepth projectWithIntrinsicsAndZ generatePatches generatePatchesFastImgNoscale generatePatchesImgScale findIndicesOfCorresponding3DPointsWithDist showNegatives generatePatchesImg PoseFinder PoseFinderArgs VideoPoseFinder p4pf getRigidTransform2 P4PfEstimator EPNPEstimator LineEstimator testLineFit samplePointsOnLineGaussianNoise Ransac example_usage COLMAPDatabase blob_to_array image_ids_to_pair_id pair_id_to_image_ids array_to_blob CrossDomainFeatureExtractor FeatureExtractor D2NetFeatureExtractor SpatialMatcher Matcher ExhaustiveMatcher buildArgumentParser MultimodalPatchNet5lShared2lFCN MultimodalKeypointPatchNet5lShared2l SimplePatchNet MultimodalHardNetShared3l MultimodalPatchNet5lShared2lPhotoONNX MultimodalPatchNet5lShared2lRenderONNX MultimodalPatchNet MultimodalResNetShared2l MultimodalVGG16HardNetShared3l PatchNetBN5l weights_init LockedSinglemodalVGG16FinetunedShared3l MultimodalPatchNet5lShared2l8CH L2Norm OriginalHardNet SimplePatchNet5l SimpleResNet MultimodalKeypointPatchNet5lShared2lFCN SinglemodalHardNet3l HardNet MultimodalResNet50 SimplePatchNet5l8CH MultimodalPatchNet5lShared2l MultimodalPatchNet5lShared2lBN MultimodalPatchesCache CachedMultimodalPatchesDataset loss_HardNetNeg loss_random_sampling loss_HardNetWithDist distance_matrix_vector_negative global_orthogonal_regularization loss_HardNet loss_HardNetNegShow select_HardNetMultimodal distance_matrix_vector loss_L2Net distance_vectors_pairwise plotSample MultimodalPatchesDataset loadListFile plotSampleBatched MultimodalPatchesDatasetAll PositionalDatasetSampler drawMatches add_argument ArgumentParser processVideo VideoPoseFinder print PatchesDatasetCreator createDataset buildArgumentParser parse_args join isdir print tqdm isfile append listdir patches_dataset_path generateSets setname rendered_dataset_path dot loadMatrixFromFile join dot isdir join getSceneCenter movePoseToCenter glob loadMatrixFromFile join getSceneCenter movePoseToCenter loadMatrixFromFile projectiveToIntrinsics dot imread dot norm concatenate transpose inv copy dot array load intrinsicsToFov join norm movePoseToCenter calculatePosErrAlongCameraAxis findBestPose loadtxt dot parseInfoFile getGPSPose isfile calculateErrors array getRenderedPose getGroundTruthPose plot cumsum print insert astype isnan histogram float glob join arange grid pi flatten abs show plotCumulativeHistogram set_yscale ylabel title scatter savefig savetxt legend append gca getTimestampForImage range plot directory concatenate month astype original_images mean dataset_dir listdir matching_dir_name join isdir print xlabel getResultForImage tqdm hist figure int32 array len print str float rot_matrix arange grid xticks yticks subplot plotCumulativeHistogram getcwd len ylabel shape title savetxt savefig legend gca tight_layout join print loadtxt xlabel figure isfile makedirs arange grid xticks subplot getcwd len ylabel shape title savetxt savefig legend gca append range plot tight_layout mean join int print loadtxt xlabel figure isfile array makedirs arange grid flatten xticks yticks subplot getcwd set_yscale len ylabel title savetxt scatter savefig legend gca tight_layout mean join print loadtxt xlabel figure isfile median makedirs arange xticks round max yticks str logical_and ylabel bar legend append sum range tight_layout int print text xlabel tqdm figure array join arange cumsum loadtxt print astype set_printoptions isnan figure histogram float max join arange print loadtxt cumsum astype set_printoptions isnan figure histogram float max join arange plotCumulativeHistogram loadtxt xlabel grid ylabel tight_layout savefig figure legend xticks yticks join arange plotCumulativeHistogram loadtxt xlabel grid ylabel tight_layout savefig figure legend xticks yticks join arange plotCumulativeHistogram loadtxt xlabel grid ylabel tight_layout savefig figure legend xticks yticks join arange plotCumulativeHistogram loadtxt xlabel grid ylabel tight_layout savefig figure legend xticks yticks join arange plotCumulativeHistogram loadtxt print grid xlabel ylabel tight_layout shape savefig figure legend xticks sum printPercentageBarPlot join print loadtxt hist savefig figure int floor append sum array range load plot cumsum min astype histogram float value print cumsum bucket step bucket_limit sum array convertHistogram summary_iterator value isinstance plot print cumsum bucket bucket_limit legend array convertHistogram summary_iterator glob join add_noise str normal with_egl earth_file checkImagesAlreadyRendered print resolution system uniform output_directory vreckon update getList add set range len update add getInfo set update getPhotoset int str fromtimestamp mktime print min search timetuple searchAndDownloadPhotosInGeoCircle year update join int str Places365Classifier basename move print len search dirname downloadPhoto range exists makedirs update int str print search getPhotosets range len str join urlretrieve print makedirs join dirname makedirs print xlabel ylabel title hist array str arange xlabel min ylabel title hist array max arange print xlabel ylabel title getLocationFileName hist array downloadLocationData xlabel ylabel title hist getLocationFileName array radians cos atan2 sqrt sin xlabel getClassificationFileName ylabel title hist array arange xticks sorted list getClassificationFileName ylabel bar title set_color legend gca append range update Places365Classifier mean items print xlabel Patch array show histoNumPhotosInAlbum histoAttributes histoFractionPhotosWithGPSinAlbum add_subplot histoFracOutdoorAndNatural histoNumAlbumsUser figure histoLocationAccuracy splitext load close getLocationFileName isfile open getLocation load close getLocationFileName isfile open append update suptitle set_xticklabels set_yticklabels add_subplot axis subplots_adjust gray imshow figure zip ceil float enumerate len getClassificationFileName Places365Classifier dirname join getClassificationFileName dirname array makedirs join getClassificationFileName dirname array makedirs getExif print join isdir print putExifToPhoto downloadExif getLocationFileName putLocationToPhoto dirname listdir exists join isdir print putExifToPhoto downloadExif getLocationFileName putLocationToPhoto dirname listdir join remove listdir search join purge copy dirname isfile listdir makedirs print getLocationFileName getClassificationFileName join searchAndDownloadPhotosInGeoCircleWithCount basename longitude downloadLocationDataForSingleDataset putInformationToPhotosInSingleDataset photos_count latitude output_directory radius update print tqdm getInfo split update int print tqdm getInfo range len printLicenses names getInfoForPhotos output_file license database cos sin sum rotate reshape ravel project size range arange lil_matrix subplot time format plot concatenate print reshape hstack fun least_squares shape figure append ravel array range len int arctan2 ones print poseFrom2D3DWithFOV astype bundleAdjustment fovToIntrinsics sum array reshape hstack Ransac P4PfEstimator run reshape hstack Ransac EPNPEstimator run int solveP4PfRansac astype int fovToIntrinsics solveEPNPRansac astype int print reshape astype solvePnP fovToIntrinsics solvePnPRansac array reshape projectiveToIntrinsics zeros solvePnPRansac array concatenate transpose findFundamentalMat dot recoverPose append range FM_RANSAC cos sin cos sin cos sin inZero2Pi rotationZ arctan2 reshape transpose dot rotationY item tan array arctan2 array pi arctan norm array tile dot transpose array write array describe concatenate concatenate ones reshape transpose inv astype projectiveToIntrinsics hstack dot dot transpose sum dot transpose sum dot transpose projectiveToIntrinsics meshgrid hstack linspace unproject kneighbors arange fit kneighbors arange fit int all arange concatenate astype shuffle pi int concatenate astype float32 pi copy pad vstack resize append range int pi int concatenate astype float32 copy getSizeFOV pad vstack resize append range int astype float32 pad vstack int subplot rand astype min copy float32 imshow pad scatter figure resize ceil max range append int subplot reshape rand astype min pi imshow pad scatter sqrt figure resize append zeros max range rand axis pi resize max subplot transpose imshow pad scatter append range astype ascontiguousarray sqrt int reshape min float32 figure zeros norm show subplot rand imshow scatter figure range len timer resize show list genRandomCorrespondingPoints2D unproject_image findIndicesOfCorresponding3DPoints shape imread range loadMatrixFromFile savePointCloudToPly generatePatchesFast splitext loadDepth float flip generatePatches int print projectiveToFOV tqdm sub svd det reshape transpose sign dot diag getRigidTransform2 ones reshape zeros eig hstack transpose range dot sqrt real append power sum array imag len reshape uniform randn show plot print transpose Ransac shape samplePointsOnLineGaussianNoise scatter vstack figure LineEstimator array run commit database_path float64 rand ArgumentParser add_keypoints exists add_matches connect parse_args next close create_tables execute add_image remove print add_argument dict add_camera blob_to_array randint data constant isinstance orthogonal Conv2d unsqueeze reshape sqrt sum exp print clamp min exit mean distance_vectors_pairwise exp print type_as exit mean distance_matrix_vector ge sum cuda diag clamp norm distance_matrix_vector_negative min clf max subplot squeeze colorbar imshow append to range nonzero float reshape pause draw min figure distance_matrix_vector numpy diag clf gather max subplot exp view squeeze transpose exit colorbar imshow to range detach nonzero float norm print sort pause type_as min draw clamp distance_matrix_vector numpy diag clf gather cuda subplot exp view squeeze transpose exit imshow mean float print sort pause type_as min draw clamp hist distance_matrix_vector numpy diag distance_matrix_vector_negative clf gather cuda subplot exp view squeeze transpose exit imshow append range cat mean print sort pause min draw clamp hist distance_matrix_vector numpy diag mul clamp size mean pow sum show subplot imshow figure range show subplot make_grid axes set_axis_off set_xlim add_subplot transpose imshow scatter figure numpy max range set_ylim isfile hasattr line ones tuple astype type array circle | [](https://paperswithcode.com/sota/patch-matching-on-hpatches?p=landscapear-large-scale-outdoor-augmented) # LandscapeAR: Large Scale Outdoor Augmented Reality by Matching Photographs with Terrain Models Using Learned Descriptors This repository contains official implementation of the ECCV 2020 LandscapeAR paper. If you use this code in a scientific work, please, cite it: ``` Brejcha, J., Lukáč, M., Hold-Geoffroy, Y., Wang, O., Čadík, M.: LandscapeAR: Large Scale Outdoor Augmented Reality by Matching Photographs with Terrain Models Using Learned Descriptors, In: 16th European Conference on Computer Vision (ECCV), 2020. ``` | 1,601 |
bremen79/cocob | ['stochastic optimization'] | ['Training Deep Networks without Learning Rates Through Coin Betting'] | mnist/mnist_fully_connected.py mnist/input_data.py optimizer/cocob_optimizer.py optimizer/__init__.py main bias_variable weight_variable COCOB truncated_normal constant softmax_cross_entropy_with_logits relu minimize equal float32 placeholder matmul reduce_mean cast bias_variable argmax read_data_sets weight_variable | # COCOB TensorFlow implementation of COCOB from the paper **[Backprop without Learning Rates Through Coin Betting](https://arxiv.org/abs/1705.07795)** Francesco Orabona and Tatiana Tommasi https://arxiv.org/abs/1705.07795 ### Description COntinuous COin Betting (COCOB) is a novel algorithm for stochastic subgradient descent (SGD) that does not require any learning rate setting. Contrary to previous methods, we do not adapt the learning rates, nor we make use of the assumed curvature of the objective function. Instead, we reduce the optimization process to a game of betting on a coin and obtain a learning rate free procedure for deep networks. | 1,602 |
brendenpetersen/deep-symbolic-regression | ['combinatorial optimization'] | ['Symbolic Regression via Neural-Guided Genetic Programming Population Seeding'] | dso/dso/task/regression/regression.py dso/dso/library.py dso/dso/language_model/language_model_prior.py dso/dso/run.py dso/dso/task/control/scripts/policy_eval.py dso/dso/task/__init__.py dso/dso/language_model/model/model_dyn_rnn.py dso/dso/task/regression/sklearn.py dso/dso/baselines/constraints.py dso/dso/test/custom_tasks/custom_task_prior.py dso/dso/utils.py dso/dso/task/control/envs/test/test_envs.py dso/dso/prior.py dso/dso/program.py dso/dso/test/generate_test_data.py dso/dso/task/control/scripts/benchmark_zoo.py dso/dso/logeval.py dso/dso/execute.py dso/dso/gp/gp_controller.py dso/dso/baselines/eureqa/run_eureqa.py dso/dso/train_stats.py dso/dso/task/control/__init__.py dso/setup.py dso/dso/task/control/control.py dso/dso/test/test_prior.py dso/dso/const.py dso/dso/gp/base.py dso/dso/task/regression/test_sklearn.py dso/dso/task/task.py dso/dso/task/control/scripts/sample_zoo.py dso/dso/task/control/envs/continuous_cartpole.py dso/dso/test/custom_tasks/test_custom_task_prior.py dso/dso/test/test_core.py dso/dso/gp/utils.py dso/dso/task/control/envs/test/test_lander.py dso/dso/train.py dso/dso/core.py dso/dso/functions.py dso/dso/task/control/envs/cartpole_bullet.py dso/dso/task/control/envs/lander.py dso/dso/test/test_constant.py dso/dso/config/__init__.py dso/dso/task/control/envs/pendulum.py dso/dso/language_model/__init__.py dso/dso/memory.py dso/dso/tf_state_manager.py dso/dso/controller.py dso/dso/subroutines.py dso/dso/baselines/gpsr.py dso/dso/task/regression/dataset.py dso/dso/__init__.py dso/dso/variance.py dso/dso/test/test_multiobject.py dso/dso/task/control/utils.py make_const_optimizer ScipyMinimize ConstOptimizer Dummy Controller LinearWrapper DeepSymbolicOptimizer python_execute cython_execute protected_div protected_n3 protected_n4 protected_sigmoid protected_exp protected_log protected_inv n3 create_tokens sigmoid logabs harmonic protected_n2 expneg protected_sqrt n4 protected_expneg Library Token TokenNotFoundError HardCodedConstant PlaceholderConstant main LogEval make_queue UniqueQueue ItemContainer UniquePriorityQueue get_samples Queue ProgramQueueMixin Constraint ConstConstraint LanguageModelPrior NoInputsConstraint LengthConstraint JointPrior RelationalConstraint InverseUnaryConstraint Prior RepeatConstraint SoftLengthPrior make_prior UniformArityPrior TrigConstraint _finish_tokens from_str_tokens from_tokens build_tree convert_to_sympy Node Program main train_dso print_summary get_position parents_siblings jit_parents_siblings_at_once jit_check_constraint_violation_descendant_no_target_tokens ancestors get_mask jit_check_constraint_violation jit_check_constraint_violation_descendant_with_target_tokens jit_check_constraint_violation_uchild make_state_manager HierarchicalStateManager StateManager work learn hof_work pf_work StatsLogger safe_update_summary empirical_entropy is_float is_pareto_efficient import_custom_source weighted_quantile safe_merge_dicts get_duration get_human_readable_time cached_property quantile_variance make_check_num_const check_inv check_const make_check_max_len make_check_min_len check_trig GP get_project evaluate work get_dataset main get_model start_client get_base_model load_config load_config get_base_config _eval_step RunOneStepAlgorithm GPController tokens_to_DEAP staticLimit DEAP_to_tokens cxOnePoint create_primitive_set individual_to_dso_aps rename_token multi_mutate DEAP_to_padded_tokens LanguageModelPrior LanguageModel make_task SequentialTask Task HierarchicalTask set_task ControlTask TimeFeatureWrapper load_default_model load_model RenderEnv CustomCartPoleContinuousBulletEnv CustomCartPoleBulletEnv CustomCartPoleContinuousEnv CustomLunarLander demo_heuristic_lander ContactDetector heuristic angle_normalize CustomPendulumEnv setup_envs_run_rollouts main main get_env_info Model main BenchmarkDataset main make_regression_metric RegressionTask DeepSymbolicRegressor test_task model main test_constant test_regression_with_hard_coded_constants test_task cached_results test_model_parity model test_multiobject_relational test_multiobject_output test_multiobject_repeat test_multiobject_trig test_multiobject_length model test_state_checker test_child test_repeat make_sequence test_trig make_testing_message make_failed_message test_const test_uchild test_inverse test_descendant assert_is_violation_false make_batch test_no_inputs assert_valid assert_invalid test_length assert_is_violation_true test_sibling pre_assert_is_violation CustomTask CustomPrior test_custom_prior test_custom_task append token pop array all Token format is_float HardCodedConstant PlaceholderConstant append range analyze_log LogEval ProgramQueue Batch pop items validate format list prior_class isinstance join print describe JointPrior import_custom_source append __name__ input_tokens n_objects cumsum choice append argmax array isinstance const_token is_float from_tokens index set_constants lower append float array split tostring _finish_tokens Program pop arity repr capitalize Node append range append children Node pop make deepcopy format time join print DeepSymbolicOptimizer train print print_summary join format argv print cpu_count strftime imap_unordered append train_dso Pool load_config enumerate shape prange full range max shape full range len shape prange range zeros shape range zeros ones int range len shape range shape range a_in_b a_not_in_b shape range a_in_b a_not_in_b shape range a_in_b pop manager_class r trainable_variables save_results print_var_means iter_in_order max clip run str list compress train_step Batch make_queue apply_along_axis save_stats append sum stochastic compute_probs sample_batch push_batch update range report_constraint_counts format concatenate close set sample float pqt_batch_size get_duration zeros enumerate int time pqt_k evaluate StatsLogger print r weighted_quantile any repeat get_rewards quantile gp_controller global_variables_initializer quantile_variance push_best array print_stats len float sum any arange zeros argsort cumsum argmax count_nonzero unique len divmod get deepcopy list items isinstance Mapping set_index concat to_csv isfile DataFrame read_csv match import_module getattr split int concatenate print exit weighted_quantile compute_probs repeat get_rewards quantile sample sum array range append len print enumerate print enumerate print enumerate format get_project evaluate solutions print expression get_model DataFrame get_base_model join T format var replace lambdify f_hat mean dirname read_csv print Client join dirname read_csv start list unlock_holdout get_dataset get get_models train get_result_when_complete items list set_parameter get_result_when_complete start_advanced_tuning_session run get_project work to_csv id delete get_models read_csv isfile start_client range safe_merge_dicts get_base_config isinstance r from_tokens list defaultdict ret len choice append searchSubtree range enumerate mutUniform mutShrink randint mutNodeReplacement mutInsert input_tokens items list format tokens arity PrimitiveSet renameArguments rename_token addPrimitive enumerate addTerminal len jit_parents_siblings_at_once array array zeros DEAP_to_tokens PrimitiveTree _finish_tokens task_class import_custom_source make_task set_execute load upper format print join load_model endswith resource_filename startswith listdir abs array clip continuous seed format heuristic print render reset step seed make list items print reset sample step keys range enumerate list items clear_cache DataFrame upper Program array startswith set_task listdir keys format print action_space observation_space reset sample TimeFeatureWrapper strip seed shape Model sum predict mean get_env_info make time int RenderEnv reset step savez load_default_model hstack choice savetxt plot resource_filename BenchmarkDataset to_list var seed update random fit update DeepSymbolicOptimizer save train HardCodedConstant arange update train load_config load trainable_variables run resource_filename train set_config load_config update trainable_variables concatenate assert_array_almost_equal train set_config load_config run update seed set_n_objects setup from_str_tokens squeeze random assert_array_almost_equal execute update deepcopy set_n_objects assert_valid assert_invalid append train update deepcopy set_n_objects assert_valid assert_invalid append train update set_n_objects setup assert_valid min assert_invalid sample make_sequence train max append update deepcopy set_n_objects assert_valid assert_invalid append train set_n_objects format function lineno filename format function print filename lineno print compute_probs make_batch compute_probs make_batch jit_parents_siblings_at_once format make_batch make_testing_message test_is_violated is_violated actions append expand_dims enumerate len pre_assert_is_violation getframeinfo enumerate pre_assert_is_violation getframeinfo enumerate int max parents_siblings zeros_like parent_adjust ones Batch len logical_and where arities stack swapaxes append zeros array range prior max_length update assert_valid assert_invalid RepeatConstraint assert_is_violation_true append train assert_is_violation_false library update make_pool_and_set_task assert_valid assert_invalid append train update assert_is_violation_false assert_valid RelationalConstraint assert_invalid assert_is_violation_true append train actionize library update assert_valid assert_invalid library trig_tokens assert_is_violation_true append train assert_is_violation_false TrigConstraint update print arity RelationalConstraint assert_invalid assert_is_violation_true zip append train range actionize library update assert_valid RelationalConstraint assert_invalid assert_is_violation_true append train assert_is_violation_false library update ConstConstraint make_pool_and_set_task assert_valid assert_invalid assert_is_violation_true append train assert_is_violation_false library update assert_valid RelationalConstraint assert_invalid assert_is_violation_true append train assert_is_violation_false library update items list assert_valid assert_invalid InverseUnaryConstraint assert_is_violation_true append train assert_is_violation_false library update setup assert_valid min assert_invalid sample make_sequence train max append update assert_valid assert_invalid state_checker_tokens append train library update train update train | # Deep symbolic optimization <p align="center"> <img src="banner.png" width=750/> </p> Deep symbolic optimization (DSO) is a deep learning framework for symbolic optimization tasks. The package `dso` includes the core symbolic optimization algorithms, as well as support for two particular symbolic optimization tasks: (1) _symbolic regression_ (recovering tractable mathematical expressions from an input dataset) and (2) discovering _symbolic policies_ for reinforcement learning environments. In the code, these tasks are referred to as `regression` and `control`, respectively. We also include a simple interface for defining new tasks. This repository contains code supporting the following publications: 1. Petersen et al. 2021 **Deep symbolic regression: Recovering mathematical expressions from data via risk-seeking policy gradients.** *ICLR 2021.* [Oral](https://iclr.cc/virtual/2021/poster/2578) [Paper](https://openreview.net/forum?id=m5Qsh0kBQG) 2. Landajuela et al. 2021 **Discovering symbolic policies with deep reinforcement learning.** *ICML 2021.* [Paper](http://proceedings.mlr.press/v139/landajuela21a/landajuela21a.pdf) 3. Mundhenk et al. 2021 **Symbolic Regression via Neural-Guided Genetic Programming Population Seeding.** *NeurIPS 2021* [Paper](https://arxiv.org/abs/2111.00053) 4. Landajuela et al. 2021 **Improving exploration in policy gradient search: Application to symbolic optimization.** *Math-AI @ ICLR 2021.* [Paper](https://mathai-iclr.github.io/papers/papers/MATHAI_16_paper.pdf) | 1,603 |
brett-daley/expectigrad | ['stochastic optimization'] | ['Expectigrad: Fast Stochastic Optimization with Robust Convergence Properties', 'On the Convergence of Adam and Beyond'] | tests/test_tensorflow1.py tests/test_tensorflow2.py expectigrad/tensorflow2.py setup.py expectigrad/testing.py expectigrad/tensorflow1.py tests/test_pytorch.py expectigrad/pytorch.py Expectigrad ExpectigradOptimizer Expectigrad gradient_test_function generate_test_sequence NumpyExpectigrad TestExpectigradPytorch TestExpectigradTensorflow1 TestExpectigradTensorflow2 asarray NumpyExpectigrad copy append gradient_test_function range | # Expectigrad: Fast Stochastic Optimization with Robust Convergence Properties  [](./LICENSE)  [](#pytorch) [](#tensorflow-1.x) [](#tensorflow-2.x) Expectigrad is a first-order stochastic optimization method that fixes the [known divergence issue](https://arxiv.org/abs/1904.09237) of Adam, RMSProp, and related adaptive methods while offering better performance on | 1,604 |
broadinstitute/SignatureAnalyzer-GPU | ['stock price prediction'] | ['Automatic Relevance Determination in Nonnegative Matrix Factorization with the β-Divergence'] | NMF_functions.py ARD_NMF.py SignatureAnalyzer-GPU.py ARD_NMF print_report run_method_engine update_H_gaussian_L2 update_lambda_L2 update_H_poisson_L1 update_H_gaussian_L1 update_W_gaussian_L2 NMF_algorithim update_lambda_L1_L2 update_W_poisson_L2 update_W_poisson_L1 update_W_gaussian_L1 update_H_poisson_L2 update_lambda_L1 beta_div update_lambda_L2_L1 calculate_objective_function update_del run_parameter_sweep write_output main createFolder print format write div send calculate_objective_function abs forward max initalize_data str list format NMF_algorithim print_report time T print write dict beta_div K0 dtype type log div beta_div log reshape transpose div matmul reshape transpose matmul pow div reshape transpose div matmul dtype type div matmul div transpose matmul pow div transpose matmul dtype type div matmul div transpose matmul div abs max makedirs run_method_engine output_dir use_val_set max_iter Process sample_names device_count append prior_on_W range Pipe start report_frequency write_output tolerance int join print prior_on_H to_csv channel_names len DataFrame sum to_csv createFolder data run_method_engine labeled float16 set_start_method parquet ArgumentParser output_dir use_val_set read_parquet channel_names max_iter sample_names exit read_csv parse_args set_defaults a prior_on_W phi report_frequency b write_output tolerance parameters_file read_dataframe print add_argument prior_on_H float32 feather run_parameter_sweep ARD_NMF K0 objective | # SignatureAnalyzer-GPU # Installation ``` git clone https://github.com/broadinstitute/SignatureAnalyzer-GPU.git ``` To install pytorch please use Anaconda (find more details @ https://pytorch.org/): ``` conda install pytorch torchvision cudatoolkit=9.0 -c pytorch ``` # Setup | 1,605 |
broadinstitute/getzlab-SignatureAnalyzer | ['stock price prediction'] | ['Automatic Relevance Determination in Nonnegative Matrix Factorization with the β-Divergence'] | signatureanalyzer/tests/test_mapping.py signatureanalyzer/signatureanalyzer.py signatureanalyzer/plotting/_cosine.py signatureanalyzer/tests/test_spectra.py signatureanalyzer/ref/format_cosmic_files.py signatureanalyzer/pathways/__init__.py signatureanalyzer/plotting/_rna.py signatureanalyzer/__init__.py signatureanalyzer/bnmf.py signatureanalyzer/plotting/_muts.py signatureanalyzer/__main__.py signatureanalyzer/supervised_bnmf.py signatureanalyzer/spectra.py signatureanalyzer/pathways/_gsea.py signatureanalyzer/context.py signatureanalyzer/utils.py signatureanalyzer/tests/test_nmf.py setup.py signatureanalyzer/plotting/_utils.py signatureanalyzer/consensus.py signatureanalyzer/plotting/__init__.py signatureanalyzer/plotting/_nmf.py ardnmf consensus_cluster run_spectra run_maf run_matrix get_spectra_from_maf SS_NMF_algorithim supervised_ardnmf _map_dbs_sigs get_nruns_from_output get_pole_pold_muts get_true_snps_from_maf _map_sbs_sigs sbs1536_annotation_converter plot_mutational_signatures load_reference_signatures get_nlogs_from_output _map_sbs_id_sigs transfer_weights assign_signature_weights_to_maf l2fc sbs_annotation_converter select_signatures postprocess_msigs _map_polymerase96_id _map_id_sigs compl get96_from_1536 split_negatives get_dnps_from_maf compute_phi _map_composite_sigs file_loader select_markers main gprof cosine_similarity_plot signature_barplot_sbs_id _map_id_sigs_back signature_barplot_ID signature_barplot_DBS stacked_bar signature_barplot_polymerase _map_sbs_sigs_back signature_barplot_composite signature_barplot k_dist consensus_matrix marker_heatmap color_list_to_matrix_and_cmap series_to_colors func TestMapping TestNmf TestSpectra select_markers sample_names run_method_engine select_signatures astype ARD_NMF rename transfer_weights DataFrame channel_names get_nruns_from_output concat read_hdf vstack DataFrame read_hdf get_spectra_from_maf plot_mutational_signatures K idxmax DataFrame load_reference_signatures HDFStore idxmin get_nlogs_from_output ardnmf assign_signature_weights_to_maf range format close postprocess_msigs join int print to_csv makedirs plot_mutational_signatures K idxmax DataFrame load_reference_signatures HDFStore idxmin get_nlogs_from_output map ardnmf range format close postprocess_msigs join int isinstance print file_loader any makedirs read_hdf K idxmax DataFrame HDFStore idxmin marker_heatmap get_nlogs_from_output max_id savefig consensus_matrix ardnmf range consensus_cluster format k_dist close split_negatives join int isinstance print to_csv file_loader array makedirs concat get_true_snps_from_maf drop TwoBitFile rename fillna __getitem__ str list all apply append format astype copy reversed upper lower zip enumerate get_dnps_from_maf Series write any len SS_NMF_algorithim select_markers div intersect1d rename tensor calculate_objective_function forward cuda max values initalize_data abs str list columns sample_names squeeze map apply transfer_weights format select_signatures astype print_report T print DataFrame write index dict ARD_NMF beta_div K0 numpy channel_names endswith astype copy where mean median values sum copy T astype copy div rename sum max range list tqdm mean unique append sort_values print dropna format name name name apply to_series _map_dbs_sigs _map_sbs_sigs to_series _map_sbs_sigs name map list sort_index copy index dict div idxmax rename get96_from_1536 sum load_reference_signatures values drop reset_index T get_nruns_from_output arange groupby reset_index len extend append sort_values array flatnonzero diff groupby arange reset_index concatenate len delete apply append sort_values array flatnonzero diff sum DataFrame format write map copy index intersect1d rename unique append signature_barplot_DBS stacked_bar concat read_hdf savefig append Index signature_barplot_sbs_id format k_dist signature_barplot_ID signature_barplot_polymerase copy join print write cosine_similarity_plot signature_barplot_composite signature_barplot array seed int random_seed run_matrix print run_maf add_argument run_spectra ArgumentParser input parse_args list format categories isinstance print gprofiler index sort_values tqdm append DataFrame items list set_frame_on subplots arange set_yticklabels set_yticks index set_visible get_ylim heatmap linkage set_ylim sum remove subplots plot set_xticklabels set_xlabel set_ylim map copy div set_xticks set_ylabel sort_values values name apply name subplots tick_params list set_title bar append range product set_xticklabels set_xlim copy startswith compl enumerate join isinstance sort_index Series text subplots_adjust set_xticks _map_sbs_sigs_back len subplots set_title isinstance sort_index set_xticklabels Series text set_xlim copy index subplots_adjust bar set_xticks append tick_params enumerate len _map_id_sigs_back subplots set_title isinstance set_xticklabels Series text set_xlim group copy index subplots_adjust bar set_xticks append tick_params enumerate len subplots tick_params list set_title bar append range product set_xticklabels set_xlim group copy startswith compl reindex enumerate join remove isinstance Series text subplots_adjust set_xticks set_ylim len subplots tick_params list set_title bar append range product set_xticklabels set_xlim group copy startswith compl reindex enumerate join remove isinstance Series text subplots_adjust set_xticks set_ylim len subplots tick_params list set_title bar append range product set_xticklabels set_xlim copy startswith compl reindex enumerate join remove isinstance Series text subplots_adjust set_xticks set_ylim len int format subplots set_title set_xticklabels get_xticklabels countplot set_ylabel set_ylim len dendrogram subplots rainbow roll set_visible rename linspace max heatmap y0 values AgglomerativeClustering set_link_color_palette list name set_xlabel map x1 color_list_to_matrix_and_cmap append hlines format y1 add_axes unique linkage fit_predict enumerate items T series_to_colors vlines x0 Series set_yticks sort text set_ylabel set_xticks subplots arange cumsum set_yticklabels tuple roll set_ticks set_visible heatmap y0 values list set_frame_on set_title set_xlabel x1 color_list_to_matrix_and_cmap hlines append set_xticklabels y1 add_axes set_ticks_position unique __call__ keys items T series_to_colors vlines x0 set_yticks dict set_xticks set_ylabel set_ticklabels len list zip dict unique color_palette len reshape set dict array len | # SignatureAnalyzer Automatic Relevance Determination (ARD) - NMF of mutational signature & expression data. Designed for scalability using Pytorch to run using GPUs if available. _Requires Python 3.6.0 or higher._ Please visit our [wiki](https://github.com/broadinstitute/getzlab-SignatureAnalyzer/wiki) for full documentation. ## Installation ##### PIP `pip3 install signatureanalyzer` or ##### Git Clone * `git clone --recursive https://github.com/broadinstitute/getzlab-SignatureAnalyzer.git` | 1,606 |
brochier/expert_finding | ['network embedding'] | ['New Datasets and a Benchmark of Document Network Embedding Methods for Scientific Expert Finding'] | expert_finding/models/random_model.py expert_finding/models/gvnrt_expert_model.py expert_finding/models/propagation_idne_model.py tests/context.py expert_finding/models/idne.py expert_finding/models/propagation_model.py expert_finding/preprocessing/text/window_slider.py tests/test_io.py expert_finding/preprocessing/text/dictionary.py expert_finding/models/voting_idne_model.py expert_finding/models/gvnrt.py expert_finding/preprocessing/text/light_vocabulary.py expert_finding/preprocessing/text/regex.py tests/test_evaluation.py expert_finding/preprocessing/graph/window_slider.py expert_finding/models/post_ane_model.py expert_finding/preprocessing/text/stop_words.py expert_finding/models/tadw.py expert_finding/models/voting_model.py expert_finding/models/graph2gauss_utils.py expert_finding/models/propagation_tadw_model.py expert_finding/preprocessing/graph/random_walker.py scripts/benchmark.py scripts/data_stats.py expert_finding/preprocessing/text/tokenizer.py expert_finding/evaluation.py expert_finding/models/voting_tadw_model.py expert_finding/models/data_generator.py expert_finding/models/graph2gauss.py expert_finding/models/panoptic_model.py expert_finding/models/transformer.py expert_finding/metrics.py scripts/context.py setup.py expert_finding/models/pre_ane_model.py expert_finding/models/tools.py expert_finding/preprocessing/text/vectorizers.py expert_finding/io.py run_all_evaluations get_empty_eval merge_evaluations plot_evaluation run get_list_of_dataset_names load_dataset get_average_precision get_recall_at_k get_roc_curve get_precision_at_k get_precision_recall_curve get_precision get_all_scores get_reciprocal_rank get_roc_auc_score get_recall RandomChoice generate_batches MultipleRandomChoice async_batches Graph2Gauss Model cartesian_product score_node_classification get_hops sample_all_hops to_triplets batch_pairs_sample edges_to_sparse train_val_test_split_adjacency sample_last_hop sparse_feeder load_dataset score_link_prediction edge_cover Model Clock TFModel Model Clock TFModel Model TFModel Model Model Model Model Model Model Model TADW Model chuncker Clock cosine_loss activation_attention Model Model Model RandomWalker MultipleRandomChoice RandomChoice sample_neighbors one_walk RandomSkip WindowSlider grouper Dictionary convert_size to_token_sequence Vocabulary to_id_sequence tokenize convert_size strip_tags stringify strip_numeric remove_stopwords deaccent strip_punctuation strip_short split_alphanum strip_multiple_whitespaces strip_non_alphanum tokenize get_tfidf_1 get_tf_1 get_tfidf_dictionary get_tf_N get_tf_dictionary get_tfidf_N WindowSlider main memory_limit get_memory merge_evaluations plot_evaluation run_all_evaluations list A append squeeze get_all_scores enumerate predict fit items list get_empty_eval mean append std subplots linspace show set_title set_xlabel savefig legend append plot set_xlim mean interp zip minimum join suptitle maximum set_ylabel fill_between std set_ylim load format debug resource_filename dict resource_listdir sum sum len enumerate get_precision_recall_curve get_roc_curve asarray arange squeeze hstack shuffle MultipleRandomChoice range tile randint sum zeros len get __next__ apply_async ThreadPool generate_batches next ones permutation arange eliminate_zeros edges_to_sparse warn row_stack nnz column_stack seed tocsr map append edge_cover set nonzero int A1 symmetrize minimum_spanning_tree T maximum any randint array len coo_matrix f1_score StratifiedShuffleSplit fit LogisticRegressionCV append normalize next range predict split dot setdiag tolil range randint len arange append combinations arange A1 list setdiff1d arange map set flatten add row_stack nonzero append column_stack tocsr arange setdiff1d concatenate copy row_stack nonzero append column_stack list range len transpose float32 matmul activation reduce_sum cast tile expand_dims equal norm exp l2_normalize matmul diag_part log join format arange debug nodes_number shuffle save zeros range data list arange min tolist extend nonzero range len int pow floor round log strip_tags list deaccent strip_punctuation lower strip_multiple_whitespaces append strip_non_alphanum split isinstance sub remove_stopwords csr_matrix docs_seqs enumerate csr_matrix get_sequence csr_matrix get_sequence enumerate num_docs csr_matrix unique docs_seqs normalize sum log enumerate len get_sequence num_docs csr_matrix unique normalize sum log len get_sequence num_docs csr_matrix unique normalize sum log enumerate len setrlimit getrlimit RLIMIT_AS items list run_all_evaluations merge_evaluations load_dataset info get_list_of_dataset_names | ## Python package for the paper [ New datasets and a benchmark of document network embedding methods for scientific expert finding](https://arxiv.org/pdf/2004.03621.pdf) (BIR20@ECIR20) ### Install: You need python 3.7 installed on your computer with pip. Optionally create a new environment (with conda): conda create --name expert_finding python=3.7 pip conda activate expert_finding Then run: pip install git+https://github.com/brochier/expert_finding | 1,607 |
brochier/gvnr | ['network embedding'] | ['Global Vectors for Node Representations'] | gvnr/models/netmf.py gvnr/models/gvnr.py tests/context.py gvnr/models/glove.py gvnr/data/datasets.py gvnr/models/tadw.py gvnr/preprocessing/window_slider.py tests/test_evaluation.py tests/test_baselines.py gvnr/preprocessing/random_walker.py gvnr/models/wrappers.py gvnr/evaluation.py gvnr/models/deepwalk.py scripts/example.py gvnr/models/gvnrt.py scripts/context.py setup.py gvnr/baselines.py scripts/eval.py run construct_indicator get_score train_and_predict predict_cv random_train_test get_dataset clique parse_adjacencylist_unchecked from_adjlist WalksCorpus Graph from_networkx from_numpy grouper build_deepwalk_corpus_iter load_edgelist from_adjlist_unchecked build_deepwalk_corpus parse_adjacencylist run Model GloVe Clock Model gvnr Clock Model gvnrt Clock netmf_large approximate_normalized_graph_laplacian load_adjacency_matrix svd_deepwalk_matrix direct_compute_deepwalk_matrix deepwalk_filter netmf_small approximate_deepwalk_matrix TADW RandomChoice one_walk RandomWalker RandomSkip WindowSlider grouper get_score tadw_wrapper RandomWalker build_cooccurrence_matrix abspath binary_wrapper csr_matrix get_dataset savetxt netmf_wrapper dirname load_npz deepwalk_svd_wrapper build_random_walks format gvnrt_wrapper resource_filename info WindowSlider gvnr_no_filter_wrapper fit_predict pardir join gvnr_wrapper glove_wrapper svd_wrapper netmf_small_wrapper netmf_svd_wrapper tfidf_wrapper isfile deepwalk_wrapper save_npz asarray squeeze argsort shape zeros sum fliplr range construct_indicator OneVsRestClassifier LogisticRegression ShuffleSplit predict_proba append f1_score split seed train_and_predict predict_cv random_train_test range enumerate len int arange shuffle OneVsRestClassifier predict LogisticRegression load debug resource_filename warning info list random_walk shuffle nodes append range shuffle list range nodes sorted extend set extend Graph make_consistent Graph iterkeys nodes_iter make_undirected append enumerate data make_consistent issparse make_undirected row tocoo Graph col zip append Graph list sorted set Graph str basicConfig debug from_numpy Word2Vec build_deepwalk_corpus get_vector range zeros debug loadmat debug min maximum max range len diags debug min identity dot laplacian max eigsh count_nonzero T function floatX debug f astype maximum deepwalk_filter dot matrix log svds approximate_normalized_graph_laplacian csr_matrix debug svd_deepwalk_matrix float sum approximate_deepwalk_matrix T function zeros_like floatX debug f astype identity log maximum dot laplacian matrix float sum diags range csr_matrix debug direct_compute_deepwalk_matrix svd_deepwalk_matrix join format arange debug nodes_number shuffle save zeros range | ## Python package for the paper [Global Vectors for Node Representation](https://arxiv.org/pdf/1902.11004.pdf) (WWW19) ### To run the experiments presented in the paper: You need python 3.6 installed on your computer with pip. Optionally create a new environment (with conda): conda create --name gvnr python=3.6 pip Then run: git clone https://github.com/brochier/gvnr cd gvnr pip install -r requirements.txt | 1,608 |
brochier/idne | ['network embedding'] | ['Inductive Document Network Embedding with Topic-Word Attention'] | idne/eval/visualization.py idne/models/cane.py idne/models/graph2gauss_utils.py tests/context.py idne/models/tadw.py idne/preprocessing/text/regex.py idne/eval/multi_label_classification.py idne/models/tools.py tests/test_link_prediction_new.py tests/test_multi_label_classification_new.py idne/preprocessing/text/light_vocabulary.py idne/models/graph2gauss.py idne/preprocessing/text/window_slider.py idne/eval/multi_label_classification_new.py idne/models/idne.py scripts/evaluations.py scripts/topic_distrib_eval.py idne/eval/link_prediction_new.py idne/preprocessing/text/vectorizers.py idne/eval/multi_class_classification_new.py idne/preprocessing/graph/window_slider.py idne/models/gvnrt.py tests/test_multi_class_classification.py idne/datasets/io.py idne/models/data_generator.py idne/preprocessing/text/tokenizer.py idne/preprocessing/text/stop_words.py idne/preprocessing/graph/random_walker.py tests/test_multi_label_classification.py tests/test_multi_class_classification_new.py idne/models/lsa.py scripts/topic_attention_weights.py idne/preprocessing/text/dictionary.py scripts/context.py setup.py idne/models/transformer.py idne/eval/multi_class_classification.py tests/test_link_prediction.py idne/eval/link_prediction.py make_symetric load_multi_label_dataset load_multi_class_dataset evaluate generate_test_set_edges test make_symetric get_roc_auc_score generate_test_set_nodes evaluate test get_roc_auc_score get_score convert_labels evaluate train_and_predict convert_labels evaluate train_and_predict get_score train_and_predict evaluate train_and_predict evaluate plot_heat_map dataSet Model TFModel RandomChoice generate_batches MultipleRandomChoice async_batches Graph2Gauss Model cartesian_product score_node_classification get_hops sample_all_hops to_triplets batch_pairs_sample edges_to_sparse train_val_test_split_adjacency sample_last_hop sparse_feeder load_dataset score_link_prediction edge_cover Model Clock TFModel Model TFModel Model TADW Model chuncker Clock cosine_loss activation_attention approximate_normalized_graph_laplacian RandomWalker approximate_deepwalk_matrix MultipleRandomChoice deepwalk_filter RandomChoice sample_neighbors pagerank_scipy one_walk RandomSkip WindowSlider grouper Dictionary convert_size to_token_sequence Vocabulary to_id_sequence tokenize convert_size strip_tags stringify strip_numeric remove_stopwords deaccent strip_punctuation strip_short split_alphanum strip_multiple_whitespaces strip_non_alphanum tokenize get_tfidf_1 get_tf_1 get_tfidf_dictionary get_tf_N get_tf_dictionary get_tfidf_N WindowSlider main memory_limit print_scores get_memory get_html memory_limit get_memory main tokenize main memory_limit get_memory convert_labels main memory_limit get_memory main memory_limit get_memory main memory_limit get_memory main memory_limit get_memory main memory_limit get_memory main memory_limit get_memory data list sum_duplicates setdiag eliminate_zeros csr_matrix set add nonzero zip append array enumerate load format debug resource_filename dict make_symetric load format debug resource_filename dict make_symetric data eliminate_zeros seed list tocsr add append format debug choice set nonzero zip enumerate setdefault dict randint array len append list predict enumerate list arange generate_test_set_edges len shuffle test __init__ append std range enumerate fit data eliminate_zeros seed list add append sum format debug copy choice set zip enumerate setdefault dict randint array len predict_new generate_test_set_nodes seed train_and_predict list StratifiedShuffleSplit append std enumerate split sort dict unique zeros enumerate predict convert_labels predict_proba LogisticRegressionCV f1_score roc_auc_score fit get_score train_and_predict StratifiedShuffleSplit eliminate_zeros copy split seed iterative_train_test_split mean append range MultiOutputClassifier get_embeddings IterativeStratification train_test_split next setdiff1d concatenate debug get_embeddings_new array show int subplots arange set_xticklabels set_yticklabels invert_yaxis set_yticks set_xlim set_xticks pcolor tick_top xticks set_ylim asarray arange squeeze hstack shuffle MultipleRandomChoice range tile randint sum zeros len get __next__ apply_async ThreadPool generate_batches next ones permutation arange eliminate_zeros edges_to_sparse warn row_stack nnz column_stack seed tocsr map append edge_cover set nonzero int A1 symmetrize minimum_spanning_tree T maximum any randint array len coo_matrix f1_score StratifiedShuffleSplit fit LogisticRegressionCV append normalize next range predict split dot setdiag tolil range randint len arange append combinations arange A1 list setdiff1d arange map set flatten add row_stack nonzero append column_stack tocsr arange setdiff1d concatenate copy row_stack nonzero append column_stack list range len transpose float32 matmul activation reduce_sum cast tile expand_dims equal norm exp l2_normalize matmul diag_part log join format arange debug nodes_number shuffle save zeros range data list arange min tolist extend nonzero range len print copy dot eye sample_neighbors normalize sum range debug min maximum max range len diags debug min identity dot laplacian max eigsh count_nonzero T function floatX debug f astype maximum deepwalk_filter dot matrix log int pow floor round log strip_tags list deaccent strip_punctuation lower strip_multiple_whitespaces append strip_non_alphanum split isinstance sub remove_stopwords csr_matrix docs_seqs enumerate csr_matrix get_sequence csr_matrix get_sequence enumerate num_docs csr_matrix unique docs_seqs normalize sum log enumerate len get_sequence num_docs csr_matrix unique normalize sum log len get_sequence num_docs csr_matrix unique normalize sum log enumerate len setrlimit getrlimit RLIMIT_AS print join print_scores dump list load_multi_class_dataset evaluate items dict open dirname abspath info append load_multi_label_dataset pardir enumerate argmax sum print get_html Model raw_attention plot_direct_topics Dictionary max enumerate fit T get_inducing_points get_word_embeddings get_topics dot plot_words_topics_amplitudes | ## Python package for the paper [Inductive Document Network Embedding with Topic-Word Attention](https://arxiv.org/pdf/2001.03369.pdf) (ECIR20) ### To run the experiments presented in the paper: You need python 3.7 installed on your computer with pip. Optionally create a new environment (with conda): conda create --name idne python=3.7 pip Then run (for linux users): git clone https://github.com/brochier/idne cd idne pip install -r requirements.txt | 1,609 |
brookehus/sCSC | ['protein folding'] | ['Simultaneous Coherent Structure Coloring facilitates interpretable clustering of scientific data by amplifying dissimilarity'] | notebooks/sCSC.py initialize_dendrogram_matrices plot_next_dendrogram_split get_subgroup_similarity get_binary_codes plot_line get_eigenvectors_for_dendrogram T eig matmul sqrt sum diag enumerate arange shape pdist fcluster empty linkage zeros arange binary_repr all transpose delete where matmul intersect1d nan sum array plot str subplots text cos mean plot_line sin | Simultaneous coherent structure coloring ======================================== []() This repository contains the data and an example clustering model calculation in research article, [Simultaneous Coherent Structure Coloring facilitates interpretable clustering of scientific data by amplifying dissimilarity](https://doi.org/10.1371/journal.pone.0212442). If you use the code herein, please cite: ```bibtex @article{husic2019simultaneous, title={Simultaneous coherent structure coloring facilitates interpretable clustering of scientific data by amplifying dissimilarity}, author={Husic, Brooke E and Schlueter-Kuck, Kristy L and Dabiri, John O}, journal={PLoS ONE}, | 1,610 |
brooklyn1900/SPCNet | ['scene text detection', 'instance segmentation', 'semantic segmentation'] | ['Scene Text Detection with Supervised Pyramid Context Network'] | train.py data/__init__.py demo.py nets/config.py nets/utils.py nets/resnet_v1.py nets/model.py nets/resnet_utils.py data/icdar.py data/data_util.py data/icdar2017/txt2img.py get_model_list get_image_list InferenceConfig read_image get_result main GeneratorEnqueuer get_image build_rpn_targets generator get_batch polygon_area resize_image_and_annotation compute_backbone_shapes get_set_list get_annotation read_image Config _extra_conv_arg_scope_with_bn detect_target generate_detect_target build_mrcnn_bbox_loss build_rpn_class_loss get_detect_results build_RPN build_rpn_bbox_loss build_mrcnn_class_loss build_input_graph build_TCM build_SPC build_rescore_graph generate_all_anchors PyramidROIAlign TCM_module generate_proposal build_mrcnn_mask_loss build_FPN build_mrcnn_head smooth_l1_loss build_global_mask_loss build_mrcnn_mask refine_detections_graph 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 astype float32 mimread imread array get_checkpoint_state all_model_checkpoint_paths latest_checkpoint append join listdir isfile reset_default_graph gpu_list trainable_variables checkpoint_path pretrained_model_path MkDir moving_average_decay Saver GPUOptions global_variables get_collection gpu_list apply build_input_graph apply_gradients polynomial_decay build_SPC get_or_create_global_step group compute_gradients assign_from_checkpoint_fn learning_rate AdamOptimizer ExponentialMovingAverage MODEL_VARIABLES global_variables_initializer join join read_image exists astype float32 join extract_bboxes astype randint resize_mask int32 resize_image fliplr BACKBONE callable sum zip ones compute_overlaps choice RPN_TRAIN_ANCHORS_PER_IMAGE zeros argmax amax len arange IMAGE_SHAPE compute_backbone_shapes RPN_ANCHOR_RATIOS BACKBONE_STRIDES get_set_list generate_pyramid_anchors BATCH_SIZE MAX_GT_INSTANCES shape resize_image_and_annotation MINI_MASK_SHAPE get_image build_rpn_targets format minimize_mask astype shuffle choice USE_MINI_MASK get_annotation join uint8 RPN_ANCHOR_SCALES print RPN_ANCHOR_STRIDE zeros len generator get is_running print start sleep GeneratorEnqueuer array IMAGE_SHAPE generate_detect_target norm_boxes_graph add_n RPN_ANCHOR_RATIOS build_mrcnn_bbox_loss build_rpn_class_loss get_detect_results BATCH_SIZE build_RPN build_rpn_bbox_loss get_collection build_mrcnn_class_loss shape build_TCM append range generate_all_anchors generate_proposal build_mrcnn_mask_loss build_FPN stack MEAN_PIXEL REGULARIZATION_LOSSES build_mrcnn_head print build_global_mask_loss array build_mrcnn_mask len uint8 float32 placeholder int32 USE_MINI_MASK bool _extra_conv_arg_scope_with_bn print TCM_module range _extra_conv_arg_scope_with_bn convert_to_tensor RPN_ANCHOR_SCALES norm_boxes ones multiply RPN_ANCHOR_STRIDE RPN_ANCHOR_RATIOS generate_pyramid_anchors BACKBONE_STRIDES minimum IMAGES_PER_GPU reshape batch_slice indices RPN_NMS_THRESHOLD array RPN_BBOX_STD_DEV PRE_NMS_LIMIT concat reduce_max boolean_mask MASK_SHAPE crop_and_resize gather box_refinement_graph round trim_zeros_graph ROI_POSITIVE_RATIO transpose squeeze pad cast expand_dims range USE_MINI_MASK overlaps_graph cond int TRAIN_ROIS_PER_IMAGE float32 greater maximum int32 split IMAGES_PER_GPU batch_slice concat where crop_and_resize stop_gradient gather round squeeze log2_graph gather_nd cast append expand_dims range sqrt equal minimum reshape float32 maximum int32 split _extra_conv_arg_scope_with_bn _extra_conv_arg_scope_with_bn IMAGES_PER_GPU reshape batch_slice minimum constant apply_box_deltas_graph reshape clip_boxes_graph concat gather map_fn DETECTION_MAX_INSTANCES build_rescore_graph stack gather_nd DETECTION_MIN_CONFIDENCE pad set_intersection expand_dims argmax BBOX_STD_DEV minimum constant exp log2_graph MASK_SHAPE maximum greater boolean_mask sqrt reduce_mean cast int32 crop_and_resize round split less abs cast float32 softmax_cross_entropy_with_logits one_hot not_equal reshape squeeze where reduce_mean gather_nd cast int32 equal IMAGES_PER_GPU batch_pack_graph squeeze reduce_sum where reduce_mean gather_nd cast int32 cond equal reshape reduce_mean one_hot softmax_cross_entropy_with_logits reshape int64 stack cast gather_nd reduce_mean gather cond reshape transpose shape int64 stack cast gather_nd reduce_mean gather cond convert_to_tensor one_hot reshape reduce_mean append range cond pad | # Scene-Text-Detection-with-SPCNET
Unofficial repository for [Scene Text Detection with Supervised Pyramid Context Network][https://arxiv.org/abs/1811.08605] with tensorflow.
## 参考代码
网络实现主要借鉴Keras版本的[Mask-RCNN](https://github.com/matterport/Mask_RCNN.git),训练数据接口参考了[argman/EAST](https://github.com/argman/EAST).论文作者在知乎的文章介绍[SPCNet](https://zhuanlan.zhihu.com/p/51397423).
## 训练
### 1、训练数据准备
训练数据放在data/下,训练数据准备在data/icdar.py:
>data
>>icdar2017
>>>Annotaions //image_1.txt
| 1,611 |
brunocalogero/AMLSassignment | ['face detection'] | ['From Facial Parts Responses to Face Detection: A Deep Learning Approach'] | binary_age/binary_age_SVM_PCA_plotting.py binary_human/binary_human_LR_PCA.py multiclass_hair/multiclass_hair_SVM_normal.py multiclass_hair/multiclass_hair_SVM_PCA_plotting.py binary_human/binary_human_SVM_normal.py binary_glasses/binary_glasses_LR_landmarks.py binary_human/binary_human_VGG.py binary_emotion/binary_emotion_SVM_PCA.py binary_age/binary_age_SVM_PCA.py multiclass_hair/multiclass_hair_LR_PCA.py binary_human/binary_human_LR_landmarks.py binary_age/binary_age_LR_PCA_plotting.py multiclass_hair/multiclass_hair_CNN_rawtf.py binary_glasses/binary_glasses_LR_PCA_plotting.py binary_age/binary_age_CNN.py binary_glasses/binary_glasses_SVM_landmarks.py binary_human/binary_human_SVM_PCA_plotting.py binary_human/binary_human_LR_PCA_plotting.py binary_glasses/binary_glasses_CNN.py multiclass_hair/multiclass_hair_SVM_PCA.py binary_age/binary_age_LR_PCA.py binary_emotion/binary_emotion_LR_landmarks.py binary_emotion/binary_emotion_LR_PCA.py binary_glasses/binary_glasses_SVM_PCA_plotting.py multiclass_hair/multiclass_hair_CNN.py binary_emotion/binary_emotion_VGG.py preprocessing/PCA_multiclass.py multiclass_hair/multiclass_hair_SVM_normal_plotting.py binary_age/binary_age_VGG.py binary_human/binary_human_CNN.py binary_emotion/binary_emotion_SVM_PCA_plotting.py binary_emotion/binary_emotion_CNN.py binary_glasses/binary_glasses_LR_PCA.py binary_age/binary_age_SVM_normal.py binary_glasses/binary_glasses_SVM_PCA.py binary_age/binary_age_LR_landmarks.py binary_age/binary_age_SVM_landmarks.py binary_glasses/binary_glasses_SVM_normal.py multiclass_hair/multiclass_hair_LR_PCA_plotting.py binary_emotion/binary_emotion_SVM_normal.py binary_glasses/binary_glasses_VGG.py preprocessing/PCA_binary.py binary_emotion/binary_emotion_LR_PCA_plotting.py binary_human/binary_human_SVM_landmarks.py binary_human/binary_human_SVM_PCA.py binary_emotion/binary_emotion_SVM_landmarks.py optimization_func_hyper create_model activation_hyper pull_dataset batch_epoch_hyper learning_rate_hyper pull_dataset obtain_landmarks plot_learning_curve pull_dataset obtain_landmarks plot_learning_curve pull_dataset extract_features Dataset pull_test_set optimization_func_hyper create_model activation_hyper pull_dataset batch_epoch_hyper learning_rate_hyper pull_dataset obtain_landmarks plot_learning_curve pull_dataset obtain_landmarks plot_learning_curve pull_dataset extract_features Dataset pull_test_set optimization_func_hyper create_model activation_hyper pull_dataset batch_epoch_hyper learning_rate_hyper pull_dataset obtain_landmarks plot_learning_curve pull_dataset obtain_landmarks plot_learning_curve pull_dataset extract_features Dataset pull_test_set optimization_func_hyper create_model activation_hyper pull_dataset batch_epoch_hyper learning_rate_hyper pull_dataset obtain_landmarks plot_learning_curve pull_dataset obtain_landmarks plot_learning_curve pull_dataset extract_features Dataset pull_test_set optimization_func_hyper create_model activation_hyper pull_dataset batch_epoch_hyper learning_rate_hyper pull_dataset check_accuracy model_init_fn Dataset plot_learning_curve pull_dataset pull_dataset plot_learning_curve plot_learning_curve pull_dataset pca_transform pull_dataset pca_transform int format print tolist astype shuffle resize append imread walk array read_csv compile Sequential Adam add Dense MaxPooling2D Conv2D BatchNormalization Flatten Dropout GridSearchCV print KerasClassifier dict zip fit GridSearchCV print KerasClassifier dict zip fit GridSearchCV print KerasClassifier dict zip fit GridSearchCV print KerasClassifier dict zip fit int norm y asarray predict_obj zip pi atan2 mean detect_obj append float atan range x enumerate obtain_landmarks plot xlabel learning_curve grid ylabel mean ylim title figure legend fill_between std int format print astype shuffle resize append imread array walk predict print argmax run dense max_pooling2d flatten conv2d batch_normalization print PCA n_components_ transform StandardScaler fit reshape pca_transform any train_test_split | # AMLSassignment ELEC0132: Applied Machine Learning Systems (18/19) Assignment ## Download Full repo with datasets available: https://drive.google.com/open?id=1XODub1W-K3Z8mu4WHU5fix6asR0PK4xq ## Setup - I highly suggest using a python3.5 conda environment (with tensorflow-gpu==1.4 if using gpu) - `pip install -r requirements.txt` ## Original Dataset All three necessary versions of the dataset - to be able to run the code) can be found on the drive link above, you can also download the original provided labeled dataset (with outliers) using this link: https://drive.google.com/drive/folders/1NgP2jQakFHibIhpevDLshodWw-L52yXi?usp=sharing ## Written Report | 1,612 |
bshall/Tacotron | ['speech synthesis'] | ['Location-Relative Attention Mechanisms For Robust Long-Form Speech Synthesis'] | train.py tacotron/__init__.py tacotron/dataset.py preprocess.py tacotron/model.py tacotron/text.py melspectrogram preprocess_dataset process_wav mu_compress train_model load_checkpoint save_checkpoint log_alignment pad_collate BucketBatchSampler SortedSampler TTSDataset CBHG zoneout HighwayNetwork DynamicConvolutionAttention Encoder DecoderCell Tacotron BatchNormConv PreNet load_cmudict format_alt_entry text_to_id expand_abbreviations parse_text replace_symbols clean tokenize preemphasis amplitude_to_db maximum pad load with_suffix loudness integrated_loudness Meter save mu_compress melspectrogram max print ProcessPoolExecutor mkdir sum values print mkdir save print load load_state_dict subplots add_figure xlabel ylabel imshow figure specshow checkpoint_dir clip_grad_norm_ zero_grad MultiStepLR DataLoader save_checkpoint numpy Path cuda text_path Adam log_alignment unscale_ GradScaler range update SummaryWriter partial dataset_dir TTSDataset enumerate BucketBatchSampler backward add_scalar load_checkpoint print RandomSampler tqdm parameters step len pad pad_sequence list zip bernoulli_ sub sub replace format_alt_entry upper expand_abbreviations replace_symbols joinpath join list set append clean tokenize parse_text | <p align="center"> <a href="https://colab.research.google.com/github/bshall/Tacotron/blob/main/tacotron-demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> </p> # Tacotron with Location Relative Attention A PyTorch implementation of [Location-Relative Attention Mechanisms For Robust Long-Form Speech Synthesis](https://arxiv.org/abs/1910.10288). Audio samples can be found [here](https://bshall.github.io/Tacotron/). Colab demo can be found [here](https://colab.research.google.com/github/bshall/Tacotron/blob/main/tacotron-demo.ipynb). <div align="center"> <img width="655" height="390" alt="Tacotron (with Dynamic Convolution Attention)" src="https://raw.githubusercontent.com/bshall/Tacotron/main/tacotron.png"><br> <sup><strong>Fig 1:</strong>Tacotron (with Dynamic Convolution Attention).</sup> </div> | 1,613 |
bsridatta/wav2letter-Swedish | ['speech recognition'] | ['wav2letter++: The Fastest Open-source Speech Recognition System'] | recipes/librispeech/data/utils.py recipes/librispeech/data/prepare_data.py recipes/wsj/data/prepare_data.py tutorials/1-librispeech_clean/prepare_data.py recipes/timit/data/utils.py tutorials/1-librispeech_clean/prepare_lm.py recipes/timit/data/prepare_data.py recipes/wsj/data/prepare_lm.py recipes/wsj/data/utils.py recipes/librispeech/data/prepare_lm.py findtranscriptfiles parse_speakers_gender copytoflac write_sample copytoflac write_sample find_transcripts processdict ndx2idlist write_sample preprocess transcript2wordspelling findtranscriptfiles write_sample endswith join walk append Transformer set_output_format build join rsplit copytoflac lower dirname sep split replace append preprocess split join walk setdefault sort lower sub replace Transformer format remove system build set_output_format transcript2wordspelling | # wav2letter++ wav2letter++ is a fast open source speech processing toolkit from the Speech Team at Facebook AI Research. 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). The goal of this software is to facilitate research in end-to-end models for speech recognition. The previous version of wav2letter (written in Lua) can be found in the "wav2letter-lua" branch under the repository. ## Building wav2letter++ See [Building Instructions](docs/installation.md) for details. ## Full documentation - [Data Preparation](docs/data_prep.md) | 1,614 |
bstienen/active-learning | ['active learning'] | ['Constraining the Parameters of High-Dimensional Models with Active Learning'] | plot_time_results.py | # Active Learning Code accompanying our Active learning paper [Constraining the Parameters of High-Dimensional Models with Active Learning](https://link.springer.com/article/10.1140%2Fepjc%2Fs10052-019-7437-5) ## Citation If you use this code, don't forget to cite us! @article{Caron:2019xkx, author = "Sascha Caron, Tom Heskes, Sydney Otten, and Bob Stienen", title = "{Constraining the Parameters of High-Dimensional Models with Active Learning}", eprint = "1905.08628", archivePrefix = "arXiv", primaryClass = "cs.LG", | 1,615 |
bsvineethiitg/adams | ['stochastic optimization'] | ['Adam: A Method for Stochastic Optimization', 'Exploiting Uncertainty of Loss Landscape for Stochastic Optimization'] | Experiments/utils/progress/setup.py Experiments/utils/visualize.py Experiments/utils/progress/progress/bar.py Experiments/utils/progress/test_progress.py Experiments/adam_all.py Experiments/models/cifar/vgg.py Experiments/models/cifar/preresnet.py Experiments/models/cifar/mnistLR.py Experiments/models/cifar/resnet.py Experiments/main.py Experiments/utils/eval.py Experiments/utils/misc.py PyTorch-Optimizers/adams.py Experiments/models/imagenet/resnext.py Experiments/utils/__init__.py Experiments/utils/progress/progress/counter.py Experiments/models/cifar/resnext.py Experiments/utils/progress/progress/helpers.py Experiments/models/cifar/mnistMLP.py Experiments/models/cifar/wrn.py PyTorch-Optimizers/adamucb.py Experiments/models/cifar/densenet.py Experiments/models/cifar/alexnet.py Experiments/models/cifar/__init__.py Experiments/models/imagenet/__init__.py Experiments/models/cifar/adampapercifar.py Experiments/utils/progress/progress/__init__.py Experiments/utils/progress/progress/spinner.py Experiments/utils/logger.py PyTorch-Optimizers/adamcb.py AdamALL test save_checkpoint adjust_learning_rate main train AdamCIFAR10 cifar10cnn AlexNet alexnet densenet Transition DenseNet Bottleneck BasicBlock mnistlr MnistLR MnistMLP mnistmlp preresnet PreResNet Bottleneck conv3x3 BasicBlock ResNet Bottleneck conv3x3 resnet BasicBlock ResNeXtBottleneck resnext CifarResNeXt vgg19 VGG vgg16_bn vgg19_bn vgg11_bn make_layers vgg11 vgg13 vgg13_bn vgg16 wrn BasicBlock NetworkBlock WideResNet resnext50 ResNeXt Bottleneck resnext101 resnext152 accuracy plot_overlap savefig Logger LoggerMonitor init_params AverageMeter mkdir_p get_mean_and_std make_image show_mask_single show_mask gauss colorize show_batch sleep FillingSquaresBar FillingCirclesBar IncrementalBar ChargingBar ShadyBar PixelBar Bar Countdown Stack Counter Pie SigIntMixin WriteMixin WritelnMixin PieSpinner MoonSpinner Spinner PixelSpinner LineSpinner Progress Infinite AdamCB Adams AdamUCB train_batch endswith SGD DataLoader DataParallel adjust_learning_rate Logger save_checkpoint arch dataset eta1 opt dataloader cuda max str Adam savefig dirname load_state_dict append sum CIFAR100 CrossEntropyLoss range format plot AdamALL Compose close test start_epoch resume mkdir_p startswith CIFAR10 checkpoint MNIST join load evaluate print parameters eta2 train epochs set_names data model zero_grad Bar finish append next update format size test item float enumerate time criterion backward print AverageMeter accuracy isnan step update data time format criterion model size AverageMeter accuracy eval Bar item finish float next enumerate copyfile join save param_groups AdamCIFAR10 AlexNet MnistLR MnistMLP CifarResNeXt Conv2d make_layers VGG make_layers VGG make_layers VGG make_layers VGG make_layers VGG make_layers VGG make_layers VGG make_layers VGG WideResNet ResNeXt ResNeXt ResNeXt topk size t eq mul_ expand_as append sum max asarray arange plot numbers enumerate len print DataLoader div_ zeros range len normal constant isinstance kaiming_normal Conv2d bias modules BatchNorm2d weight Linear makedirs numpy range zeros unsqueeze gauss show make_image imshow make_grid make_image subplot make_grid size clone axis upsampling imshow expand_as range make_image subplot make_grid size clone axis upsampling imshow expand_as cpu range len | ## Exploiting Uncertainty of Loss Landscape for Stochastic Optimization Paper: [http://arxiv.org/abs/1905.13200](http://arxiv.org/abs/1905.13200) Cite as: ``V.S. Bhaskara, and S. Desai. ``_``arXiv preprint``_`` arXiv:1905.13200 [cs.LG] (2019)``. ### Algorithm We introduce variants of the Adam optimizer that either bias the updates along regions that conform across mini-batches or randomly "explore" in the parameter space along the variance-gradient. The update rules are summarized below:  AdamUCB and AdamCB are biased estimates of the full-gradient. We recommend using AdamS which is an unbiased estimate, and outperforms other variants based on our experiments with CIFAR-10. Please refer to the [paper](http://arxiv.org/abs/1905.13200) for more details. ### Code PyTorch implementation of the optimizers is available under [``PyTorch-Optimizers/``](PyTorch-Optimizers/) ### Usage | 1,616 |
bsxfan/probabilistic_embeddings | ['speaker diarization'] | ['Probabilistic embeddings for speaker diarization'] | odyssey2020/test_ahc.py lib/special/__init__.py odyssey2020/__init__.py lib/__init__.py lib/deriv/__init__.py odyssey2020/ahc.py lib/deriv/adfunctions.py lib/special/softplus.py lib/prob/__init__.py lib/combin/partitions.py lib/deriv/adtools.py lib/special/erf_tools.py lib/combin/__init__.py lib/special/besselk.py lib/deriv/broadcast_adtools.py odyssey2020/test_ntuplemodel.py lib/prob/crp.py odyssey2020/ntuplemodel.py odyssey2020/diag2covplda.py PartitionsOf create_index Bell blocklabels_to_flagvector labels_to_1hotmatrix int2bits partitions_and_subsets PartitionsAsBlocklabels squeeze logsumexp rrandn rdot csHvp cs raug cstest cstestobj rimag csHess cstest_w astuple optobjective rprod prodfun sum2sh sum2shape CRPbeta logprob_alpha logprob_obj ML_alpha_crp logprob_alpha_beta AHC ML_crp CRPalpha CRP logprob_beta ML_beta_crp logK1e_2ndderiv k0e logK1e k1e cs2 csret k012e logdprime2EER erfinv Phi_inv reparam_pdf Phi_and_logderiv erf_and_logderiv erf cs_erfinv EER2dprime logdprime2EER_and_logabsderiv dprime2EER EER2logdprime Phi softplusinv softplus SingletonDict AHC model NTupleModel arange max zeros array astype exp shape sum max log f imag ndarray isscalar isinstance ndarray isscalar isinstance ndarray isscalar isinstance ndarray isscalar isinstance rrandn tuple raug f back rimag astuple rrandn tuple raug f back rimag astuple rprod obj imag real empty csHvp range len obj randn maximum range real abs imag len reshape tuple shape sum len shape sum tuple len print sum gammaln log sum gammaln log sum log gammaln sigmoid softplus softplus minimize print sigmoid zeros x print minimize_scalar x sigmoid minimize_scalar x softplus k0e iscomplexobj k1e kve iscomplexobj iscomplexobj f back k0e iscomplexobj k1e cs kvp exp k1e erf exp erfinv imag real cs_erfinv erf erf_and_logderiv erfinv Phi Phi exp Phi_and_logderiv exp Phi_inv log Phi_inv y2x sign | # Probabilistic Embeddings This repository will contain Python code associated with our [paper](http://arxiv.org/abs/2004.04096): Anna Silnova, Niko Brummer, Johan Rohdin, Themos Stafylakis and Lukas Burget, "Probabilistic embeddings for speaker diarization", Odyssey 2020: The Speaker and Language Recognition Workshop, Tokio. The code here is a work in progress and is not useable yet. For now, if you want a working tool for speaker diarization, see [The BUT BHMM code repository](https://github.com/BUTSpeechFIT/VBx). The tools here will not allow you to fully replicate the experiments described in the paper. Specifically, we do not include the probabilistic x-vector extractor. We do include: - A reference implementation of our discriminative traning criterion. It can be used to train the extractor and the PLDA backend, or just the backend. The criterion is a special case of multiclass cross-entropy, where the classes are all 4140 ways to partition a set of 8 elements. - A reference implementation of our PLDA scoring algorithm. Given an n-tuple of embeddings extracted from an n-tuple of speech segments, the scoring algorithm can compute likelihoods of the form P(speech segment n-tuple | clustering hypothesis) . - A reference implementation of the Chinese restaurant process prior on partition (clustering) hypotheses. ## What is a probabilistic embedding? A traditional embedding is a vector in R<sup>n</sup>, with n fixed, extracted from some complex input (for us a speech segment of variable duration). Such embeddings are much easier to model and process than the original inputs. | 1,617 |
btc-room101/bitcoin-rnn | ['learning to execute'] | ['Learning to Execute'] | priv2pub.py mk-privaddr-pair.py gru-addr2priv.py CharacterTable colors seed2hpriv encode HMAC | # bitcoin-rnn A impementation of training a LSTM network to associate public bitcoin addresses, with private keys. [ Note, inversion and non-inversion are highly suggested also wif and non-wif data, see mk-prvadd-pair.py, for examples of generating training data. This public example is only for understanding concepts, true production requires huge training sets, and various alternate representations of bitcoin address abstraction. Reference for theory of this concept to the following paper. Input may optionally be inverted, shown to increase performance in many tasks in: "Learning to Execute" http://arxiv.org/abs/1410.4615 and "Sequence to Sequence Learning with Neural Networks" http://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf | 1,618 |
bugbug-lou/CVP | ['future prediction', 'video prediction'] | ['Compositional Video Prediction'] | cfgs/collections.py cvp/evaluator.py cvp/layers.py _init_path.py data/ShapeStacks.py data/debug_init_paths.py utils/box_utils.py train.py PerceptualSimilarity/util/html.py cvp/bilinear.py cvp/collections.py cfgs/base_cfgs.py data/PlayroomV1.py PerceptualSimilarity/__init__.py cvp/losses.py cvp/decoder.py cvp/pok_model.py test.py cvp/graph.py cvp/models.py cvp/logger.py cvp/vid_encoder.py data/Primitive.py utils/data_utils.py cfgs/train_cfgs.py demo.py PerceptualSimilarity/util/visualizer.py cfgs/const.py cvp/vis.py cvp/layout.py cfgs/test_cfgs.py utils/model_utils.py PerceptualSimilarity/util/util.py cvp/debug_init_paths.py data/DemoImage.py multi main main quan main add_path str_tuple int_tuple int_list bool_flag BaseOptions float_tuple AttrDict TestOptions TrainOptions crop_bbox_batch_cudnn crop_bbox tensor_linspace _invperm uncrop_bbox bilinear_sample crop_bbox_batch AttrDict add_path refine_module Pix Comb add_layer_to NoFactor vstack hstack Evaluator BypassFactorGCNet BypassFactorFCNet _init_weights NoEdgeConv GraphEdgeConv GraphResBlock FcResBlock build_mlp build_pre_act build_pre_act_list _get_padding ResidualBlock Unflatten GlobalAvgPool build_cnn deconv3d build_fblock _init_conv get_activation build_fblock2 build_fconv batchNorm5d get_normalization_2d Flatten _boxes_to_grid gauss_mask mask_to_region _bbox_to_grid_fwd01 bbox_to_mask bbox_to_bg_feat splat soft_mask_splat_to_bg splat_with_wgt _pool_samples mask_norm _boxes_to_grid_inv bbox_to_bg mask_to_bg splat_neg sg2im_masks_to_layout boxes_to_region_layout mask_splat_to_bg boxes_to_layout mask_to_layout bbox_to_region splat_to_bg_feat Logger get_G_loss resize_l1_loss get_D_loss add_loss LossManager CVP collate_batch LP BaseBG NoFactor PoseEncoder VidD PoseFCDecoder PoseFrameGan PoseVaeNoFactor StateEncoder PoseVaePos VidG PoseVidGan PoseDecoder PoseVae FrameG kl_criterion ImageLearnedPrior ImageFixPrior VidEncoder TrajHierarchy ImageNoZ gaussian_lstm skeleton_13B_valid get_skeleton_pred get_bbox_traj_image convert_torch2cv skeleton_13B skeleton_10B get_layout_list draw_bbox_image convert_cv2torch mask get_skeleton_color convert_batch2cv render_pose skeleton_13B_trip get_crop get_bbox_traj deprocess_dt_v_o_image add_path build_vid_loaders dt_collate_fn DemoShapeStacks raw_to_agent_particles tell project_and_occlude_particles ShapeStacks build_vid_loaders agent_particles_to_image_coordinates dt_collate_fn raw_to_agent_particles tell project_and_occlude_particles build_vid_loaders agent_particles_to_image_coordinates Primitive dt_collate_fn build_vid_loaders ShapeStacks dt_collate_fn PerceptualLoss HTML im2tensor dssim montage prep_display_image zeroClipper varname random_swap tensor2tensorlab resize_image save_image tensor2vec datetime_str psnr np2tensor diagnose_network rand_flip mkdirs load_image tensor2im cos_sim bootstrap read_csv_file_as_text normalize_blob read_text_file grab_patch mkdir info resize_image_zoom flatten_nested_list cos_sim_blob normalize_tensor print_numpy l2 voc_ap tensorlab2tensor rgb2lab read_file tensor2np zoom_to_res Visualizer extents_to_centers xy_to_xyxy xyxy_to_transform extents_to_logcenters box_stack invert_box_transform apply_box_transform extents_to_xy logcenters_to_extents transform_to_xyxy centers_to_extents imagenet_preprocess imagenet_deprocess_batch rescale Resize imagenet_deprocess crop_image build_all_model vid_batch_to_cuda get_model_name build_loaders int get_bbox_traj_image save_pack dt extend convert_batch2cv append range seed build_all_model join print Evaluator manual_seed multi build_loaders int save_vid_traj get_bbox_traj_image save_raw_box_image save_seq2gif dt push_pix_error convert_batch2cv push_box_error save_cmp_snapshot calc_total_bbox_error perceptual_metric range initialize draw_save_error draw_save_pix DistModel quan model add_images zero_grad Logger add_loss output_dir save separate_losses LossManager FloatTensor dt Adam dirname get_bbox_traj state_dict dec_zero_grad startswith type get_crop get_model_name backward parameters train step makedirs append tuple crop_bbox view size contiguous nonzero zeros range size type_as crop_bbox all view size contiguous type_as nonzero append type range cat size stack expand clamp to bilinear_sample expand mul view clamp size expand to size dim expand insert Conv2d ReLU append BatchNorm2d LeakyReLU range refine_module extend Upsample append range ones hstack append range len ones range len hasattr isinstance weight kaiming_normal_ Linear float startswith kaiming_uniform weight kaiming_normal int _get_padding ResidualBlock isinstance AvgPool2d print MaxPool2d Linear Conv2d _init_conv get_activation Upsample append get_normalization_2d enumerate Flatten split BatchNorm1d InstanceNorm1d len Dropout ReLU append LeakyReLU range Linear InstanceNorm1d len Conv2d Tanh Sigmoid ReLU append BatchNorm2d LeakyReLU range Dropout AvgPool2d Conv2d get_activation append get_normalization_2d range len AvgPool2d Conv2d get_activation append get_normalization_2d range len BatchNorm1d InstanceNorm1d print Linear ReLU append LeakyReLU Dropout BatchNorm1d InstanceNorm1d print Linear ReLU append LeakyReLU range Dropout _boxes_to_grid grid_sample size expand _pool_samples logcenters_to_extents size expand _boxes_to_grid grid_sample view size _pool_samples _boxes_to_grid grid_sample FloatTensor size stack append mask_norm sum cuda range cat _boxes_to_grid grid_sample FloatTensor size stack append mask_norm sum cuda range cat _boxes_to_grid grid_sample FloatTensor size stack append cuda range cat FloatTensor size splat stack append cuda range cat size splat stack cuda append sum mask_norm range cat size splat_neg splat stack append mask_norm sum cuda range cat view to clamp size expand floor nonzero _bbox_to_grid_fwd01 scatter_add splat_with_wgt splat_with_wgt _boxes_to_grid grid_sample clamp size stack append sum cuda range _boxes_to_grid grid_sample size expand stack append range _boxes_to_grid grid_sample clamp size stack append sum cuda range cat _boxes_to_grid_inv grid_sample FloatTensor size stack append cuda range _boxes_to_grid_inv grid_sample size stack append range pow int sum softmax view size expand stack to size expand stack sub to view size expand stack sub to view ones print size clamp expand item zeros scatter_add view print size l1_loss avg_pool2d item size l1_loss add_loss to l1_dst_loss_weight size to add_loss append stack enumerate exp log convert_torch2cv view size imagenet_deprocess_batch append range uint8 COLOR_BGR2RGB FloatTensor transpose astype cvtColor enumerate uint8 transpose astype ascontiguousarray COLOR_RGB2BGR numpy cvtColor int list skeleton_13B_valid skeleton_13B skeleton_10B size convert_cv2torch astype skeleton_13B_trip append zeros numpy range len int list skeleton_13B_valid skeleton_13B skeleton_10B size convert_cv2torch astype skeleton_13B_trip append zeros numpy range line tuple range circle len int line tuple astype circle enumerate int line tuple astype range circle int line tuple astype range circle int list size convert_cv2torch astype append zeros numpy range circle minimum int size tolist astype maximum convert_cv2torch append zeros numpy range circle minimum int size astype maximum copy rectangle append numpy range append imagenet_deprocess_batch range size imagenet_deprocess_batch view append imagenet_deprocess_batch range view clamp size imagenet_deprocess_batch append range int line transpose len astype numpy zeros is_tensor range circle enumerate view print size stack append range len print DataLoader is_train DemoShapeStacks all list concatenate reshape transpose float32 matmul shape zeros minimum list concatenate reshape transpose astype maximum matmul shape zeros float raw_to_agent_particles list print reshape astype shape agent_particles_to_image_coordinates join num_val_samples shuffle_val ShapeStacks get_bbox_nums list_paths int append Primitive sequence_len range now readline close append float open sqrt sum shape normalize_blob view normalize_tensor rgb2lab tensor2im filterwarnings np2tensor astype lab2rgb rgb2lab tensor2np isclose clip transpose numpy print parameters astype max zoom fromarray save print join search print float64 flatten astype mkdir makedirs uint dtype permutation arange reshape astype sqrt ceil zeros meshgrid array append readline close open append split append readline close open arange concatenate size maximum sum max range exp transpose is_tensor stack extents_to_centers centers_to_extents apply_box_transform stack transpose is_tensor log extents_to_centers invert_box_transform box_stack box_stack box_stack is_tensor box_stack stack is_tensor log hstack transpose is_tensor stack append clamp size clone imagenet_deprocess append range cat append range interpolate cat cuda exp appr_pix_loss appr_fea_loss int build_vid_loaders startswith load model print eval load_state_dict cuda checkpoint | # Compositional Video Prediction Yufei Ye, Maneesh Singh, Abhinav Gupta*, and Shubham Tulsiani* [Project Page](https://judyye.github.io/CVP/), [Arxiv](http://arxiv.org/abs/1908.08522)  Given an initial frame, the task is to predict the next few frames in pixel level. The key insight is that a scene is comprised of distinct entities that undergo joint motions. To operationalize this idea, we propose **Compositional Video Prediction** (CVP), which consists of three main modules: 1) **Entity Predictor**: predicts per-entity representation; 2) **Frame Decoder**: generate pixels given entity-level representation; 3) **Encoder**: generate latent variables to account for multi-modality. | 1,619 |
burcgokden/CoulGAT-Graph-Attention-Interpretability | ['graph attention'] | ['CoulGAT: An Experiment on Interpretability of Graph Attention Networks'] | scc_data_prep.py common.py gatt_model.py scc_data_prep_alt.py pklsave pklload reset_graph set_graph_seed GattModel CHAMPSData predict2csv scc_test_slice_save scc_trnval_slice_save scc_load CHAMPSData predict2csv scc_test_slice_save scc_trnval_slice_save scc_load print print seed reset_default_graph set_random_seed pklsave str list shuffle pklload append keys pklsave str list shuffle pklload append keys len print pklload reset_index concatenate print astype to_csv DataFrame | ## CoulGAT: A Graph Attention Framework with screened Coulomb Attention Mechanism This repository is the implementation of graph attention framework and attention mechanism detailed in [CoulGAT: An Experiment on Interpretability of Graph Attention Networks.](https://arxiv.org/abs/1912.08409) **Key Features:** - Scalable and flexible model construction for deep plain and resnet architectures. - Model_1: Plain CoulGAT with pooling option for final layer. - Model_2: Resnet CoulGAT with pooling option for final layer. - Model_3: Plain CoulGAT composed of attention layer blocks with pooling at end of each block. - Model_4: Resnet CoulGAT with pooling at the end of each resnet block. - SCCLMAE loss for nonzero labels only or MSE/Huber/MAE loss for all labels - Uses Adam optimizer | 1,620 |
bwilder0/clusternet | ['link prediction'] | ['End to end learning and optimization on graphs'] | experiments_singlegraph.py loss_functions.py experiments_inductive.py models.py modularity.py utils.py kcenter.py train_twostage train_gcn_model fine_tune get_average_loss get_kcenter_test_loss test_twostage train_twostage gonzalez_kcenter make_dists_igraph greedy_kcenter CenterObjective make_all_dists rounding loss_modularity loss_kcenter GCNLink GCNClusterNet GCNDeepSigmoid GCNDeep cluster GCN _divide get_mod_matrix make_modularity_matrix_nodiag improve_modularity partition get_modularity largest_eig get_base_modularity_matrix _get_delta_Q greedy_modularity_communities make_modularity_matrix baseline_spectral edge_dropout load_nofeatures make_normalized_adj negative_sample sparse_mx_to_torch_sparse_tensor accuracy load_data encode_onehot normalize model softmax item sum range model K item append sum range rounding model backward zero_grad Adam parameters loss_fn step range edge_dropout get_evaluation model_ts make_normalized_adj negative_sample backward print zero_grad Adam choice t parameters negsamplerate step range use_igraph arange tensor max view partition greedy_kcenter sum make_modularity_matrix range baseline_spectral gonzalez_kcenter make_dists_igraph greedy_modularity_communities item float long model_ts print repeat make_all_dists zeros diag backward print zero_grad choice get_average_loss item append step range numpy roc_auc_score append zeros item zeros CenterObjective obj range zeros_like from_numpy_array numpy range shortest_path_length concatenate Read_Ncol reshape rand savetxt tensor numpy array shortest_paths max clone range len ones eye sigmoid sum obj K _k_init norm check_random_state squeeze range t numpy softmax tensor sum diag ones t unsqueeze eye sum ones t unsqueeze eye sum eigh numpy zeros range degree heappop heappush push list MappedQueue nodes append sum update frozenset set keys modularity enumerate pop remove print dict from_numpy_array zeros numpy len _divide subgraph get_base_modularity_matrix set difference from_numpy_array append zeros numpy range get_mod_matrix improve_modularity tuple eigs asmatrix largest_eig _get_delta_Q array csc_matrix get_mod_matrix pop list size index _get_delta_Q append zeros argmax array range len dot set_edge_attributes list print in_degree astype out_degree copy degree dict number_of_edges sum list sum diag get_base_modularity_matrix todense eig int format make_normalized_adj loadtxt long max to_sparse zeros range long randint int arange choice multiply coo_matrix eye normalize numpy get list map set array genfromtxt list todense FloatTensor csr_matrix multiply shape normalize range format LongTensor coo_matrix unique long print sort reshape sparse_mx_to_torch_sparse_tensor eye zeros array diags flatten dot sum array sum type_as double data Size astype float32 from_numpy shape int64 | # ClusterNet This code implements and evaluates the ClusterNet method described in the NeurIPS 2019 [paper](https://arxiv.org/abs/1905.13732) "End to End Learning and Optimization on Graphs". ClusterNet provides a differentiable k-means clustering layer which is used as a building block for solving graph optimization problems. ``` @inproceedings{wilder2019end, title={End to End Learning and Optimization on Graphs}, author={Wilder, Bryan and Ewing, Eric and Dilkina, Bistra and Tambe, Milind}, booktitle={Advances in Neural and Information Processing Systems}, year={2019} } ``` | 1,621 |
bxshi/DiscourseVisualization | ['argument mining'] | ['Visualizing the Flow of Discourse with a Concept Ontology'] | tocsv.py get_values parse_values filter_row is_insert values_sanity_check main append enumerate writer chr reader writerow filter_row append stdout get_values parse_values add_argument files is_insert values_sanity_check ArgumentParser input parse_args | bxshi/DiscourseVisualization | 1,622 |
byangderek/CCF | ['object proposal generation', 'pedestrian detection', 'face detection', 'edge detection'] | ['Convolutional Channel Features'] | caffe/python/caffe/classifier.py caffe/python/caffe/test/test_net.py caffe/tools/extra/resize_and_crop_images.py caffe/python/caffe/layers.py caffe/src/caffe/test/test_data/generate_sample_data.py caffe/python/detect.py caffe/python/caffe/detector.py caffe/python/draw_net.py caffe/examples/finetune_flickr_style/assemble_data.py caffe/tools/extra/extract_seconds.py caffe/python/caffe/io.py caffe/python/caffe/__init__.py caffe/examples/web_demo/app.py caffe/python/classify.py caffe/python/caffe/draw.py caffe/scripts/download_model_binary.py caffe/tools/extra/parse_log.py caffe/examples/web_demo/exifutil.py caffe/python/caffe/test/test_python_layer.py caffe/python/caffe/test/test_solver.py caffe/scripts/cpp_lint.py caffe/scripts/copy_notebook.py caffe/examples/python_nets/caffenet.py caffe/python/caffe/pycaffe.py download_image make_net max_pool conv_relu alexnet fc_relu start_tornado start_from_terminal embed_image_html classify_upload index allowed_file ImagenetClassifier classify_url open_oriented_im apply_orientation main main parse_args Classifier Detector determine_node_label_by_layertype draw_net determine_edge_label_by_layertype get_pydot_graph choose_color_by_layertype get_pooling_types_dict draw_net_to_file Transformer blobproto_to_array datum_to_array array_to_blobproto arraylist_to_blobprotovecor_str array_to_datum resize_image blobprotovector_str_to_arraylist load_image oversample Layers Function Parameters uncamel Top assign_proto to_proto _Net_blobs _Net_forward_all _Net_set_input_arrays _Net_backward _Net_params _Net_forward _Net_outputs _Net_forward_backward_all _Net_batch _Net_inputs simple_net_file TestNet python_net_file SimpleLayer TestPythonLayer TestSolver ParseNolintSuppressions CheckVlogArguments CheckSectionSpacing FindNextMultiLineCommentEnd ReplaceAll CheckForFunctionLengths _SetOutputFormat _IsTestFilename _VerboseLevel CheckBraces RemoveMultiLineComments ResetNolintSuppressions CheckForNonStandardConstructs _SetVerboseLevel PrintUsage _NestingState CheckIncludeLine CheckAccess _CppLintState Search CheckInvalidIncrement RemoveMultiLineCommentsFromRange CleansedLines CheckForBadCharacters UpdateIncludeState FindPreviousMatchingAngleBracket CheckEmptyBlockBody FindNextMultiLineCommentStart Match _NamespaceInfo CheckMakePairUsesDeduction CheckCheck IsBlankLine _SetFilters ProcessLine _FunctionState CheckPosixThreading GetLineWidth GetHeaderGuardCPPVariable IsCppString _IncludeState CheckSpacing _ClassInfo CheckForCopyright IsErrorSuppressedByNolint ProcessFileData CheckForMultilineCommentsAndStrings CloseExpression _PreprocessorInfo _OutputFormat CheckForIncludeWhatYouUse CheckSpacingForFunctionCall FindEndOfExpressionInLine FindNextMatchingAngleBracket _SetCountingStyle ProcessFile _IncludeError CleanseRawStrings CheckAltTokens CheckForNewlineAtEOF ParseArguments CheckForNonConstReference PrintCategories _Filters main FilesBelongToSameModule CheckCStyleCast FileInfo _BlockInfo CheckForHeaderGuard CheckCaffeDataLayerSetUp ReverseCloseExpression CleanseComments _DropCommonSuffixes _ClassifyInclude CheckStyle CheckCaffeAlternatives FindStartOfExpressionInLine _ShouldPrintError CheckComment Error _GetTextInside CheckLanguage CheckCaffeRandom GetPreviousNonBlankLine reporthook parse_readme_frontmatter model_checks_out valid_dirname get_start_time extract_seconds extract_datetime_from_line get_log_created_year write_csv parse_log get_line_type save_csv_files main parse_args ResizeCropImagesMapper PILResizeCrop OpenCVResizeCrop urlretrieve Convolution InnerProduct Data SoftmaxWithLoss LRN Accuracy max_pool InnerProduct conv_relu fc_relu Dropout get read info load_image classify_image StringIO join replace info secure_filename save filename open_oriented_im classify_image fromarray replace astype save resize StringIO items list listen HTTPServer format print start WSGIContainer update start_tornado add_option OptionParser debug port parse_args ImagenetClassifier forward run hasattr _getexif astype float32 tile apply_orientation open transpose model_def endswith ArgumentParser DataFrame mean_file channel_swap Detector output_file dirname parse_args input_file format gpu to_hdf detect_selective_search mean set_mode_cpu load time set_index print add_argument to_csv set_mode_gpu pretrained_model detect_windows read_csv len add_argument ArgumentParser read NetParameter output_image_file rankdir Merge draw_net_to_file items list DESCRIPTOR batch_size str num_output get_pooling_types_dict add_edge determine_node_label_by_layertype list Dot values name determine_edge_label_by_layertype choose_color_by_layertype Edge Node bottom append type layer add_node top shape BlobProto extend flat extend BlobProtoVector ParseFromString BlobProtoVector extend tostring shape Datum flat data len astype float32 tile zoom tuple resize fill empty array concatenate shape tile empty array items list isinstance extend getattr setattr list NetParameter _to_proto extend OrderedDict values items list layers index set outputs _forward len items list _backward layers inputs index set len items list asarray extend copy next _batch iter forward values len items list asarray backward extend next _batch zip_longest zip iter forward values len ascontiguousarray list concatenate iter num zeros next range values len NamedTemporaryFile str close write error search add group clear compile compile compile SetOutputFormat SetCountingStyle SetFilters _Filters startswith IsErrorSuppressedByNolint _ShouldPrintError write IncrementErrorCount replace append Match group find startswith endswith range error FindNextMultiLineCommentEnd RemoveMultiLineCommentsFromRange FindNextMultiLineCommentStart rstrip find range len FindEndOfExpressionInLine range len FindStartOfExpressionInLine error min search I range len FileInfo RepositoryName sep sub ParseNolintSuppressions error startswith split GetHeaderGuardCPPVariable enumerate error enumerate error len error replace count error find error find error find error find error Search error match InnermostClass replace error escape Match Search error group Search Check error lines Count End group Begin NumLines Match raw_lines range Search error match group error Match group pop group append Search pop group append Search elided replace CheckSpacingForFunctionCall rfind error len group min CloseExpression NumLines sub find CheckComment Match range Search lines_without_raw_strings error group starting_linenum Match range Search error rfind len group ReverseCloseExpression Search Match CloseExpression find error Match CloseExpression find elided error strip group FindEndOfExpressionInLine find Match range CloseExpression len error Match finditer normalize isinstance GetLineWidth int InnermostClass CheckCheck error CheckAltTokens CheckBraces CheckSpacing CheckSectionSpacing CheckEmptyBlockBody CheckAccess GetHeaderGuardCPPVariable lines_without_raw_strings _DropCommonSuffixes RepositoryName match split CheckNextIncludeOrder CanonicalizeAlphabeticalOrder FileInfo error search group SetLastHeader match _ClassifyInclude Match pop end search set append values M rstrip replace CheckCStyleCast error _GetTextInside CheckIncludeLine search group lstrip startswith Match ResetSection Search split rfind error group ReverseCloseExpression lstrip findall Match range Search ReplaceAll error Match Search endswith replace setdefault group search CleanseComments open list FilesBelongToSameModule error search copy sub NumLines FullName keys range error search CheckPosixThreading ParseNolintSuppressions CheckVlogArguments CheckMakePairUsesDeduction CheckCaffeDataLayerSetUp CheckLanguage CheckInvalidIncrement CheckCaffeRandom CheckForNonConstReference check_fn Update CheckForNonStandardConstructs CheckStyle raw_lines CheckForMultilineCommentsAndStrings CheckCaffeAlternatives CheckForFunctionLengths CleansedLines _NestingState CheckForBadCharacters CheckForNewlineAtEOF _IncludeState RemoveMultiLineComments CheckForCopyright ResetNolintSuppressions CheckForHeaderGuard NumLines CheckCompletedBlocks CheckForIncludeWhatYouUse range ProcessLine _FunctionState Error rstrip endswith len write ProcessFileData _SetVerboseLevel range split write exit join write exit _VerboseLevel int getopt _SetOutputFormat set _SetVerboseLevel PrintCategories _SetFilters _OutputFormat PrintUsage _SetCountingStyle split getreader ParseArguments ResetErrorCounts stderr exit verbose_level PrintErrorCounts StreamReaderWriter ProcessFile getwriter int time write flush load join index int rfind datetime split getctime year strip extract_datetime_from_line get_start_time total_seconds strip write get_log_created_year close extract_datetime_from_line open float get_log_created_year compile join basename write_csv print parse_log save_csv_files output_dir logfile_path | # README # The codes are with the ICCV2015 paper ["Convolutional Channel Features"](http://arxiv.org/abs/1504.07339). The codes include training and testing of a pedestrian detector on Caltech Pedestrian Dataset. We also provide our trained model for reproduction of the results on Caltech Pedestrian Detection Benchmark ([reasonable](http://www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/rocs/UsaTestRocReasonable.pdf), [detailed](http://www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/rocs/UsaTestRocs.pdf)) reported in the paper. The codes are written in MATLAB, dependent on [Caffe](https://github.com/BVLC/caffe) and [Piotr's Computer Vision Matlab Toolbox](https://github.com/pdollar/toolbox). Codes are tested on Linux 12.04.3 LTS with 128GB memory and a Titan Z GPU. ### Preparation ### * Make the provided Caffe version with matCaffe interface * Download [VGG-16 CaffeModel](https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md) to `./data/CaffeNets/` * Download [Caltech Pedestrian Dataset](http://www.vision.caltech.edu/Image_Datasets/CaltechPedestrians/) and set it up properly with codes in `./data/code3.2.1` ### Demo for pedestrian detection ### * Run `./runDetect.m`, and detection results will be saved as `allBBs.mat` | 1,623 |
byildiz/feature-selection | ['image retrieval'] | ['Distinctive Interest Point Selection for Efficient Near-duplicate Image Retrieval'] | calc_recall.py recall_th.py divide.py recall_count.py merge_recall.py calc_recall_alt.py merge_recall_alt.py query.py find_max_f.py count_groups.py find_variation name_to_int is_in_same_group find_group find_max_group main dist_cmp path_key update_results find_filename find_variation name_to_int is_in_same_group find_group find_max_group main dist_cmp path_key update_results find_filename main find_group find_variation find_filename main main main main find_variation is_in_same_group find_group find_max_group main path_key update_results find_filename find_variation name_to_int is_in_same_group find_group find_max_group main dist_cmp path_key update_results find_filename find_variation name_to_int is_in_same_group find_group find_max_group main dist_cmp path_key update_results find_filename int readline find_variation print len exit find_group split append float update_results range find_filename open find_group find_group append findall int find_group sorted zeros join str endswith write close walk max list items findall | [paper]: https://ieeexplore.ieee.org/document/7459172 [thesis]: http://earsiv.etu.edu.tr/xmlui/handle/20.500.11851/2308 # Distinctive Interest Point Selection for Efficient Near-duplicate Image Retrieval This repository is the official implementation of [Distinctive Interest Point Selection for Efficient Near-duplicate Image Retrieval][paper].  ## Compiling the code ### Requirements - Open CV - Boost - CMake | 1,624 |
byungsook/neural-flow-style | ['style transfer'] | ['Lagrangian Neural Style Transfer for Fluids'] | scene/smokegun.py test_chocolate.py test_smokegun_resim.py util.py styler_base.py styler_3p.py styler_2p.py transform.py config.py vgg.py test_dambreak2d.py test_smokegun.py scene/dambreak2d.py scene/chocolate.py add_argument_group get_config Styler Styler StylerBase main run main run main run main SimG2P run curl rot_mat_poisson rot_mat rot_y_3d rot_z_3d PoissonDisc batch_warp2d rot_mat_turb rot_mat_uniform W batch_affine_warp2d p2g rotate batch_affine_warp3d mgrid _repeat GW subsample p2g_repulsive grad g2p_cubic p2g_grad rot_x_3d _interpolate2d g2p_linear scale batch_warp3d g2p p2g_ batch_mgrid p2g_wavg _interpolate3d advect match_histograms rescale_tf histogram_match_tf resize int_shape save_image prepare_dirs_and_logger draw_voxel yuv2rgb tffunc lap_merge save_video cosine_decay denoise lap_normalize crop_ratio npz2vdb draw_pt save_config lap_split_n get_time resize_tf hsv2rgb str2bool v2rgb make_grid rgb2yuv lap_split normalize_std save_density vgg_16 vgg_arg_scope preprocess repeat load_vgg vgg_19 main main main downup_sample append parse_known_args numParticles tuple set_random_seed gpu_id addAttribute save Styler dataset max prepare_dirs_and_logger seed fromarray list create FLOAT ones data_dir target_frame savefig num_frames legend append range get RandomState draw_pt plot astype set attributeInfo stack trange float enumerate join read log_dir load_img VECTOR print d_path addParticle min write len run max disc radius resolution zeros savez_compressed arange resampling SimG2P v_path exp INT naive_adv sum concatenate scale sample uint8 optimize transmit array num_frames resampling pop float32 stack cast meshgrid expand_dims mgrid tile slice reshape _interpolate2d slice reshape _interpolate3d ones reshape matmul reshape float32 gather expand_dims cast clip_by_value floor add_n zeros _repeat range reshape float32 gather expand_dims cast clip_by_value floor add_n zeros _repeat range slice reshape matmul batch_mgrid batch_warp2d slice reshape matmul batch_mgrid batch_warp3d concat concat to_int32 transpose greater where max_pool batch_mgrid logical_or max_pool3d batch_warp2d batch_warp3d reshape matmul placeholder batch_mgrid tile batch_warp3d to_int32 multiply float32 batch_mgrid cast batch_warp2d array cos pi sin array cos pi sin array cos pi sin array append rot_y_3d rot_mat_poisson rot_y_3d rot_z_3d matmul append rot_mat_uniform sample PoissonDisc max append append float abs linspace _hermite reshape float32 gather expand_dims cast clip_by_value floor zeros _repeat range reshape float32 gather expand_dims cast clip_by_value floor add_n zeros _repeat range interpolate_scatter3d reshape concat logical_and float32 W boolean_mask cast clip_by_value floor int32 tile expand_dims reduce_all range append interpolate_scatter2d interpolate_scatter3d GW reshape concat logical_and float32 boolean_mask cast clip_by_value floor int32 tile expand_dims reduce_all range append interpolate_scatter2d interpolate_scatter3d reshape concat logical_and float32 W boolean_mask where cast clip_by_value floor int32 tile expand_dims reduce_all range append interpolate_scatter2d interpolate_scatter3d reshape concat float32 W floor clip_by_value cast int32 tile expand_dims range append interpolate_scatter2d interpolate_scatter3d reshape concat transpose floor int32 cast tile append add_n expand_dims range W min cos pi append range lap_split list lap_merge map lap_split_n reduce_mean expand_dims abs list map placeholder as_list shape transpose reshape resize reshape transpose float32 shape cast int32 resize float astype float32 stack append range fromarray uint8 astype save dtype mod where shape cast int32 zeros abs equal float64 astype shape unique interp ravel cumsum reshape reduce_max divide add flatten shape int64 cast clip_by_value gather histogram_fixed_width reduce_min range py_func str join format argv log_dir save_config chdir tag get_time dirname dataset makedirs print join log_dir join sorted format glob get_writer close rmtree append_data imread ones_like uint8 arctan2 hsv_to_rgb astype pi sqrt stack max int min ceil zeros float range fromarray make_grid save Vector3dVector stack argwhere draw_geometries PointCloud call savez_compressed LineSet create_mesh_coordinate_frame Visualizer draw_geometries_with_key_callbacks Vector3dVector loadframe append Vector2iVector range PointCloud pop OrderedDict get_model_variables vgg_arg_scope preprocess init assign_from_checkpoint_fn join print data_dir call append sh makedirs src_x_pos obstacle copyArrayToGridMAC vec3 resolution_x save resize advectSemiLagrange savez_compressed show fromarray create exp src_radius data_dir path_format Gui num_frames copyGridToArrayReal bWidth fillGrid sum resolution_y applyToGrid astype mkdir open_bound trange src_z_pos join uint8 src_y_pos resolution_z buoyancy setOpenBound transmit time_step zeros initDomain step Solver x src_x_pos obstacle vec3 setWallBcs resolution_x copyGridToArrayMAC solvePressure save advectSemiLagrange savez_compressed show fromarray create exp src_radius path_format Gui copyGridToArrayReal bWidth fillGrid sum resolution_y addBuoyancy applyToGrid astype mkdir vorticityConfinement open_bound trange src_z_pos uint8 src_y_pos resolution_z buoyancy setOpenBound transmit time_step zeros initDomain step Solver x | # Lagrangian Neural Style Transfer for Fluids Tensorflow implementation of [Lagrangian Neural Style Transfer for Fluids](http://www.byungsoo.me/project/lnst). [Byungsoo Kim](http://www.byungsoo.me), [Vinicius C. Azevedo](http://graphics.ethz.ch/~vviniciu/), [Markus Gross](https://graphics.ethz.ch/people/grossm), [Barbara Solenthaler](https://graphics.ethz.ch/~sobarbar/) [Computer Graphics Laboratory](https://cgl.ethz.ch/), ETH Zurich  (Note that [Transport-Based Neural Style Transfer for Smoke Simulations (TNST)](http://www.byungsoo.me/project/neural-flow-style) implementation is moved to `tnst` branch.) ## Requirements This code is tested on Windows 10 with GTX 1080 (8GB) and the following requirements: - [Python 3](https://www.python.org/) - [TensorFlow 1.15](https://www.tensorflow.org/install/) | 1,625 |
c-rbp/panoptic_segmentation | ['panoptic segmentation'] | ['Stable and expressive recurrent vision models'] | detectron2/data/datasets/cityscapes_panoptic.py detectron2/modeling/backbone/gnbn.py projects/DensePose/densepose/densepose_coco_evaluation.py tests/test_checkpoint.py detectron2/modeling/proposal_generator/build.py detectron2/evaluation/cityscapes_evaluation.py detectron2/modeling/backbone/gnbn_lowlevel.py detectron2/utils/visualizer.py detectron2/utils/collect_env.py detectron2/modeling/backbone/gnbnOLD.py tools/visualize_data.py projects/TensorMask/tensormask/arch.py detectron2/modeling/anchor_generator.py detectron2/data/detection_utils.py detectron2/modeling/proposal_generator/rpn_outputs.py detectron2/modeling/proposal_generator/rpn.py detectron2/checkpoint/__init__.py projects/TridentNet/tridentnet/trident_rcnn.py tests/test_data_loader.py projects/TensorMask/tests/__init__.py detectron2/modeling/postprocessing.py detectron2/config/compat.py detectron2/modeling/meta_arch/fully_rec_panoptic_fpn.py projects/TensorMask/tensormask/layers/swap_align2nat.py projects/DensePose/train_net.py detectron2/model_zoo/__init__.py detectron2/evaluation/sem_seg_evaluation.py detectron2/evaluation/lvis_evaluation.py detectron2/utils/registry.py detectron2/modeling/backbone/backbone.py detectron2/modeling/roi_heads/fast_rcnn.py tests/test_boxes.py detectron2/data/datasets/lvis.py projects/TensorMask/tensormask/layers/__init__.py projects/TensorMask/tests/test_swap_align2nat.py detectron2/modeling/roi_heads/mask_head.py detectron2/data/samplers/__init__.py detectron2/data/datasets/coco_panoptic.py projects/DensePose/densepose/evaluator.py detectron2/utils/logger.py detectron2/structures/__init__.py detectron2/modeling/meta_arch/semantic_seg.py detectron2/modeling/backbone/fpnOLD.py detectron2/modeling/meta_arch/retinanet.py detectron2/export/caffe2_export.py detectron2/export/shared.py detectron2/data/samplers/grouped_batch_sampler.py detectron2/layers/roi_align.py setup.py detectron2/modeling/roi_heads/rotated_fast_rcnn.py detectron2/utils/events.py detectron2/layers/roi_align_rotated.py detectron2/utils/video_visualizer.py detectron2/data/samplers/distributed_sampler.py detectron2/modeling/sampling.py detectron2/utils/__init__.py projects/DensePose/apply_net.py detectron2/structures/image_list.py projects/PointRend/point_rend/config.py detectron2/evaluation/panoptic_evaluation.py detectron2/layers/__init__.py detectron2/modeling/roi_heads/roi_heads.py detectron2/modeling/backbone/__init__.py docs/conf.py projects/PointRend/point_rend/point_features.py detectron2/data/transforms/transform_gen.py tools/visualize_json_results.py detectron2/utils/comm.py detectron2/evaluation/testing.py detectron2/structures/instances.py detectron2/data/__init__.py detectron2/modeling/box_regression.py detectron2/solver/lr_scheduler.py projects/TridentNet/tridentnet/trident_rpn.py tools/train_net.py detectron2/data/datasets/pascal_voc.py detectron2/export/caffe2_modeling.py detectron2/data/catalog.py detectron2/config/__init__.py detectron2/modeling/test_time_augmentation.py projects/DensePose/densepose/vis/extractor.py projects/TensorMask/tensormask/config.py detectron2/modeling/proposal_generator/rrpn_outputs.py detectron2/modeling/roi_heads/box_head.py projects/DensePose/densepose/structures.py tests/test_roi_align.py detectron2/modeling/meta_arch/__init__.py detectron2/export/c10.py detectron2/export/__init__.py projects/DensePose/densepose/utils/dbhelper.py detectron2/modeling/backbone/rnns_OLD.py demo/demo.py detectron2/solver/build.py detectron2/export/patcher.py tools/benchmark.py projects/PointRend/point_rend/__init__.py detectron2/data/transforms/__init__.py detectron2/config/defaults.py detectron2/export/caffe2_inference.py tests/test_roi_pooler.py tests/test_model_e2e.py projects/DensePose/densepose/densepose_head.py detectron2/modeling/meta_arch/rcnn.py projects/DensePose/densepose/config.py detectron2/checkpoint/catalog.py detectron2/layers/batch_norm.py detectron2/data/datasets/coco.py detectron2/evaluation/__init__.py tests/test_sampler.py projects/TensorMask/train_net.py projects/DensePose/densepose/roi_head.py detectron2/checkpoint/detection_checkpoint.py projects/DensePose/densepose/dataset.py projects/TridentNet/tridentnet/config.py projects/TridentNet/tridentnet/trident_conv.py detectron2/export/api.py detectron2/structures/keypoints.py detectron2/engine/__init__.py detectron2/utils/serialize.py detectron2/config/config.py projects/DensePose/densepose/dataset_mapper.py detectron2/utils/file_io.py projects/DensePose/densepose/vis/bounding_box.py detectron2/engine/train_loop.py detectron2/modeling/matcher.py projects/DensePose/densepose/vis/base.py detectron2/data/dataset_mapper.py detectron2/data/datasets/cityscapes.py detectron2/modeling/proposal_generator/proposal_utils.py detectron2/data/datasets/builtin.py detectron2/modeling/roi_heads/cascade_rcnn.py get_timestep_results.py projects/TridentNet/tridentnet/__init__.py detectron2/data/transforms/transform.py tools/panoptic_visualization.py detectron2/modeling/proposal_generator/rrpn.py detectron2/engine/hooks.py detectron2/layers/mask_ops.py projects/PointRend/train_net.py projects/TridentNet/tridentnet/trident_backbone.py tests/test_roi_heads.py detectron2/modeling/backbone/fpnmine.py demo/predictor.py detectron2/data/datasets/__init__.py detectron2/data/datasets/builtin_meta.py detectron2/modeling/roi_heads/keypoint_head.py detectron2/model_zoo/model_zoo.py tests/test_nms_rotated.py detectron2/data/build.py detectron2/evaluation/rotated_coco_evaluation.py tests/test_anchor_generator.py tests/test_data_transform.py tests/test_rpn.py detectron2/modeling/backbone/gn.py detectron2/modeling/roi_heads/__init__.py detectron2/data/datasets/lvis_v1_categories.py detectron2/modeling/proposal_generator/__init__.py projects/TensorMask/setup.py projects/PointRend/point_rend/point_head.py tests/test_model_zoo.py detectron2/checkpoint/c2_model_loading.py projects/PointRend/point_rend/roi_heads.py detectron2/__init__.py detectron2/data/datasets/register_coco.py tests/test_mask_ops.py detectron2/layers/nms.py detectron2/modeling/meta_arch/build.py tests/test_rotated_boxes.py detectron2/modeling/backbone/rnns.py detectron2/structures/masks.py projects/DensePose/densepose/utils/logger.py detectron2/solver/__init__.py detectron2/evaluation/coco_evaluation.py detectron2/layers/wrappers.py projects/DensePose/densepose/__init__.py detectron2/engine/defaults.py detectron2/modeling/backbone/gnbn_horizontal.py projects/DensePose/query_db.py detectron2/utils/memory.py tests/test_visualizer.py tools/caffe2_converter.py detectron2/layers/deform_conv.py tools/plain_train_net.py detectron2/structures/rotated_boxes.py projects/DensePose/densepose/vis/densepose.py projects/TridentNet/train_net.py detectron2/modeling/backbone/resnet.py detectron2/modeling/backbone/gnbn_lowlevel_lesssp.py detectron2/layers/rotated_boxes.py tests/test_box2box_transform.py detectron2/modeling/backbone/fpn.py tests/test_roi_align_rotated.py detectron2/utils/colormap.py detectron2/evaluation/pascal_voc_evaluation.py projects/PointRend/point_rend/coarse_mask_head.py detectron2/modeling/backbone/build.py detectron2/modeling/__init__.py tests/test_fast_rcnn.py detectron2/modeling/meta_arch/panoptic_fpn.py detectron2/utils/env.py projects/TensorMask/tensormask/__init__.py tests/test_config.py detectron2/engine/launch.py detectron2/layers/shape_spec.py detectron2/data/datasets/lvis_v0_5_categories.py detectron2/modeling/poolers.py tests/__init__.py detectron2/evaluation/evaluator.py detectron2/structures/boxes.py detectron2/data/common.py get_results get_model_zoo_configs get_extensions get_version get_parser setup_cfg VisualizationDemo AsyncPredictor convert_c2_detectron_names convert_basic_c2_names align_and_update_state_dicts Detectron2Handler ModelCatalogHandler ModelCatalog DetectionCheckpointer upgrade_config downgrade_config _rename _RenameConverter ConverterV2 ConverterV1 guess_version set_global_cfg get_cfg CfgNode print_instances_class_histogram build_detection_test_loader filter_images_with_few_keypoints build_detection_train_loader load_proposals_into_dataset worker_init_reset_seed get_detection_dataset_dicts trivial_batch_collator filter_images_with_only_crowd_annotations _quantize MetadataCatalog DatasetCatalog Metadata AspectRatioGroupedDataset DatasetFromList MapDataset DatasetMapper check_metadata_consistency annotations_to_instances transform_instance_annotations annotations_to_instances_rotated transform_proposals gen_crop_transform_with_instance build_transform_gen check_image_size create_keypoint_hflip_indices SizeMismatchError filter_empty_instances transform_keypoint_annotations read_image register_all_coco register_all_pascal_voc register_all_cityscapes register_all_lvis register_all_ade20k _get_coco_instances_meta _get_builtin_metadata _get_coco_panoptic_separated_meta _get_cityscapes_files load_cityscapes_instances load_cityscapes_semantic _cityscapes_files_to_dict register_all_cityscapes_panoptic get_cityscapes_panoptic_files load_cityscapes_panoptic convert_to_coco_json load_coco_json register_coco_instances convert_to_coco_dict load_sem_seg register_coco_panoptic register_coco_panoptic_separated load_coco_panoptic_json merge_to_panoptic register_lvis_instances _get_lvis_instances_meta_v1 _get_lvis_instances_meta_v0_5 get_lvis_instances_meta load_lvis_json load_voc_instances register_pascal_voc RepeatFactorTrainingSampler InferenceSampler TrainingSampler GroupedBatchSampler ExtentTransform Resize_rotated_box ResizeTransform HFlip_rotated_box TransformGen RandomFlip RandomSaturation check_dtype RandomLighting apply_transform_gens RandomContrast Resize RandomCrop ResizeShortestEdge RandomExtent RandomBrightness DefaultTrainer save_activation default_setup DefaultPredictor default_argument_parser PeriodicCheckpointer LRScheduler IterationTimer PreciseBN CallbackHook PeriodicWriter AutogradProfiler EvalHook launch _distributed_worker _find_free_port SimpleTrainer HookBase TrainerBase CityscapesEvaluator instances_to_coco_json COCOEvaluator _evaluate_box_proposals _evaluate_predictions_on_coco inference_context inference_on_dataset DatasetEvaluator DatasetEvaluators set_bn_eval _evaluate_predictions_on_lvis _evaluate_box_proposals LVISEvaluator COCOPanopticEvaluator _print_panoptic_results PascalVOCDetectionEvaluator parse_rec voc_eval voc_ap RotatedCOCOeval RotatedCOCOEvaluator SemSegEvaluator verify_results print_csv_format flatten_results_dict Caffe2Model add_export_config export_caffe2_model Caffe2KeypointRCNNInference Caffe2RPN Caffe2Compatible Caffe2FastRCNNOutputsInference Caffe2MaskRCNNInference Boxes4or5 Caffe2ROIPooler InstancesList run_and_save_graph _op_stats export_caffe2_detection_model _assign_device_option _export_via_onnx ProtobufDetectionModel ProtobufModel Caffe2GeneralizedRCNN Caffe2RetinaNet set_caffe2_compatible_tensor_mode _cast_to_f32 Caffe2PanopticFPN Caffe2MetaArch assemble_rcnn_outputs_by_name convert_batched_inputs_to_c2_format GenericMixin mock_fastrcnn_outputs_inference ROIHeadsPatcher patch Caffe2CompatibleConverter patch_generalized_rcnn mock_mask_rcnn_inference mock_keypoint_rcnn_inference rename_op_input get_sub_graph_external_input_output to_device IllegalGraphTransformError mock_torch_nn_functional_interpolate save_graph_base identify_reshape_sub_graph alias remove_reshape_for_fc construct_init_net_from_params DiGraph get_params_from_init_net get_pb_arg_valstrings _modify_blob_names _rename_blob group_norm_replace_aten_with_caffe2 _rename_versioned_blob_in_proto get_pb_arg_ints ScopedWS get_pb_arg_vals save_graph get_pb_arg_floats fuse_copy_between_cpu_and_gpu get_pb_arg_vali get_pb_arg_valf _generic_status_identifier onnx_compatibale_interpolate remove_dead_end_ops get_pb_arg BilinearInterpolation check_set_pb_arg infer_device_type fetch_any_blob get_producer_map fuse_alias_placeholder rename_op_output _get_dependency_chain _updater_raise _create_const_fill_op_from_numpy create_const_fill_op get_consumer_map _create_const_fill_op_from_c2_int8_tensor NaiveSyncBatchNorm FrozenBatchNorm2d AllReduce get_norm ModulatedDeformConv DeformConv _ModulatedDeformConv _DeformConv paste_mask_in_image_old pad_masks _do_paste_mask paste_masks_in_image scale_boxes nms_rotated batched_nms_rotated batched_nms ROIAlign _ROIAlign _ROIAlignRotated ROIAlignRotated pairwise_iou_rotated ShapeSpec _NewEmptyTensorOp interpolate cat Conv2d RotatedAnchorGenerator build_anchor_generator _create_grid_offsets BufferList DefaultAnchorGenerator Box2BoxTransformRotated Box2BoxTransform Matcher convert_boxes_to_pooler_format assign_boxes_to_levels ROIPooler detector_postprocess sem_seg_postprocess subsample_labels DatasetMapperTTA GeneralizedRCNNWithTTA Backbone build_backbone FPNINDIV2 build_resnet_fpn_backbone FPN build_resnet_fpnindi_explain_backbone FPNGN build_resnet_fpnindi_explain_post_cbp10_backbone build_retinanet_resnet_fpngn_backbone build_resnet_fpnlateral_cbp10_backbone build_resnet_fpn_gnbn_horizontal_cbp10_backbone build_resnet_fpnindiv2_cbp10_noskip_backbone build_resnet_fpn_gnbn_lowlevel_gala_cbp10_backbone build_resnet_fpnindi_gala_backbone build_resnet_fpn_gnbn_lowlevel_bptt3_backbone build_resnet_fpngn_cbp10_backbone FPNINDI build_resnet_fpnindi_explain_cbp10_backbone build_resnet_fpn_gnbn_backbone build_resnet_fpnindiv2_cbp10_backbone build_resnet_fpn_gnbn_lowlevel_cbp10_backbone LastLevelMaxPool build_resnet_fpnlateral_backbone FPNLATERAL build_resnet_fpngn_backbone build_resnet_fpn_gnbn_lowlevel_backbone build_resnet_fpnlateral_cbp20_backbone build_retinanet_resnet_fpn_backbone build_resnet_fpnindi_backbone LastLevelP6P7 build_resnet_fpn_gnbn_lowlevel_lesssp_cbp10_backbone LastLevelP6P7GN build_resnet_fpn_gn_backbone build_resnet_fpngn_gala_backbone build_resnet_fpnindiv2_backbone FPNINDIEXPLAIN build_resnet_fpnindi_explain_post_backbone _assert_strides_are_log2_contiguous LastLevelMaxPool build_retinanet_resnet_fpn_backbone build_resnet_fpn_backbone FPN FPNINDI build_resnet_fpnindi_backbone LastLevelP6P7 FPNGN build_resnet_fpn_gnbn_backbone build_retinanet_resnet_fpngn_backbone LastLevelP6P7GN build_resnet_fpngn_backbone build_resnet_fpngn_gala_backbone build_resnet_fpn_gn_backbone build_resnet_fpn_gnbn_lowlevel_backbone build_resnet_fpngn_cbp10_backbone _assert_strides_are_log2_contiguous LastLevelMaxPool build_retinanet_resnet_fpn_backbone build_resnet_fpn_backbone FPN LastLevelP6P7 _assert_strides_are_log2_contiguous ResNet ResNetBlockBase BottleneckBlock DeformBottleneckBlock make_stage BasicStem build_resnet_gn_backbone build_resnet_gnbn_backbone ResNet ResNetBlockBase BottleneckBlock DeformBottleneckBlock make_stage BasicStem build_resnet_gnbn_backbone tdConvGRUCell ResNet ResNetBlockBase BottleneckBlock DeformBottleneckBlock hConvGRUCell make_stage BasicStem build_resnet_gnbn_horizontal_backbone ResNet ResNetBlockBase BottleneckBlock DeformBottleneckBlock make_stage BasicStem build_resnet_gnbn_lowlevel_model_backbone ResNet ResNetBlockBase BottleneckBlock DeformBottleneckBlock make_stage BasicStem ResNet build_resnet_gnbn_lowlevel_lesssp_backbone ResNetBlockBase BottleneckBlock DeformBottleneckBlock make_stage BasicStem ResNet ResNetBlockBase BottleneckBlock build_resnet_backbone DeformBottleneckBlock make_stage BasicStem tdConvGRUCell CBP_penalty hConvGRUExtraSMCell hConvGRUCellv2 RBPFun hConvGRUCell hConvExplGRUCell tdConvGRUCellOld hConvGRUCellOld CBPForward hConvGRUCell RBPFun tdConvGRUCell build_model combine_semantic_and_instance_outputs FPN PanopticFPN combine_semantic_and_instance_outputs PanopticFPN ProposalNetwork GeneralizedRCNN permute_all_cls_and_box_to_N_HWA_K_and_concat permute_to_N_HWA_K RetinaNet RetinaNetHead SemanticSegmentor SemSegFPNHead build_sem_seg_head RecurrentSemSegFPNHead build_proposal_generator add_ground_truth_to_proposals add_ground_truth_to_proposals_single_image RPN StandardRPNHead build_rpn_head rpn_losses RPNOutputs find_top_rpn_proposals RRPN RRPNOutputs find_top_rrpn_proposals FastRecurrentRCNNConvFCHead build_box_head FastRCNNConvFCHead _ScaleGradient CascadeROIHeads FastRCNNOutputs fast_rcnn_inference fast_rcnn_inference_single_image FastRCNNOutputLayers build_keypoint_head keypoint_rcnn_inference KRCNNConvDeconvUpsampleHead keypoint_rcnn_loss RecurrentMaskRCNNConvUpsampleHead mask_rcnn_inference MaskRCNNConvUpsampleHead build_mask_head RecurrentSPMaskRCNNConvUpsampleHead Recurrent5MaskRCNNConvUpsampleHead Recurrentv1MaskRCNNConvUpsampleHead mask_rcnn_loss Res5ROIHeads build_roi_heads ROIHeads select_proposals_with_visible_keypoints select_foreground_proposals StandardROIHeads RROIHeads RotatedFastRCNNOutputs fast_rcnn_inference_single_image_rotated fast_rcnn_inference_rotated get get_checkpoint_url get_config_file _ModelZooUrls build_lr_scheduler build_optimizer WarmupMultiStepLR WarmupCosineLR _get_warmup_factor_at_iter pairwise_iou matched_boxlist_iou BoxMode Boxes ImageList Instances Keypoints _keypoints_to_heatmap heatmaps_to_keypoints polygon_area BitMasks polygons_to_bitmask rasterize_polygons_within_box PolygonMasks pairwise_iou RotatedBoxes detect_compute_compatibility get_env_module collect_torch_env collect_env_info random_color det_random_color colormap get_local_size synchronize get_world_size get_local_rank reduce_dict _get_global_gloo_group shared_random_seed all_gather get_rank gather _serialize_to_tensor is_main_process _pad_to_largest_tensor setup_environment setup_custom_environment _configure_libraries _import_file seed_all_rng EventStorage TensorboardXWriter EventWriter get_event_storage JSONWriter CommonMetricPrinter Detectron2Handler _cached_log_stream log_first_n _find_caller setup_logger log_every_n create_small_table _ColorfulFormatter log_every_n_seconds retry_if_cuda_oom _ignore_torch_cuda_oom PicklableWrapper _DetectedInstance VideoVisualizer VisImage Visualizer GenericMask ColorMode _PanopticPrediction _create_text_labels url_resolver setup autodoc_skip_member ShowAction create_argument_parser register_action InferenceAction main DumpAction Action setup_dataset ShowAction create_argument_parser register_action EntrywiseAction main PrintAction Action main setup Trainer add_densepose_config get_densepose_metadata DatasetMapper Params DensePoseDataMode DensePoseCocoEval DensePoseEvalMode DensePoseLosses densepose_inference ASPPPooling build_densepose_predictor _NonLocalBlockND ASPP DensePoseV1ConvXHead _linear_interpolation_utilities DensePoseDataFilter NONLocalBlock2D _resample_data build_densepose_head DensePosePredictor _extract_single_tensors_from_matches _extract_single_tensors_from_matches_one_image build_densepose_losses DensePoseDeepLabHead initialize_module_params ASPPConv _grid_sampling_utilities build_densepose_data_filter _extract_at_points_packed DensePoseCOCOEvaluator _evaluate_predictions_on_coco_gpsm prediction_to_json _evaluate_predictions_on_coco_gps _evaluate_predictions_on_coco Decoder DensePoseROIHeads DensePoseResult DensePoseList normalized_coords_transform DensePoseTransformData DensePoseDataRelative DensePoseOutput AllEntrySelector EntrySelector FieldEntrySelector verbosity_to_level PointsVisualizer CompoundVisualizer RectangleVisualizer TextVisualizer MatrixVisualizer BoundingBoxVisualizer ScoredBoundingBoxVisualizer _extract_v_from_iuvarr DensePoseDataPointsVisualizer DensePoseDataPointsIVisualizer DensePoseDataPointsVVisualizer DensePoseResultsMplContourVisualizer DensePoseDataCoarseSegmentationVisualizer DensePoseResultsVVisualizer DensePoseResultsFineSegmentationVisualizer _densepose_data_i_for_cmap DensePoseOutputsFineSegmentationVisualizer _extract_u_from_iuvarr DensePoseOutputsVVisualizer DensePoseOutputsUVisualizer _densepose_data_v_for_cmap _densepose_data_u_for_cmap DensePoseDataPointsUVisualizer DensePoseResultsVisualizer DensePoseMaskedColormapResultsVisualizer DensePoseResultsCustomContourVisualizer _extract_i_from_iuvarr DensePoseResultsUVisualizer extract_boxes_xywh_from_instances BoundingBoxExtractor ScoreThresholdedExtractor CompoundExtractor ScoredBoundingBoxExtractor DensePoseResultExtractor extract_scores_from_instances NmsFilteredExtractor create_extractor main setup Trainer CoarseMaskHead add_pointrend_config get_uncertain_point_coords_on_grid point_sample get_point_coords_wrt_image point_sample_fine_grained_features generate_regular_grid_point_coords get_uncertain_point_coords_with_randomness StandardPointHead roi_mask_point_loss build_point_head PointRendROIHeads calculate_uncertainty get_extensions main setup Trainer TensorMask TensorMaskAnchorGenerator _paste_mask_lists_in_image _postprocess _assignment_rule TensorMaskHead add_tensormask_config SwapAlign2Nat _SwapAlign2Nat SwapAlign2NatTest main setup Trainer add_tridentnet_config build_trident_resnet_backbone TridentBottleneckBlock make_trident_stage TridentConv merge_branch_instances TridentStandardROIHeads TridentRes5ROIHeads TridentRPN TestAnchorGenerator random_rotated_boxes TestBox2BoxTransformRotated random_boxes TestBox2BoxTransform TestBoxIOU TestBoxMode TestCheckpointer TestConfigVersioning TestTransformAnnotations TestTransforms FastRCNNTest rasterize_polygons_with_grid_sample TestMaskCropPaste benchmark_paste iou_between_full_image_bit_masks create_model_input get_empty_instance RetinaNetE2ETest ModelE2ETest MaskRCNNE2ETest get_regular_bitmask_instances get_model_zoo TestModelZoo TestNMSRotated ROIAlignTest benchmark_roi_align ROIAlignRotatedTest ROIHeadsTest TestROIPooler TestRotatedBoxesLayer TestRotatedBoxesStructure benchmark_rotated_iou RPNTest TestGroupedBatchSampler TestVisualizer benchmark_eval benchmark_data setup benchmark_train setup_cfg parse_args output setup setup get_evaluator do_train main do_test main setup Trainer parse_args output setup create_instances dataset_id_map join stack DataFrame join format strip readlines strftime getenv dirname abspath append get join format glob dirname abspath append join isdir glob unlink realpath rmtree islink symlink dirname exists merge_from_file confidence_threshold config_file get_cfg merge_from_list opts freeze add_argument ArgumentParser deepcopy deepcopy sorted format convert_basic_c2_names zip getLogger tuple shape startswith info keys cat get_missing_parameters_message getLogger tuple warning max values sorted list view tolist shape convert_c2_detectron_names format info keys enumerate error clone get_unexpected_parameters_message len VERSION upgrade clone range VERSION downgrade clone range VERSION format warning getLogger _get _del _set split clear update getLogger format info len getLogger format info len pop format getLogger set info list sorted copy list tabulate arange format chain min log_first_n extend zip_longest colored zeros sum INFO len list check_metadata_consistency thing_classes print_instances_class_histogram filter_images_with_few_keypoints from_iterable zip filter_images_with_only_crowd_annotations getLogger DataLoader SAMPLER_TRAIN BatchSampler get_detection_dataset_dicts RepeatFactorTrainingSampler TrainingSampler ASPECT_RATIO_GROUPING REPEAT_THRESHOLD AspectRatioGroupedDataset format IMS_PER_BATCH get_world_size TRAIN info DatasetMapper MapDataset DatasetFromList len DataLoader MapDataset BatchSampler get_detection_dataset_dicts DatasetMapper DatasetFromList InferenceSampler len randint seed_all_rng pop apply_box convert astype Boxes Instances nonempty XYXY_ABS as_tensor clip decode apply_segmentation isinstance convert XYXY_ABS transform_keypoint_annotations apply_coords reshape decode ndarray Keypoints isinstance BitMasks Boxes Instances stack polygons_to_bitmask append tensor PolygonMasks clip Instances tensor clip RotatedBoxes append nonempty get update check_metadata_consistency keypoint_flip_map dict keypoint_names minimum asarray convert astype maximum randint int32 XYXY_ABS str format getLogger error enumerate str RandomFlip MIN_SIZE_TRAIN_SAMPLING info getLogger MIN_SIZE_TEST MIN_SIZE_TRAIN ResizeShortestEdge MAX_SIZE_TRAIN MAX_SIZE_TEST append get join list items register_coco_panoptic register_coco_instances _get_builtin_metadata register_coco_panoptic_separated register_lvis_instances list join items get_lvis_instances_meta join list format items set _get_builtin_metadata register join register_pascal_voc join register set update _get_coco_instances_meta enumerate ls join append info _get_cityscapes_files format partial map info Pool len append get_local_path _get_cityscapes_files replace list asarray isinstance Polygon endswith bounds geoms id buffer difference is_empty nonzero unique append XYXY_ABS union chain get join info ls append append get_cityscapes_panoptic_files join list items set register warning Timer getCatIds sorted list append anns frPyObjects sum get format XYWH_ABS zip loadImgs info seconds keys enumerate join get_local_path isinstance loadCats len list sorted format zip warn set info append len get int decode hasattr ndarray isinstance tolist convert len reverse_id_mapper item info append XYXY_ABS float sum PolygonMasks enumerate mkdirs dirname register set append int join register set register set update append copy register set Timer load_imgs get_local_path format seconds sorted list zip get get_file_name set get_lvis_instances_meta info LVIS keys append len sorted sorted join get_local_path findall text append find register set width arctan2 cos h pi w new_w sin new_h check_dtype get_transform apply_image append cpu getuid add_argument hash ArgumentParser str read format collect_env_info join config_file CUDNN_BENCHMARK setup_logger get_world_size get_rank mkdirs abspath info OUTPUT_DIR seed_all_rng socket bind close AF_INET SOCK_STREAM _find_free_port spawn main_func list init_process_group new_group synchronize set_device main_func range decode XYWH_ABS has pred_keypoints convert tolist append XYXY_ABS numpy range len arange zeros_like max pairwise_iou Boxes append sum loadAnns range cat getAnnIds mean float proposal_boxes enumerate reshape sort min zeros as_tensor len pop deepcopy evaluate COCOeval summarize imgIds evalImgs accumulate loadRes ious array len str format evaluate getLogger min perf_counter timedelta reset info DatasetEvaluators len _BatchNorm train isinstance eval train training get_ann_ids load_anns pop deepcopy format getLogger LVISResults warn get_results create_small_table print_results info LVISEval run append tabulate info int parse findall text append find arange concatenate size maximum sum max range parse_rec cumsum argmax max sum range eps format astype float minimum reshape maximum voc_ap argsort zeros bool array len join list format items getLogger info str getLogger error exit EXPECTED_RESULTS pformat info abs items list isinstance freeze defrost is_frozen CN get_caffe2_inputs C2MetaArch export_caffe2_detection_model property onnx_graph_to_caffe2_net get_available_passes optimize apply get items sorted list infer_device_type _assign_op_device_option get_ssa deepcopy format remove_reshape_for_fc info construct_init_net_from_params get_params_from_init_net fuse_alias_placeholder fuse_copy_between_cpu_and_gpu _assign_device_option remove_dead_end_ops any encode_additional_info _op_stats colored _export_via_onnx group_norm_replace_aten_with_caffe2 tabulate __name__ format save_graph info get arange keypoint_rcnn_inference pred_classes Boxes int64 zeros to apply get from_tensors image_sizes zip append Tensor named_children isinstance ccc RPN patch ROIPooler device int upsample_filt zeros conv_transpose2d warning isinstance is_in_onnx_export FetchBlob arg get_pb_arg get_pb_arg get_pb_arg get_pb_arg get_pb_arg get_pb_arg format extend MakeArgument warning getattr setattr get_pb_arg update data type NetDef list format items isinstance extend warning append type len range enumerate defaultdict append range enumerate len get_ssa get_producer_map deepcopy get_ssa _update_i op reversed zip union deepcopy list _replace_list map output input append partial GetPydotGraph format print write_svg op GetPydotGraphMinimal dirname _modify_blob_names write_png write_pdf makedirs remove format check_set_pb_arg get_pb_arg_vals op get_pb_arg_vali info get_pb_arg decode rename_op_input rename_op_output op extend get_pb_arg_vali append bool enumerate external_output external_input output op zip input range len deepcopy get_ssa get_producer_map rename_op_output _rename_versioned_blob_in_proto get_ssa _rename_versioned_blob_in_proto get_ssa sum format get_all_paths get_producer_map min from_ssa warning get_consumer_map get_ssa op _get_dependency_chain append enumerate join get_ssa format all deepcopy remove get_sub_graph_external_input_output rename_op_output extend info append identify_reshape_sub_graph _fuse_once get_ssa list all extend reversed add set get_consumer_map enumerate isinstance arange grid_sample size expand stack device to split int arange chunk _do_paste_mask device ceil tensor to zeros len fromarray max uint8 min from_numpy resize zeros to numpy array float new_zeros zeros_like nms view size tolist new_zeros nms_rotated min clone to max _output_size tuple meshgrid reshape arange NAME clamp sqrt log2 floor epsilon cat cat pred_boxes has Instances scale paste_masks_in_image proposal_boxes image_size clip expand int squeeze min numel NAME ShapeSpec enumerate IN_FEATURES OUT_CHANNELS FPNGN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNINDI build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNINDIEXPLAIN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNINDIEXPLAIN build_resnet_backbone IN_FEATURES OUT_CHANNELS build_resnet_backbone FPNINDIV2 IN_FEATURES OUT_CHANNELS build_resnet_backbone FPNINDIV2 IN_FEATURES OUT_CHANNELS build_resnet_backbone FPNINDIV2 IN_FEATURES OUT_CHANNELS FPNLATERAL build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNLATERAL build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNLATERAL build_resnet_backbone IN_FEATURES OUT_CHANNELS build_resnet_backbone FPNINDIV2 IN_FEATURES OUT_CHANNELS FPNINDIEXPLAIN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNINDI build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNGN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNGN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPN build_resnet_backbone IN_FEATURES OUT_CHANNELS FPN build_resnet_gn_backbone IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_model_backbone FPN IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_model_backbone FPN IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_model_backbone FPN IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_model_backbone FPN IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_lesssp_backbone FPN IN_FEATURES build_resnet_gnbn_horizontal_backbone OUT_CHANNELS FPN IN_FEATURES build_resnet_gnbn_backbone OUT_CHANNELS FPN FPN channels build_resnet_backbone IN_FEATURES OUT_CHANNELS FPNGN channels build_resnet_backbone IN_FEATURES OUT_CHANNELS build_resnet_gnbn_lowlevel_backbone append block_class range convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS convert_frozen_batchnorm STEM_OUT_CHANNELS make_stage WIDTH_PER_GROUP max DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate NORM STRIDE_IN_1X1 parameters DEFORM_MODULATED NUM_GROUPS clamp ones_like META_ARCHITECTURE zeros_like tolist argsort item append to shape reshape permute view view NAME NAME ones Instances device image_size log cat len HEAD_NAME arange Instances device tensor clip count all Boxes nonempty append cat isfinite zip batched_nms enumerate sort min image_sizes full len smooth_l1_loss to float32 binary_cross_entropy_with_logits arange RotatedBoxes Instances device tensor clip count all nonempty batched_nms_rotated append cat isfinite zip enumerate sort min image_sizes full len NAME all view reshape Boxes Instances nonzero batched_nms clip NAME put_scalar cross_entropy get_event_storage view gt_keypoints squeeze numel shape cat append tensor to to_heatmap len detach heatmaps_to_keypoints zip cat split put_scalar arange get_event_storage size numel binary_cross_entropy_with_logits item append to max cat arange isinstance sigmoid zip cat split NAME NAME append squeeze gt_classes put_scalar get_event_storage squeeze numel mean unsqueeze any append tensor all view reshape RotatedBoxes Instances batched_nms_rotated nonzero clip replace join resource_filename merge_from_file load build_model get_cfg WEIGHTS get_checkpoint_url get_config_file WEIGHT_DECAY_NORM ADDED_WEIGHT_KEYS isinstance print WEIGHT_DECAY_BIAS AdamW SGD PRETRAINED_LR_SCALE add named_parameters BASE_LR modules BIAS_LR_FACTOR WEIGHT_DECAY LR_SCHEDULER_NAME min area where clamp_ prod zeros max max min area clamp long argmax arange view exp_ clamp squeeze new_zeros ceil float sum max range frPyObjects merge from_numpy deepcopy max polygons_to_bitmask join sorted format check_output strip set isfile append split get str list defaultdict items join format detect_compute_compatibility check_output get_env_module strip device_count is_available tabulate range append origin randint len seed randint len barrier get_world_size format getLogger from_buffer dumps get_rank warning get_backend device to len get_world_size all_gather tensor max zeros cat _serialize_to_tensor _get_global_gloo_group loads zip append max _pad_to_largest_tensor max zip _get_global_gloo_group loads get_rank append _serialize_to_tensor _pad_to_largest_tensor randint all_gather get_world_size seed int set_rng_state format from_bytes get_state getLogger strftime getpid info urandom spec_from_file_location exec_module module_from_spec get int setUseOpenCL get setup_custom_environment _configure_libraries endswith setup_environment _import_file import_module setFormatter join format _cached_log_stream getLogger addHandler StreamHandler Formatter mkdirs _ColorfulFormatter dirname colored DEBUG setLevel f_back _getframe f_code _find_caller log isinstance _find_caller log get time _find_caller log tuple tabulate zip getattr replace add_transform add_config_value connect items list add_parser ArgumentParser set_defaults add_subparsers create_argument_parser setup_logger func setLevel parse_args verbosity_to_level get format timer info merge_from_file config_file add_densepose_config get_cfg setup_logger merge_from_list default_setup opts freeze verify_results setup resume_or_load build_model test WEIGHTS Trainer eval_only is_main_process CN kaiming_normal_ constant_ named_parameters NAME DensePosePredictor DensePoseDataFilter DensePoseOutput len clamp float min unbind _linear_interpolation_utilities unbind arange grid_sample size expand stack u gt_densepose hasattr y view list clone i unsqueeze full_like zip append v tensor range x len _extract_single_tensors_from_matches_one_image size len extend long cat enumerate DensePoseLosses append tolist range len getLogger _evaluate_predictions_on_coco_gpsm warn _evaluate_predictions_on_coco_gps create_small_table info accumulate summarize DensePoseCocoEval evaluate accumulate summarize DensePoseCocoEval evaluate device numpy clip numpy clip N_PART_LABELS numpy clip has clone has error isinstance getLogger add_pointrend_config CN squeeze unsqueeze grid_sample Size tensor affine_grid int arange view rand point_sample uncertainty_func cat float min shape zeros to transpose get_point_coords_wrt_image append tensor enumerate cat split put_scalar arange size numel binary_cross_entropy_with_logits to cat NAME unsqueeze clone add_tensormask_config new_full int all zeros_like size min max cat tolist empty_like paste_masks_in_image unique append tensor cat clip pred_boxes Instances nonempty _paste_mask_lists_in_image image_size CN add_tridentnet_config CN append block_class range convert_frozen_batchnorm STEM_OUT_CHANNELS BRANCH_DILATIONS WIDTH_PER_GROUP max TRIDENT_STAGE DEFORM_NUM_GROUPS FREEZE_AT RES2_OUT_CHANNELS append freeze range OUT_FEATURES DEPTH RES5_DILATION DEFORM_ON_PER_STAGE BasicStem enumerate pop NORM STRIDE_IN_1X1 TEST_BRANCH_IDX parameters DEFORM_MODULATED NUM_BRANCH NUM_GROUPS scores pred_classes append tensor batched_nms range cat len sum arange grid_sample from_numpy shape meshgrid to append randn clamp rand Boxes benchmark manual_seed is_available cat merge_from_file get_cfg get_config_file BitMasks rand Boxes Instances to BitMasks rand Boxes Instances to benchmark is_available stack benchmark append format setup info IMS_PER_BATCH build_detection_train_loader total available iter Timer seconds trange next range virtual_memory load list format setup build_model build_optimizer islice f WEIGHTS build_detection_train_loader DetectionCheckpointer DistributedDataParallel defrost register_hooks info SimpleTrainer train load Timer list format setup build_model model islice build_detection_test_loader WEIGHTS eval defrost info seconds range add_export_config ckpt add_argument ArgumentParser show join print waitKey imshow save evaluator_type join COCOPanopticEvaluator COCOEvaluator SemSegEvaluator append OUTPUT_DIR join format print_csv_format get_evaluator inference_on_dataset build_detection_test_loader OrderedDict info OUTPUT_DIR TEST is_main_process get PeriodicCheckpointer build_lr_scheduler CHECKPOINT_PERIOD format MAX_ITER build_optimizer build_detection_train_loader DetectionCheckpointer info train OUTPUT_DIR format DistributedDataParallel do_train info test_with_TTA OUTPUT_DIR register_hooks update glob ENABLED TIMESTEPS join isdir savez sort isfile format asarray XYWH_ABS convert Boxes Instances XYXY_ABS | Quick build detectron on slurm - bash rebuild_detectron2.sh Download weights - R-FPN ResNet50 trained with C-RBP for 20 steps: `wget https://bashupload.com/qyTMQ/-D4Ro.pth` - R-FPN ResNet101 trained with C-RBP for 20 steps: `wget https://bashupload.com/V_Rhr/lwUiz.pth` - FPN ResNet50: `wget https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_50_1x/139514544/model_final_dbfeb4.pkl` - FPN ResNet101: `wget https://dl.fbaipublicfiles.com/detectron2/COCO-PanopticSegmentation/panoptic_fpn_R_101_3x/139514519/model_final_cafdb1.pkl` Train a model - R-FPN ResNet50 trained with C-RBP for 20 steps: `python tools/train_net.py --num-gpus 10 --config-file configs/COCO-PanopticSegmentation/panoptic_rfpn_R_50_cbp20_1x.yaml SOLVER.IMS_PER_BATCH 40 SOLVER.BASE_LR 0.05` Test a model | 1,626 |
caffe2/aicamera-style-transfer | ['style transfer'] | ['A Neural Algorithm of Artistic Style'] | app/src/main/cpp/caffe2/python/operator_test/lengths_tile_op_test.py app/src/main/cpp/caffe2/python/predictor/predictor_exporter.py app/src/main/cpp/caffe2/python/tt_core.py app/src/main/cpp/caffe2/python/mkl/mkl_speed_test.py app/src/main/cpp/caffe2/contrib/nnpack/nnpack_ops_test.py app/src/main/cpp/caffe2/python/record_queue.py app/src/main/cpp/caffe2/python/rnn/lstm_comparison.py app/src/main/cpp/caffe2/python/predictor/predictor_test.py app/src/main/cpp/caffe2/python/layers/conv.py app/src/main/cpp/caffe2/python/operator_test/mod_op_test.py app/src/main/cpp/caffe2/python/models/seq2seq/seq2seq_beam_search_test.py app/src/main/cpp/caffe2/python/helpers/nonlinearity.py app/src/main/cpp/caffe2/python/lengths_reducer_rowwise_8bit_ops_test.py app/src/main/cpp/caffe2/python/operator_test/segment_ops_test.py app/src/main/cpp/caffe2/python/operator_test/mkl_packed_fc_op_test.py app/src/main/cpp/caffe2/python/crf.py app/src/main/cpp/caffe2/python/context.py app/src/main/cpp/caffe2/python/operator_test/square_root_divide_op_test.py app/src/main/cpp/caffe2/python/layers/semi_random_features.py app/src/main/cpp/caffe2/python/workspace_test.py app/src/main/cpp/caffe2/python/operator_test/conv_transpose_test.py app/src/main/cpp/caffe2/python/mkl/rewrite_graph.py app/src/main/cpp/caffe2/python/parallel_workers.py app/src/main/cpp/caffe2/python/operator_test/counter_ops_test.py app/src/main/cpp/caffe2/python/mkl/mkl_LRN_op_test.py app/src/main/cpp/caffe2/python/task.py app/src/main/cpp/caffe2/python/operator_test/python_op_test.py app/src/main/cpp/caffe2/python/models/__sym_init__.py app/src/main/cpp/caffe2/python/utils.py app/src/main/cpp/caffe2/contrib/script/caffe2_script_test.py app/src/main/cpp/caffe2/python/gradient_checker.py app/src/main/cpp/caffe2/python/tutorials/helpers.py app/src/main/cpp/caffe2/python/modeling/parameter_sharing.py app/src/main/cpp/caffe2/python/operator_test/atomic_ops_test.py app/src/main/cpp/caffe2/python/optimizer_test.py app/src/main/cpp/caffe2/python/layers/batch_softmax_loss.py app/src/main/cpp/caffe2/python/layers/arc_cosine_feature_map.py app/src/main/cpp/caffe2/python/operator_test/gather_ranges_op_test.py app/src/main/cpp/caffe2/python/observer_test.py app/src/main/cpp/caffe2/python/operator_test/duplicate_operands_test.py app/src/main/cpp/caffe2/python/operator_test/text_file_reader_test.py app/src/main/cpp/caffe2/python/helpers/elementwise_linear.py app/src/main/cpp/caffe2/python/layers_test.py app/src/main/cpp/caffe2/python/device_checker.py app/src/main/cpp/caffe2/python/operator_test/piecewise_linear_transform_test.py app/src/main/cpp/caffe2/python/control.py app/src/main/cpp/caffe2/python/helpers/dropout.py app/src/main/cpp/caffe2/python/mkl/mkl_LRN_speed_test.py app/src/main/cpp/caffe2/python/data_workers_test.py app/src/main/cpp/caffe2/python/mkl/mkl_copy_op_test.py app/src/main/cpp/caffe2/python/mkl/mkl_fill_op_test.py app/src/main/cpp/caffe2/python/models/seq2seq/train.py app/src/main/cpp/caffe2/python/parallel_workers_test.py app/src/main/cpp/caffe2/python/test/executor_test.py app/src/main/cpp/caffe2/python/core_gradients_test.py app/src/main/cpp/caffe2/python/layers/sampling_trainable_mixin.py app/src/main/cpp/caffe2/python/layers/concat.py app/src/main/cpp/caffe2/python/test/blob_deallocation_test.py app/src/main/cpp/caffe2/python/mint/app.py app/src/main/cpp/caffe2/python/layer_parameter_sharing_test.py app/src/main/cpp/caffe2/python/operator_test/listwise_l2r_operator_test.py app/src/main/cpp/caffe2/python/toy_regression_test.py app/src/main/cpp/caffe2/python/scope.py app/src/main/cpp/caffe2/python/operator_test/matmul_op_test.py app/src/main/cpp/caffe2/python/operator_test/leaky_relu_test.py app/src/main/cpp/caffe2/python/modifier_context.py app/src/main/cpp/caffe2/python/layers/build_index.py app/src/main/cpp/caffe2/perfkernels/hp_emblookup_codegen.py app/src/main/cpp/caffe2/python/operator_test/activation_ops_test.py app/src/main/cpp/caffe2/python/operator_test/map_ops_test.py app/src/main/cpp/caffe2/python/checkpoint_test.py app/src/main/cpp/caffe2/python/layers/last_n_window_collector.py app/src/main/cpp/caffe2/python/operator_test/instance_norm_test.py app/src/main/cpp/caffe2/python/tt_core_test.py app/src/main/cpp/caffe2/experiments/python/tt_contraction_op_test.py app/src/main/cpp/caffe2/python/operator_test/weighted_sample_test.py app/src/main/cpp/caffe2/python/operator_test/deform_conv_test.py app/src/main/cpp/caffe2/python/operator_test/group_conv_test.py app/src/main/cpp/caffe2/experiments/python/device_reduce_sum_bench.py app/src/main/cpp/caffe2/python/operator_test/top_k_test.py app/src/main/cpp/caffe2/python/benchmark_generator.py app/src/main/cpp/caffe2/python/binarysize.py app/src/main/cpp/caffe2/python/operator_test/elementwise_op_broadcast_test.py app/src/main/cpp/caffe2/contrib/torch/torch_ops_test.py app/src/main/cpp/caffe2/python/layers/reservoir_sampling.py app/src/main/cpp/caffe2/python/mkl/mkl_elementwise_sum_op_test.py app/src/main/cpp/caffe2/python/layers/functional.py app/src/main/cpp/caffe2/python/layers/random_fourier_features.py app/src/main/cpp/caffe2/python/mkl/mkl_fc_speed_test.py app/src/main/cpp/caffe2/python/cached_reader.py app/src/main/cpp/caffe2/contrib/warpctc/ctc_ops_test.py app/src/main/cpp/caffe2/python/mkl/convnet_benchmarks.py app/src/main/cpp/caffe2/python/queue_util.py app/src/main/cpp/caffe2/python/operator_test/pack_ops_test.py app/src/main/cpp/caffe2/python/models/download.py app/src/main/cpp/caffe2/experiments/python/sparse_funhash_op_test.py app/src/main/cpp/caffe2/python/operator_test/resize_op_test.py app/src/main/cpp/caffe2/python/operator_test/conv_test.py app/src/main/cpp/caffe2/python/operator_test/sinusoid_position_encoding_op_test.py app/src/main/cpp/caffe2/python/modeling/parameter_sharing_test.py app/src/main/cpp/caffe2/python/operator_test/dropout_op_test.py app/src/main/cpp/caffe2/python/modeling/parameter_info.py app/src/main/cpp/caffe2/python/operator_test/copy_ops_test.py app/src/main/cpp/caffe2/contrib/tensorboard/tensorboard_test.py app/src/main/cpp/caffe2/python/helpers/control_ops.py app/src/main/cpp/caffe2/python/text_file_reader.py app/src/main/cpp/caffe2/python/operator_test/boolean_mask_test.py app/src/main/cpp/caffe2/python/layers/select_record_by_context.py app/src/main/cpp/caffe2/python/helpers/conv.py app/src/main/cpp/caffe2/python/operator_test/specialized_segment_ops_test.py app/src/main/cpp/caffe2/python/data_workers.py app/src/main/cpp/caffe2/python/muji.py app/src/main/cpp/caffe2/contrib/tensorboard/tensorboard_exporter_test.py app/src/main/cpp/caffe2/python/model_device_test.py app/src/main/cpp/caffe2/python/operator_test/adagrad_test.py app/src/main/cpp/caffe2/python/operator_test/dataset_ops_test.py app/src/main/cpp/caffe2/python/regularizer.py app/src/main/cpp/caffe2/python/python_op_test.py app/src/main/cpp/caffe2/python/mkl/mkl_conv_op_test.py app/src/main/cpp/caffe2/contrib/script/examples/run_examples.py app/src/main/cpp/caffe2/python/mkl/mkl_sbn_speed_test.py app/src/main/cpp/caffe2/python/operator_test/unique_uniform_fill_op_test.py app/src/main/cpp/caffe2/python/helpers/array_helpers.py app/src/main/cpp/caffe2/python/operator_test/filler_ops_test.py app/src/main/cpp/caffe2/python/control_ops_util.py app/src/main/cpp/caffe2/python/layers/sampling_train.py app/src/main/cpp/caffe2/python/muji_test.py app/src/main/cpp/caffe2/python/layers/batch_mse_loss.py app/src/main/cpp/caffe2/python/operator_test/find_op_test.py app/src/main/cpp/caffe2/python/operator_test/margin_ranking_criterion_op_test.py app/src/main/cpp/caffe2/python/core_test.py app/src/main/cpp/caffe2/python/functional.py app/src/main/cpp/caffe2/python/operator_test/layer_norm_op_test.py app/src/main/cpp/caffe2/python/operator_test/utility_ops_test.py app/src/main/cpp/caffe2/python/modeling/initializers_test.py app/src/main/cpp/caffe2/python/rnn/rnn_cell_test_util.py app/src/main/cpp/caffe2/distributed/store_ops_test_util.py app/src/main/cpp/caffe2/python/modeling/initializers.py app/src/main/cpp/caffe2/python/mkl/rewrite_graph_test.py app/src/main/cpp/caffe2/python/mkl/mkl_pool_op_test.py app/src/main/cpp/caffe2/python/data_parallel_model_test.py app/src/main/cpp/caffe2/python/_import_c_extension.py app/src/main/cpp/caffe2/python/mkl/mkl_sbn_op_test.py app/src/main/cpp/caffe2/python/operator_test/image_input_op_test.py app/src/main/cpp/caffe2/python/helpers/fc.py app/src/main/cpp/caffe2/python/helpers/algebra.py app/src/main/cpp/caffe2/contrib/prof/htrace_to_chrome.py app/src/main/cpp/caffe2/contrib/torch/th_ops_test.py app/src/main/cpp/caffe2/python/operator_test/mkl_conv_op_test.py app/src/main/cpp/caffe2/python/checkpoint.py app/src/main/cpp/caffe2/python/test_util.py app/src/main/cpp/caffe2/python/layers/fc_without_bias.py app/src/main/cpp/caffe2/python/operator_test/relu_op_test.py app/src/main/cpp/caffe2/python/operator_test/glu_op_test.py app/src/main/cpp/caffe2/python/operator_test/lengths_top_k_ops_test.py app/src/main/cpp/caffe2/python/operator_test/softplus_op_test.py app/src/main/cpp/caffe2/python/examples/resnet50_trainer.py app/src/main/cpp/caffe2/python/sparse_to_dense_mask_test.py app/src/main/cpp/caffe2/python/layers/feature_sparse_to_dense.py app/src/main/cpp/caffe2/python/operator_test/flexible_top_k_test.py app/src/main/cpp/caffe2/python/schema.py app/src/main/cpp/caffe2/python/operator_test/lpnorm_op_test.py app/src/main/cpp/caffe2/python/dataset.py app/src/main/cpp/caffe2/python/net_builder_test.py app/src/main/cpp/caffe2/python/layers/dropout.py app/src/main/cpp/caffe2/python/operator_test/crf_test.py app/src/main/cpp/caffe2/python/scope_test.py app/src/main/cpp/caffe2/python/docs/github.py app/src/main/cpp/caffe2/python/hsm_util.py app/src/main/cpp/caffe2/python/allcompare_test.py app/src/main/cpp/caffe2/python/visualize.py app/src/main/cpp/caffe2/python/optimizer_context.py app/src/main/cpp/caffe2/python/operator_test/blobs_queue_db_test.py app/src/main/cpp/caffe2/python/hypothesis_test_util.py app/src/main/cpp/caffe2/python/layers/batch_lr_loss.py app/src/main/cpp/caffe2/python/operator_test/recurrent_net_executor_test.py app/src/main/cpp/caffe2/python/memonger.py app/src/main/cpp/caffe2/python/predictor/predictor_exporter_test.py app/src/main/cpp/caffe2/python/layers/add_bias.py app/src/main/cpp/caffe2/python/regularizer_context.py app/src/main/cpp/caffe2/python/operator_test/string_ops_test.py app/src/main/cpp/caffe2/python/parallelize_bmuf_distributed_test.py app/src/main/cpp/caffe2/python/control_test.py app/src/main/cpp/caffe2/python/operator_test/apmeter_test.py app/src/main/cpp/caffe2/contrib/aten/aten_test.py app/src/main/cpp/caffe2/python/test/executor_test_util.py app/src/main/cpp/caffe2/python/hypothesis_test.py app/src/main/cpp/caffe2/distributed/file_store_handler_op_test.py app/src/main/cpp/caffe2/python/optimizer.py app/src/main/cpp/caffe2/python/operator_test/extend_tensor_op_test.py app/src/main/cpp/caffe2/python/mkl/mkl_relu_op_test.py app/src/main/cpp/caffe2/python/operator_test/conditional_test.py app/src/main/cpp/caffe2/python/caffe_translator.py app/src/main/cpp/caffe2/python/control_ops_grad.py app/src/main/cpp/caffe2/python/data_parallel_model.py app/src/main/cpp/caffe2/python/operator_test/softmax_ops_test.py app/src/main/cpp/caffe2/python/layers/layers.py app/src/main/cpp/caffe2/python/operator_test/sequence_ops_test.py app/src/main/cpp/caffe2/python/operator_test/rnn_cell_test.py app/src/main/cpp/caffe2/python/operator_test/merge_id_lists_op_test.py app/src/main/cpp/caffe2/contrib/tensorboard/tensorboard_exporter.py app/src/main/cpp/caffe2/python/operator_test/weighted_sum_test.py app/src/main/cpp/caffe2/python/operator_test/batch_sparse_to_dense_op_test.py app/src/main/cpp/caffe2/python/model_helper.py app/src/main/cpp/caffe2/python/layers/uniform_sampling.py app/src/main/cpp/caffe2/python/operator_test/im2col_col2im_test.py app/src/main/cpp/caffe2/python/operator_test/gru_test.py app/src/main/cpp/caffe2/contrib/nccl/nccl_ops_test.py app/src/main/cpp/caffe2/python/build.py app/src/main/cpp/caffe2/python/rnn_cell.py app/src/main/cpp/caffe2/python/operator_test/elementwise_ops_test.py app/src/main/cpp/caffe2/python/operator_test/distance_op_test.py app/src/main/cpp/caffe2/python/layer_test_util.py app/src/main/cpp/caffe2/distributed/redis_store_handler_op_test.py app/src/main/cpp/caffe2/contrib/aten/docs/sample.py app/src/main/cpp/caffe2/python/operator_test/math_ops_test.py app/src/main/cpp/caffe2/python/timeout_guard.py app/src/main/cpp/caffe2/python/db_test.py app/src/main/cpp/caffe2/python/workspace.py app/src/main/cpp/caffe2/python/operator_test/partition_ops_test.py app/src/main/cpp/caffe2/python/session.py app/src/main/cpp/caffe2/python/operator_test/learning_rate_op_test.py app/src/main/cpp/caffe2/python/operator_test/channel_shuffle_test.py app/src/main/cpp/caffe2/python/helpers/train.py app/src/main/cpp/caffe2/python/operator_test/momentum_sgd_test.py app/src/main/cpp/caffe2/python/operator_test/mkl_speed_test.py app/src/main/cpp/caffe2/python/data_parallel_model_utils.py app/src/main/cpp/caffe2/python/embedding_generation_benchmark.py app/src/main/cpp/caffe2/python/operator_test/negate_gradient_op_test.py app/src/main/cpp/caffe2/python/layers/position_weighted.py app/src/main/cpp/caffe2/python/net_drawer.py app/src/main/cpp/caffe2/python/convnet_benchmarks.py app/src/main/cpp/caffe2/python/gru_cell.py app/src/main/cpp/caffe2/python/examples/lmdb_create_example.py app/src/main/cpp/caffe2/python/operator_test/one_hot_ops_test.py app/src/main/cpp/caffe2/experiments/python/net_construct_bench.py app/src/main/cpp/caffe2/python/operator_test/hsm_test.py app/src/main/cpp/caffe2/python/operator_test/reduction_ops_test.py app/src/main/cpp/caffe2/python/helpers/tools.py app/src/main/cpp/caffe2/python/dyndep.py app/src/main/cpp/caffe2/python/models/resnet.py app/src/main/cpp/caffe2/python/operator_test/elementwise_logical_ops_test.py app/src/main/cpp/caffe2/python/operator_test/pack_rnn_sequence_op_test.py app/src/main/cpp/caffe2/python/operator_test/reshape_ops_test.py app/src/main/cpp/caffe2/python/operator_test/given_tensor_fill_op_test.py app/src/main/cpp/caffe2/python/operator_test/fc_operator_test.py app/src/main/cpp/caffe2/python/predictor/predictor_py_utils.py app/src/main/cpp/caffe2/experiments/python/SparseTransformer.py app/src/main/cpp/caffe2/python/operator_test/assert_test.py app/src/main/cpp/caffe2/python/load_save_test.py app/src/main/cpp/caffe2/python/layers/__init__.py app/src/main/cpp/caffe2/python/operator_test/sparse_gradient_checker_test.py app/src/main/cpp/caffe2/python/mkl_test_util.py app/src/main/cpp/caffe2/python/layers/split.py app/src/main/cpp/caffe2/python/net_builder.py app/src/main/cpp/caffe2/python/operator_test/batch_box_cox_test.py app/src/main/cpp/caffe2/python/operator_test/index_hash_ops_test.py app/src/main/cpp/caffe2/python/functional_test.py app/src/main/cpp/caffe2/python/operator_test/emptysample_ops_test.py app/src/main/cpp/caffe2/python/cnn.py app/src/main/cpp/caffe2/python/operator_test/cudnn_recurrent_test.py app/src/main/cpp/caffe2/python/models/seq2seq/beam_search.py app/src/main/cpp/caffe2/python/recurrent.py app/src/main/cpp/caffe2/python/operator_test/elementwise_linear_op_test.py app/src/main/cpp/caffe2/contrib/gloo/gloo_test.py app/src/main/cpp/caffe2/python/mkl/mkl_fc_op_test.py app/src/main/cpp/caffe2/python/operator_test/checkpoint_test.py app/src/main/cpp/caffe2/python/experiment_util.py app/src/main/cpp/caffe2/python/operator_test/loss_ops_test.py app/src/main/cpp/caffe2/python/models/seq2seq/seq2seq_util.py app/src/main/cpp/caffe2/python/operator_test/mpi_test.py app/src/main/cpp/caffe2/python/layers/batch_sigmoid_cross_entropy_loss.py app/src/main/cpp/caffe2/python/models/seq2seq/seq2seq_model_helper.py app/src/main/cpp/caffe2/python/mkl/mkl_pool_speed_test.py app/src/main/cpp/caffe2/python/net_printer.py app/src/main/cpp/caffe2/python/operator_test/cast_op_test.py app/src/main/cpp/caffe2/python/operator_test/shape_inference_test.py app/src/main/cpp/caffe2/contrib/tensorboard/tensorboard.py app/src/main/cpp/caffe2/python/operator_test/cosine_embedding_criterion_op_test.py app/src/main/cpp/caffe2/python/operator_test/tile_op_test.py app/src/main/cpp/caffe2/python/lstm_benchmark.py app/src/main/cpp/caffe2/python/extension_loader.py app/src/main/cpp/caffe2/python/caffe_translator_test.py app/src/main/cpp/caffe2/python/optimizer_test_util.py app/src/main/cpp/caffe2/python/pipeline_test.py app/src/main/cpp/caffe2/python/predictor/serde.py app/src/main/cpp/caffe2/python/context_test.py app/src/main/cpp/caffe2/python/attention.py app/src/main/cpp/caffe2/python/predictor_constants.py app/src/main/cpp/caffe2/python/core.py app/src/main/cpp/caffe2/python/examples/char_rnn.py app/src/main/cpp/caffe2/python/layers/batch_distill_lr_loss.py app/src/main/cpp/caffe2/python/layers/sparse_feature_hash.py app/src/main/cpp/caffe2/python/docs/parser.py app/src/main/cpp/caffe2/python/operator_test/rank_loss_operator_test.py app/src/main/cpp/caffe2/python/operator_test/sparse_lengths_sum_benchmark.py app/src/main/cpp/caffe2/python/convnet_benchmarks_test.py app/src/main/cpp/caffe2/python/predictor/mobile_exporter.py app/src/main/cpp/caffe2/python/operator_test/rebatching_queue_test.py app/src/main/cpp/caffe2/python/operator_test/flatten_op_test.py app/src/main/cpp/caffe2/python/operator_test/index_ops_test.py app/src/main/cpp/caffe2/python/models/seq2seq/translate.py app/src/main/cpp/caffe2/python/operator_test/reduce_ops_test.py app/src/main/cpp/caffe2/python/operator_test/pooling_test.py app/src/main/cpp/caffe2/python/operator_test/adam_test.py app/src/main/cpp/caffe2/python/layers/sparse_lookup.py app/src/main/cpp/caffe2/python/session_test.py app/src/main/cpp/caffe2/python/layers/tags.py app/src/main/cpp/caffe2/python/docs/generator.py app/src/main/cpp/caffe2/python/dataio.py app/src/main/cpp/caffe2/python/layers/merge_id_lists.py app/src/main/cpp/caffe2/python/operator_test/gather_ops_test.py app/src/main/cpp/caffe2/python/models/seq2seq/seq2seq_model_helper_test.py app/src/main/cpp/caffe2/python/docs/formatter.py app/src/main/cpp/caffe2/python/dataio_test.py app/src/main/cpp/caffe2/python/test/do_op_test.py app/src/main/cpp/caffe2/python/operator_test/record_queue_test.py app/src/main/cpp/caffe2/python/layers/margin_rank_loss.py app/src/main/cpp/caffe2/python/operator_test/clip_op_test.py app/src/main/cpp/caffe2/experiments/python/sparse_reshape_op_test.py app/src/main/cpp/caffe2/python/layers/fc.py app/src/main/cpp/caffe2/python/layer_model_helper.py app/src/main/cpp/caffe2/experiments/python/convnet_benchmarks.py app/src/main/cpp/caffe2/python/operator_test/prepend_dim_test.py app/src/main/cpp/caffe2/python/operator_test/boolean_unmask_test.py app/src/main/cpp/caffe2/contrib/prof/cuda_profile_ops_test.py app/src/main/cpp/caffe2/python/operator_test/pad_test.py app/src/main/cpp/caffe2/python/operator_test/normalize_op_test.py app/src/main/cpp/caffe2/python/layer_model_instantiator.py app/src/main/cpp/caffe2/python/layers/pairwise_dot_product.py app/src/main/cpp/caffe2/python/helpers/pooling.py app/src/main/cpp/caffe2/python/net_printer_test.py app/src/main/cpp/caffe2/python/gradient_check_test.py app/src/main/cpp/caffe2/python/layers/gather_record.py app/src/main/cpp/caffe2/python/operator_test/rmac_regions_op_test.py app/src/main/cpp/caffe2/python/operator_test/sparse_ops_test.py app/src/main/cpp/caffe2/python/operator_test/cross_entropy_ops_test.py app/src/main/cpp/caffe2/python/operator_test/spatial_bn_op_test.py app/src/main/cpp/caffe2/experiments/python/tt_pad_op_test.py app/src/main/cpp/caffe2/python/helpers/normalization.py app/src/main/cpp/caffe2/python/operator_test/concat_split_op_test.py app/src/main/cpp/caffe2/python/operator_test/stats_ops_test.py app/src/main/cpp/caffe2/python/predictor/mobile_exporter_test.py app/src/main/cpp/caffe2/experiments/python/funhash_op_test.py app/src/main/cpp/caffe2/python/layers/batch_normalization.py app/src/main/cpp/caffe2/python/models/resnet_test.py app/src/main/cpp/caffe2/python/operator_test/sparse_to_dense_mask_op_test.py app/src/main/cpp/caffe2/python/operator_test/video_input_op_test.py app/src/main/cpp/caffe2/python/memonger_test.py app/src/main/cpp/caffe2/python/brew.py app/src/main/cpp/caffe2/python/helpers/arg_scope.py app/src/main/cpp/caffe2/python/pipeline.py app/src/main/cpp/caffe2/contrib/aten/gen_op.py app/src/main/cpp/caffe2/python/operator_test/recurrent_network_test.py app/src/main/cpp/caffe2/python/schema_test.py app/src/main/cpp/caffe2/python/mkl/mkl_sigmoid_op_test.py app/src/main/cpp/caffe2/python/brew_test.py TestATen read get_output value_is_tensor_type self_as_first_argument write attribute_names supports expand value_has_tensors required_attribute_names get_num_inputs MyFunction MyModule TestCase TemporaryDirectory benchmark NCCLOpsTest gpu_device has_avx2 NNPackOpsTest benchmark CudaProfileOpsTest build_trace_dict stop_display get_argument_parser generate_chrome_trace main TestCaffe2Script Config graph_def_to_event write_events tensorboard_graphs cli visualize_cnn visualize_ops tensorboard_events _show_graph visualize_net nets_to_graph_def _add_gradient_scope _remap_keys _operators_to_graph_def _try_get_shapes _operator_to_node _get_blob_names _rename_all _add_tf_shape _convert_to_ssa _fill_missing_operator_names _propagate_device_option cnn_to_graph_def _set_tf_attr _blob_to_node _tf_device _replace_colons _make_unique_name ops_to_graph_def TensorboardExporterTest TensorboardTest THOpsTest TorchOpTest softmax CTCOpsTest TestFileStoreHandlerOp TestRedisStoreHandlerOp StoreOpsTests Benchmark _InceptionModule MLP AddParameterUpdate Inception VGGA GetArgumentParser OverFeat AlexNet net_DAG_Builder AddInput Benchmark SumSqrElements SoftMaxWithLoss SumElements BenchmarkMeta main parse_args TestFunHash main Create AddMomentumParameterUpdate net2list netbuilder maskNallocate NetDefNode transFCRelu Prune2Sparse TestFunHash TestSparseMatrixReshapeOp test_reshape TestTTContraction TestTTPad generic unroll TestAllCompare allcompare_process TemporaryDirectory _apply_fc_weight_for_sum_match apply_regular_attention _calc_attention_logits_from_sum_match apply_soft_coverage_attention apply_recurrent_attention _calc_attention_weights apply_dot_attention _calc_weighted_context AttentionType s main parse_kwarg GetSymbolTrie Trie PrintTrie MaybeAddColor main ReadableSize HelperWrapper BrewTest BrewGPUTest CachedReader _GetLegacyDims TranslateBatchNorm TranslateReduction TranslateDeconv TranslatorRegistry TranslateReshape TranslatePool3D TranslateROIPooling TranslateConcat TranslateRelu TranslateScale TranslateTanH TranslateCrop TranslateElementWise AddArgument TranslateModel TranslateSoftmax _GetInputDims _RemoveLegacyPad _AdjustDims TranslateData TranslateInnerProduct TranslateConv TranslateInstanceNorm TranslateAccuracy TranslateConvNd TranslateLRN _ShouldInclude TranslateInput _TranslateStridePadKernelHelper TranslatePRelu TranslateFlatten BaseTranslate _GetLegacyPadArgs TranslateVideoData TranslateDropout TranslatePool _StateMeetsRule ConvertTensorProtosToInitNet TranslateSigmoid TranslateSoftmaxWithLoss _GetBlobDimMap TestNumericalEquivalence setUpModule JobRunner Job UploadTaskGroupBuilder MultiNodeCheckpointManager get_ckpt_filename CheckpointManager epoch_limiter TestCheckpoint build_pipeline local_copy_op UploadToLocalFile CNNModelHelper context_manager get_active_context ContextManager ContextInfo current __call__ __enter__ __exit__ define_context TestContext MyContext Switch Until For _AppendNets NotNet DoParallel IfNot While _RunOnceIfNot If MergeConditionNets _MakeList _get_next_step_name GetConditionBlobFromNet CombineConditions Do DoWhile _PrependNets _CopyConditionBlobNet SwitchNot BoolNet _RunOnceIf DoUntil _IsNets add_while_op add_if_op get_external_blob_names TestControl Benchmark MLP AddParameterUpdate Inception VGGA GetArgumentParser OverFeat AlexNet _InceptionModule TestConvnetBenchmarks CreateOperator DeviceOption get_ssa scoped_execution_step remap_proto IsOperator GetGlobalInitArgs IsOperatorWithEngine _GetRegisteredOperators _recover_record_by_prefix BlobReference _RegisterPythonImpl control_op_remap InjectDeviceCopiesAmongNets copy_func_between_devices clone_and_bind_net GlobalInit RemapEntry ScopedBlobReference Plan IR to_execution_step output_to_list InferOpBlobDevices GradientRegistry InferBlobDevices _InitDataType _extract_stacktrace get_net_name device_option_equal GetIndexFromGradientList device_equal get_undefined_blobs InjectCrossDeviceCopies _get_blob_ref InjectDeviceCopiesAmongNetsWithoutB2D _add_net_to_dict recurrent_network_op_remap Net execution_step ScopedName CreatePythonOperator _RectifyInputOutput add_nets_in_order DataType RefreshRegisteredOperators get_op_ids_in_path get_output_producers ExecutionStep TestGradientCalculation AddDirectGradient AddNogradient TestGradientsAccumulationWithNoGradientOps TestSparseGradientsAccumulation TestGradientsAccumulationWithPassThroughGradients AddUseInputGradient CopyDeviceOption AddUseOutputGradient NeedAll GIS TestOpRegistryKey TestScopes TestCreateOperator TestAutoNaming TestAppendNet TestExtractPredictorNet TestCloneNet TestOperatorTraceback TestDeviceOption TestCreatePlan TestInferDevice CRFWithLoss CounterReader ReaderWithLimit Writer Reader ReaderBuilder CountUntil PipedReaderBuilder Pipe TestReaderWithLimit init_dataset read_all_data _DatasetRandomReader Dataset execution_step_with_progress _DatasetReader Const _DatasetWriter _AllReduceBlobs _BroadcastComputedParams _CreateOrCloneCommonWorld Parallelize Parallelize_GPU Parallelize_CPU_BMUF OptimizeGradientMemory _SyncAllParamsDistributed _InferBlobDevice CollectivesConcurrencyControl GetCheckpointParams _ValidateParams _SyncAllParamsSingleHost _ForEachDevice _Broadcast _SyncAllParams _GroupByDevice Parallelize_BMUF _BroadcastComputedParamsSingleHost _GetReverseOrderedGrads _AllReduceBlobsSingleHost RunInitNet _OptimizeGradientMemorySimple _PruneParametersForSharing RunWarmup _IsGPUBlob _BroadcastComputedParamsDistributed Parallelize_GPU_BMUF _RemapParameterBlobsForSharedModel ExtractPredictorNet _AllReduceBlobsDistributed _ComputeBlobsToSync _AddGradientOperators GetLearningRateBlobNames _AnalyzeOperators stripBlobName _AllReduce FinalizeAfterCheckpoint ConvertNetForDevice _RunComparison Parallelize_CPU Synchronize AddDistributedBlobSync AddBlobSync _AddDynamicMemoryOptimization RunNet ParallelizeBMUFTest RecurrentNetworkParallelTest SparseDataParallelModelTestWithSharedIndices DataParallelModelTest DeviceShiftTest SparseDataParallelModelTest TemporaryDirectory GetActivationBlobs ShiftActivationDevices _ShiftActivationDevices BatchFeeder enqueuer GlobalCoordinator DataWorker get_worker_ids init_data_input_workers dummy_fetcher dummy_fetcher_rnn DataWorkersTest DeviceChecker InitOpsLibrary _init_impl GetImportedOpsLibraries Benchmark create_model generate_data GetArgumentParser generate_embedding_table Caffe2EmbeddingGeneration ModelTrainerLog ExternalLogger DlopenGuard namedtupledict _Functional TestFunctional _tensor_splits _get_grad_blob NetGradientChecker GradientChecker _assert_close _get_grad TestConcat TestSigmoid TestSin TestMakeTwoClass TestNetGradientChecker TestTanh TestExp TestIf TestCos TestLRN TestSum TestFlatten TestRelu TestAbs GRUCell create_hierarchy create_node_with_words create_node_with_nodes _tensor_and_indices _test_binary _test_binary_broadcast sigmoid TestOperators _tensor_and_prefix _dtypes segment_ids sparse_segmented_tensor dims tensor tensor1d is_sandcastle temp_workspace is_travis segmented_tensor tensors1d tensors device_checker_device_options HypothesisTestCase lengths arrays sparse_lengths_tensor gradient_checker_device_option lengths_tensor runOpBenchmark elements_of_type TestLayers LayerModelHelper generate_predict_net generate_training_nets _generate_training_net_only generate_training_nets_forward_only shrink_output_schema generate_eval_net _filter_layers OpSpec LayersTestCase FakeQuantization8BitsRowwise TestQuantize8bits TestLoadSave TestLoadSaveBase Benchmark create_model generate_data GetArgumentParser Caffe2LSTM _add_single_target_ifneeded is_compatible compute_ranges get_updated_ranges compute_blob_assignments verify_graph_equality estimate_memory_usage optimize_inference_for_dag compute_assignments_dp optimize_inference_fast collect_blob_sizes share_grad_blobs _find_source_nodes _get_longest_paths AssignmentAlgorithm compute_statistics _compute_tree_height _get_path verify_inplace_blobs _get_count get_memory_usage topological_sort_traversal_longest_path compute_interference_graph release_blobs_when_used topological_sort_traversal _find_target_nodes _sort_tree_leaves optimize_interference apply_recurrent_blob_assignments _build_tree _get_max_size verify_assignments apply_assignments compute_assignments_greedy blob_nbytes compute_assignments count_blobs has_blob MemongerTest device_checker_device_options gradient_checker_device_option TestMiniAlexNet ModelHelper ExtractPredictorNet ModifierContext UseModifierBase OnGPU OnCPU Allreduce Allreduce2 Allreduce8 AllreduceFallback Allreduce4 TestMuji _RunWhileCondition NetBuilder _RunElseNet _RunIf _RunWhileNet _RunOnce _SetupBuilder _StopGuard _ReporterBuilder Operations _Loop _RunIfNet _test_outer python_op_builder PythonOpStats _test_if _test_inner_stop TestNetBuilder _test_loop GetPydotGraph _rectify_operator_and_name GetPlanGraph _draw_nets GetGraphPngSafe _escape_label _draw_steps GetOpNodeProducer GetPydotGraphMinimal main GetGraphInJson GetOperatorMapForPlan to_string analyze_step print_job factor_prefix Visitor print_net_def print_step format_device_option _get_step_context commonprefix print_op analyze_net call analyze_job _arg_val analyze_task analyze_op print_task_group _print_task_output _sanitize_str debug_net format_value print_net Analyzer analyze print_task analyze_task_group Printer Text _prepare_gradient_if_op gen_do_gradient _prepare_blob_copy_op gen_if_gradient _gen_if_branch_gradient _do_op_sanity_check_and_process _gen_grad_zero_init_ops _gen_subgradient_pass _prepare_gradient_do_op _get_net_argument TestDB ParameterSharingTest TestNetPrinter example_loop example_job example_task L2Norm L1Norm Regularizer TestObservers MultiPrecisionSgdOptimizer AdagradOptimizer _get_param_to_device get_lr_injection WeightDecayBuilder FtrlOptimizer build_yellowfin set_lr_injection _calc_norm_ratio _build RmsPropOptimizer add_weight_decay build_multi_precision_sgd SgdOptimizer build_adam get_param_device Optimizer YellowFinOptimizer build_rms_prop build_sgd build_fp16_sgd AdamOptimizer build_adagrad FP16SgdOptimizer build_ftrl UseOptimizer OptimizerContext TestAdam TestMultiOptimizers TestRmsProp TestOptimizerContext TestFtrl TestMomentumSgd TestWeightDecay TestSgd TestAdagrad TestYellowFin TestMultiPrecisionSgd LRModificationTestBase OptimizerTestBase DistributedTest bmuf_process GlobalWorkerCoordinator run_worker Metrics State init_workers Worker WorkerCoordinator create_worker ParallelWorkersTest dequeue_value create_queue ProcessingReader Output NetProcessor _init_output make_processor normalize_processor_output _runtime_threads_task processor_name pipe_and_output _static_threads_task _pipe_step pipe TestPipeline SubFunctionThatThrowsRuntimeError MainOpFunctionThatThrowsRuntimeError op_builder PythonOpTest QueueWrapper dequeue _QueueReader enqueue _QueueWriter Queue close_queue _QueueWriter _QueueReader RecordQueue retrieve_step_blobs set_rnn_executor_config recurrent_net UseRegularizer RegularizerContext MILSTMWithAttentionCell DropoutCell LayerNormMILSTMCell AttentionCell UnrolledCell MILSTMCell _layered_LSTM cudnn_LSTM GetLSTMParamNames MultiRNNCell LSTMWithAttention LSTMCell LSTMInitializer InitFromLSTMParams LSTMWithAttentionCell LayerNormLSTMCell _LSTM MultiRNNCellInitializer RNNCell attach_metadata_to_scalars RawTuple Field Struct _normalize_field Map schema_check from_blob_list from_dtype from_column_list _join_field_name Metadata Tuple List equal_schemas _SchemaNode NewRecord NamedTuple Scalar FeedRecord is_schema_subset ConstRecord as_record FetchRecord data_type_for_dtype InitEmptyRecord TestDB CurrentNameScope DeviceScope NameScope EmptyDeviceScope CurrentDeviceScope thread_runner TestScope LocalSession Session CompiledRunnable TestLocalSession TestSparseToDenseMask _merge_node_kwargs final_output TaskOutputList get_setup_nets Cluster SetupNets TaskGroup Task Node TaskOutput add_setup_steps WorkspaceType rand_array TestCase TextFileReader WatcherThread EuthanizeIfNecessary CompleteInTimeOrDie TestToyRegression init_tt_cores matrix_to_tt fc_net_to_tt_net tt_svd TestTTSVD NumpyArrayToCaffe2Tensor GetContentFromProtoString DebugMode debug TryReadProtoWithClass MakeArgument ConvertProtoToBinary ResetBlobs GetGPUMemoryUsageStats CaffeBlobToNumpyArray GetContentFromProto Caffe2TensorToNumpyArray PatchVisualizer ChannelLast NHWC ChannelFirst NCHW StartImmediate GetOperatorCost RunPlan _GetFreeFlaskPort CreateNet ApplyTransformIfFaster ImmediateBlobs CallWithExceptionIntercept _Workspace_create_net_with_exception_intercept GetNetName _BlobDict WorkspaceGuard ResetWorkspace IsImmediate StringifyNetName RunNetOnce InferShapesAndTypes _Blob_feed StringifyBlobName _Workspace_run GetNameScope FetchBlob Predictor RunOperatorOnce StopImmediate FetchBlobs FeedBlob _StringifyName RunOperatorImmediate StringifyProto StartMint ApplyTransform GetCudaPeerAccessPattern FetchImmediate RunOperatorsOnce RunNet FeedImmediate TestWorkspace TestWorkspaceMKLDNN TestCppEnforceAsException TestImmedibate TestTransform TestWorkspaceGPU TestMultiWorkspaces TestPredictor TestCWorkspace _TensorCPU_reshape _TensorCPU_shape Formatter Markdown DocUploader OperatorDoc OpDocGenerator OperatorEngine DocGenerator getCodeLink GHMarkdown GHOperatorDoc GHOperatorEngine GHOpDocGenerator GHOpDocUploader Parser main CreateNetOnce CharRNN main create_db read_db_with_caffe2 LoadModel RunEpoch AddNullInput AddImageInput Train main SaveModel transpose sum batch_mat_mul arg_scope get_current_scope depth_concat concat cond loop _ConvBase group_conv_deprecated conv_transpose group_conv conv_nd conv dropout elementwise_linear _elementwise_linear fc_sparse fc fc_prune fc_decomp _FC_or_packed_FC packed_fc tanh prelu relu lrn spatial_bn softmax instance_norm layer_norm max_pool_with_index average_pool max_pool video_input image_input _get_weights add_weight_decay accuracy iter Functional AddBias ArcCosineFeatureMap BatchDistillLRLoss BatchLRLoss BatchMSELoss BatchNormalization BatchSigmoidCrossEntropyLoss BatchSoftmaxLoss MapToRange Concat Conv Dropout FC FCWithoutBias FeatureSparseToDense GatherRecord LastNWindowCollector get_avg_length is_request_only_scalar InstantiationContext register_layer layer_exists LayerParameter get_key get_categorical_limit get_layer_class ModelLayer create_layer set_request_only MarginRankLoss MergeIdLists PairwiseDotProduct PositionWeighted RandomFourierFeatures ReservoirSampling SamplingTrain SamplingTrainableMixin SelectRecordByContext SemiRandomFeatures SparseFeatureHash SparseLookup get_sparse_lookup_predictor_version Split TagContext Tags UniformSampling import_recursive find_subclasses_recursively visualize_print_log index jsonify_nvd3 visualize_summary visualize_file main visualization Benchmark MLP AddParameterUpdate Inception VGGA GetArgumentParser OverFeat AlexNet ResNet50 _InceptionModule MKLConvTest MKCopyTest MKLElementwiseSumTest MKLFcTest TestMKLBasic MKLFillTest MKLLRNTest TestMKLBasic MKLPoolTest TestMKLBasic MKLReluTest MKLSpatialBNTest TestMKLBasic MKLSigmoidTest TestMKLBasic rewrite_run_net_simple rewrite_model_helper_simple rewrite_init_net_simple last_producer deterministic_io double_matmul simple_cnn simple_mlp MKLRewriteTest simple_relu complex_resnet simple_resnet alexnet simple_fc ExternalInitializer Initializer update_initializer pFP16Initializer ReversepFP16Initializer InitializerTest ParameterInfo ParameterTags ParameterType _normalize_namescope ParameterSharingContext ParameterSharing ParameterSharingTest signalHandler validModelName getURLFromName downloadFromURLToFile downloadModel progressBar deleteDirectory create_resnet_32x32 create_resnet50 ResNetBuilder count_blobs ResnetMemongerTest has_blob count_shared_blobs _parseFile BeamSearchForwardOnly Seq2SeqBeamSearchTest Seq2SeqModelHelper Seq2SeqModelHelperTest output_projection get_numberized_sentence build_embedding_encoder build_initial_rnn_decoder_states rnn_unidirectional_layer get_layer_scope rnn_bidirectional_layer LSTMWithAttentionDecoder build_embeddings build_embedding_decoder gen_vocab Seq2SeqModelCaffe2 prepare_batch run_seq2seq_model main gen_batches main _weighted_sum run_seq2seq_beam_decoder Seq2SeqModelCaffe2EnsembleDecoder TestActivations TestAdagrad TestAdam calculate_ap TestAPMeterOps TestAssert TestAtomicOps TestBatchBoxCox _inputs TestBatchSparseToDense BlobsQueueDBTest TestBooleanMaskOp TestUnmaskOp TestCastOp ChannelShuffleOpsTest CheckpointTest TestClip TestConditionalOp TestConvolution _cudnn_supports TestConvolutionTranspose CopyOpsTest TestCosineEmbeddingCriterion TestCounterOps TestCRFOp sigmoid TestCrossEntropyOps sigmoid_cross_entropy_with_logits_grad sigmoid_cross_entropy_with_logits TestLSTMs TestDatasetOps _sparse_features_map _assert_arrays_equal _dense_features_map _assert_records_equal _dataset _conv_2d_output_size _conv_2d_random_offsets _cudnn_supports _conv_2d_shuffle_offsets _conv_1d_output_size TestConvolution _conv_2d_offsets_dims DistanceTest TestDropout TestDuplicateOperands TestElementwiseLinearOp TestRowWhere rowmux TestIsMemberOf TestWhere mux TestElementwiseBroadcast TestEmptySampleOps TestExtendTensorOp TestFcOperator TestFillerOperator _fill_diagonal TestFindOperator TestFlatten TestFlexibleTopK _inputs TestBatchGatherOps TestGatherOps gather_ranges_to_dense gather_ranges _tensor_splits TestGatherRanges batched_boarders_and_data TestGivenTensorFillOps TestGlu TestGroupConvolution GRUCellTest _prepare_gru_unit_op gru_reference gru_unit_op_input gru_unit gru_input TestHsm verify_color_normalize create_test verify_rescale caffe2_img verify_apply_bounding_box TestImport run_test verify_crop TestIndexHashOps TestIndexOps TestInstanceNorm TestLayerNormOp TestLeakyRelu TestLearningRate TestLengthsTileOp TestLengthsTopKOps TestListwiseL2rOps TestLossOps LpnormTest TestMap TestMarginRankingCriterion TestMathOps TestConcatSplitOps _tensor_splits TestElementwiseOps TestReduceFrontSum TestMatMul TestBatchMatMul TestPrependDim TestShapeInference merge_id_lists_ref id_list_batch TestMergeIdListsOp MKLConvTest PackedFCTest TestMKLBasic _data TestMod TestMomentumSGD TestMPI SetupMPI TestNegateGradient TestNormalizeOp TestOneHotOps _one_hots TestTensorPackOps TestPackRNNSequenceOperator TestPad TestPartitionOps TestPiecewiseLinearTransform TestPooling PythonOpTest TestPairWiseLossOps primefac TestReBatchingQueue TestRecordQueue RecurrentNetworkTest TestRNNExecutor TestReduceFrontReductions TestReductionOps TestRelu TestLengthsToShapeOps _test_reshape TestResize RMACRegionsOpTest lstm_input lstm_with_dot_attention_reference_different_dim multi_lstm_reference RNNCellTest prepare_mul_rnn lstm_reference compute_recurrent_attention_logits lstm_with_dot_attention_reference_same_dim compute_dot_attention_logits layer_norm_milstm_reference _prepare_attention lstm_with_regular_attention_reference lstm_with_recurrent_attention_reference milstm_reference lstm_with_dot_attention_reference MulCell compute_regular_attention_logits compute_coverage_attention_logits layer_norm_with_scale_and_bias_ref lstm_unit lstm_with_coverage_attention_reference lstm_with_attention_reference layer_norm_lstm_reference mean_grad logmeanexp max_fwd LengthsTester sum_grad sparse_lengths_weighted_sum_ref logsumexp mean max_grad TesterBase logsumexp_grad SegmentsTester TestSegmentOps sparse_lengths_weighted_sum_grad_ref TestSequenceOps _add_padding_ref _gen_test_add_padding _remove_padding_ref _gather_padding_ref TestSinusoidPositionEncodingOp TestSoftmaxOps TestSoftplus TestSparseGradient benchmark_sparse_lengths_sum TestScatterOps TestFcOperator TestSpatialBN TestSpecializedSegmentOps divide_by_square_root TestSquareRootDivide _data_and_scale grad TestCounterOps _string_lists TestStringOps TestTextFileReader TestTile TestTopK TestUniqueUniformFillOp TestUtilityOps VideoInputOpTest TestWeightedSample TestWeightedSumOp Export TestMobileExporter get_meta_net_def PredictorExportMeta _global_init_net set_model_info get_predictor_exporter_helper save_to_db prepare_prediction_net load_from_db PredictorExporterTest AddPlan get_comp_name _ProtoMapGet create_predict_net GetPlanOriginal GetNetOriginal GetBlobs GetApplicationSpecificInfo GetPlan AddBlobs create_predict_init_net GetNet AddNet TestPredictor deserialize_protobuf_struct serialize_protobuf_struct Compare sigmoid tanh _prepare_rnn BlobDeallocationTest DoOpTest ExecutorGPUResNetTest ExecutorCPUConvNetTest build_conv_model build_resnet50_dataparallel_model executor_test_model_names run_resnet50_epoch ExecutorTestBase executor_test_settings gen_test_resnet50 conv_model_generators load chw loadToNCHW removeMean crop_center rescale bgr parseResults batch append deepcopy sum range print format value_has_tensors CUDA DeviceOption time format print Plan AddStep float ExecutionStep range run check_output append items list loads items sorted list search group stop_display append enumerate add_argument ArgumentParser display print htrace_log generate_chrome_trace parse_args format HTML display cnn_to_graph_def _show_graph nets_to_graph_def _show_graph _show_graph ops_to_graph_def SummaryWriter hasattr close FileWriter add_event summary flush write_events getLogger info setLevel INFO len seed get_named_summaries namedtuple getLogger named_summaries_to_events write_events info setLevel INFO len add clear update list IR output extend set ssa zip input update output input set clear update clear list g name extend output set _remap_keys input _rename_all _rename_all update join name commonprefix output set _make_unique_name input type extend Dim TensorShapeProto name HasField ints f extend _add_tf_shape i strings floats arg _set_tf_attr name device_option extend output _tf_device _add_tf_shape input attr type get all extend _tf_device _add_tf_shape device_option attr clear update input _add_gradient_scope extend set add output _convert_to_ssa _replace_colons _fill_missing_operator_names enumerate append _get_blob_names device_option CopyFrom op InferShapesAndTypes _propagate_device_option _try_get_shapes deepcopy deepcopy sum exp amax LabelCrossEntropy AveragedLoss format Sum range FC CNNModelHelper LabelCrossEntropy AveragedLoss Softmax MaxPool Relu Conv FC CNNModelHelper LabelCrossEntropy AveragedLoss Softmax MaxPool Relu Conv FC CNNModelHelper LabelCrossEntropy AveragedLoss Softmax MaxPool Relu Conv FC CNNModelHelper print netbuilder Conv MaxPool Relu Concat LabelCrossEntropy AveragedLoss Softmax MaxPool Relu Conv _InceptionModule AveragePool FC CNNModelHelper StopGradient Scale NHWC2NCHW TensorProtosDBInput Cast ConstantFill WeightedSum params Iter LearningRate warmup_iterations layer_wise_benchmark model GaussianFill net_type iterations RunPlan BenchmarkNet CreateNet AddParameterUpdate name Plan model_gen range format RunNetOnce dump_model AddStep AddGradientOperators UniformIntFill net param_init_net time print order num_workers RunAllOnGPU forward_only RunNet ExecutionStep add_argument ArgumentParser basename ArgumentParser add_argument run MomentumSGD ConstantFill WeightedSum GetParams num_gpus list format time Parallelize_GPU _CheckLookupTables CNNModelHelper info range len add_argument ArgumentParser Create data FeedBlob csr_matrix indptr indices FetchBlob deleteInput str list items insertInput Transpose print ops Relu op prev maskNallocate NetDefNode type iter FC_Sparse next values items list transFCRelu append items list op insertInput print output op NetDefNode input type Proto enumerate CreateOperator FeedBlob assert_array_equal random_sample reshape astype int64 coo_matrix FetchBlob int32 RunOperatorOnce compute str extend sizeof append range append compute extend CreateOperator FeedBlob DeviceOption ModelHelper _RunComparison dict InitOpsLibrary CPU RunOperatorOnce tuple range batch_mat_mul Reshape s SequenceMask softmax s Tanh transpose fc s fc Squeeze s _apply_fc_weight_for_sum_match _calc_attention_logits_from_sum_match Add _calc_attention_weights _calc_weighted_context s _apply_fc_weight_for_sum_match _calc_attention_logits_from_sum_match Add _calc_attention_weights _calc_weighted_context s fc ExpandDims Squeeze BatchMatMul _calc_attention_weights _calc_weighted_context s _apply_fc_weight_for_sum_match _calc_attention_logits_from_sum_match Add transpose Squeeze Mul _calc_attention_weights _calc_weighted_context s int list strip map split make_blob_on_context context blob params input_name output_name str ModelHelper getattr chain range update format RunNetOnce add_op debug astype op operator Export type net kwargs int param_init_net iters float32 extend dict split communicate print Trie name exit append sum Popen split format print name size sort MaybeAddColor ReadableSize min_size GetSymbolTrie max_depth target color PrintTrie nm_command list stage set include len _run_operator SerializeToString op protos feed shape Workspace fetch_blob range Caffe2TensorToNumpyArray len i list remove extend append keys Argument _run_operator _GetLegacyDims protos SerializeToString _AdjustDims shape append fetch_blob range arg astype op type Caffe2TensorToNumpyArray _GetLegacyPadArgs float32 feed_blob match Workspace len _run_operator SerializeToString output op protos feed shape Workspace fetch_blob range Caffe2TensorToNumpyArray len shape input_shape dim input_dim CreateOperator NetDef extend protos bottom OperatorDef extend top extend pad_h stride_w pad_w kernel_h kernel_w AddArgument stride_h hasattr NumpyArrayToCaffe2Tensor flatten convolution3d_param pad BaseTranslate temporal_pad AddArgument append convolution_param NumpyArrayToCaffe2Tensor group _TranslateStridePadKernelHelper flatten BaseTranslate AddArgument append convolution_param NumpyArrayToCaffe2Tensor extend _TranslateStridePadKernelHelper bias_term flatten BaseTranslate AddArgument OperatorDef arg AddArgument astype float32 extend output BaseTranslate _GetBlobDimMap type crop_param range append len pooling_param torch_pooling CAFFE_LEGACY_POOLING global_pooling _TranslateStridePadKernelHelper BaseTranslate AddArgument hasattr pad pooling3d_param BaseTranslate temporal_pad AddArgument int lrn_param local_size extend k alpha beta BaseTranslate float AddArgument NumpyArrayToCaffe2Tensor reshape extend flatten inner_product_param BaseTranslate dropout_ratio dropout_param extend BaseTranslate AddArgument BaseTranslate CreateOperator BaseTranslate top_k AddArgument BaseTranslate extend AddArgument BaseTranslate NumpyArrayToCaffe2Tensor extend flatten BaseTranslate AddArgument eps NumpyArrayToCaffe2Tensor zeros_like extend tile BaseTranslate AddArgument batch_norm_param BaseTranslate eltwise_param deepcopy NumpyArrayToCaffe2Tensor axis flatten BaseTranslate AddArgument append scale_param reshape_param BaseTranslate dim AddArgument append BaseTranslate flatten_param BaseTranslate roi_pooling_param HasField spatial_scale pooled_h pooled_w BaseTranslate AddArgument append BaseTranslate NumpyArrayToCaffe2Tensor extend reduction_param AddArgument BaseTranslate FeedBlob read NetParameter TranslateModel RunNetOnce name astype Merge float32 protos SerializeToString ParseFromString Caffe2TensorToNumpyArray Net CountDown add_stop_signal _prev_enter enter _prev_exit exit get add list isinstance _MakeList _IsNets _MakeList _IsNets Net _MakeList ConstantFill AddExternalOutput isinstance Net AddExternalOutput Not GetConditionBlobFromNet Net Copy AddExternalOutput _attr_dict external_input viewitems extend op range Net AddExternalOutput GetConditionBlobFromNet Proto len _CopyConditionBlobNet Net AddExternalOutput GetConditionBlobFromNet range len _MakeList _MakeList isinstance BoolNet NotNet Net _IsNets _PrependNets _CopyConditionBlobNet isinstance Net _PrependNets GetConditionBlobFromNet CreateCounter scoped_execution_step Net _get_next_step_name _PrependNets CountDown isinstance BoolNet NotNet Net _IsNets _PrependNets str isinstance Net BlobReference _PrependNets GetConditionBlobFromNet isinstance BoolNet _AppendNets NotNet Net BoolNet GetConditionBlobFromNet _AppendNets BlobReference _MakeList _MakeList Net GetConditionBlobFromNet isinstance Net GetConditionBlobFromNet isinstance get_ssa get_undefined_blobs output op add set Proto list get_external_blob_names Name If set NextScopedBlob Net Do AddExternalOutput CreateScope append Proto str list get_external_blob_names Name ConstantFill op add NextScopedBlob Net Do AddExternalOutput CreateScope append While Proto ModelHelper fc sum ModelHelper relu fc max_pool conv softmax ModelHelper relu fc max_pool conv softmax ModelHelper relu fc max_pool conv softmax concat max_pool conv relu ModelHelper relu fc max_pool conv average_pool softmax iter cudnn_ws engine op items list setattr _GetRegisteredOperators extend global_init DeviceOption op output CPU device_option DeviceOption SerializeToString ParseFromString append infer_op_input_output_device decode isinstance append ScopedBlobReference RunOperatorImmediate OperatorDef CopyFrom _RectifyInputOutput viewitems extend MakeArgument IsImmediate CurrentDeviceScope isinstance backward register_python_gradient_op register_python_op python_func_type forward _RegisterPythonImpl enumerate get str external_input isinstance output op input append set enumerate pop get_output_producers extend set arg remap_proto endswith len strings range get_remapped_str s CopyFrom arg Clone Net Proto n CopyFrom Clone Net Proto n set_input_record str list get_ssa get_undefined_blobs zip set dict field_names Clone viewkeys input_record field_blobs Proto set CPU CUDA _gen_new_name copy_func copy_func_between_devices list defaultdict external_input name Clone InferOpBlobDevices input append update op zip enumerate clear items OperatorDef CopyFrom extend_ops extend output index is_external_input append InjectCrossDeviceCopies InjectDeviceCopiesAmongNets NetDef isinstance get_net_name set report_net Substeps append network Proto name get isinstance _stop_blob SetIter all SetOnlyOnce isinstance SetConcurrentSubsteps SetNumConcurrentInstances SetShouldStopBlob RunEveryMillis to_execution_step AddSubstep SetCreateWorkspace ExecutionStep SetReportNet AddNet append f_back _getframe replace output zip HasField CopyFrom device_option Net run Net run FeedBlob str NextName AddExternalInput array Net Print Parallelize Parallelize DeviceOption _BroadcastComputedParams _AllReduceBlobs CUDA _InferBlobDevice params warning viewkeys _device_grouped_blobs _ValidateParams GetParams list _SyncAllParams name _GroupByDevice NumCudaDevices _GetReverseOrderedGrads add _OptimizeGradientMemorySimple _PruneParametersForSharing update format copy set CPU _device_type _RemapParameterBlobsForSharedModel info _AddGradientOperators _ComputeBlobsToSync net _AnalyzeOperators param_to_grad param_init_net min GetComputedParams optimizer_builder_fun _AddDynamicMemoryOptimization len Parallelize_BMUF Parallelize_BMUF DeviceOption _AllReduceBlobs CUDA _InferBlobDevice params warning viewkeys _device_grouped_blobs _ValidateParams _losses_by_gpu _ForEachDevice list _SyncAllParams _GroupByDevice NumCudaDevices _OptimizeGradientMemorySimple range format _global_model_param_updates_net copy CPU Net _device_type _AddGradientOperators param_init_net min _warmup_broadcast AddBlobSync len _data_parallel_model_init_nets CreateNet _data_parallel_model_nets RunNetOnce isinstance RunNetOnce _warmup_broadcast RunNet net _warmup_iterations name _data_parallel_model_nets isinstance str _CreateOrCloneCommonWorld RunNetOnce Net Barrier info external_output deepcopy control_input format CopyFrom external_input output op cuda_gpu_id input CurrentDeviceScope enumerate DeviceOption AddGradientOperators DeviceOption _device_type _device_prefix format add set op _ComputeBlobsToSync GetDevices _SyncAllParams CreateNet RunNetOnce _ComputeBlobsToSync name _rendezvous Net RunAllOnGPU _checkpoint_net info RunNet append op output DeviceOption CUDA _IsGPUBlob CPU _device_type sumN list viewvalues _Broadcast GetCudaPeerAccessPattern range NCCLAllreduce _SyncAllParamsDistributed _SyncAllParamsSingleHost param_init_net _SyncAllParams _devices _rendezvous set join _CreateOrCloneCommonWorld Allreduce param_init_net DeviceOption list sorted viewvalues CollectivesConcurrencyControl CPU _broadcast_context _device_type _Broadcast _Broadcast _AllReduceBlobsDistributed _AllReduceBlobsSingleHost format set _device_prefix params GetParams param_init_net format set _device_prefix GetParams info modify_ops net param_init_net DeviceOption list str allreduce viewvalues num_workers CollectivesConcurrencyControl _device_type _Broadcast list DeviceOption viewvalues _IsGPUBlob set _device_type _BroadcastComputedParamsSingleHost _BroadcastComputedParamsDistributed _BroadcastComputedParamsSingleHost warn _computed_param_names net _Broadcast str isinstance GradientSlice list format input output op cuda_gpu_id _device_prefix device_option map_ops Proto _device_prefix format int list stripBlobName format isinstance error viewitems OrderedDict viewkeys BlobReference enumerate len append sorted enumerate set _shared_model update sorted list op extend set _param_names _device_prefix len param_to_grad format viewvalues share_grad_blobs set _device_prefix warning net update format add set _device_prefix release_blobs_when_used Proto param_to_grad format _devices InferShapesAndTypes viewitems viewvalues share_grad_blobs set _device_prefix net format arg CreateCommonWorld op dict CloneCommonWorld i format stripBlobName op output add set _device_prefix GetParams input append update list format output op set cuda_gpu_id _device_prefix input InjectCrossDeviceCopies param_init_net format viewitems _ShiftActivationDevices info net len BatchFeeder CurrentNameScope DeviceOption Thread append add Metrics get_queue CurrentDeviceScope WorkerCoordinator _enqueue_batch is_active append randint range zeros randint rand print _init_impl format RefreshRegisteredOperators add seed FeedBlob format RunNetOnce transpose CreateBlobsQueue Net info range EnqueueBlobs Proto format RunNetOnce GaussianFill Net info Gather DequeueBlobs ModelHelper SinusoidPositionEncoding batch_size seq_length CreateNet name iters_to_report range format create_model RunNetOnce generate_data generate_embedding_table data_size info net param_init_net time embedding_size min RunNet add_metaclass ABCMeta setdlopenflags getdlopenflags RTLD_GLOBAL namedtuple setdefault sorted draw shape lists integers tensor len CreateOperator RunOperatorOnce BlobReference isinstance items list RunNetOnce Name Clone AddGradientOperators flatten assert_allclose append NodeProto NodeProto MergeFrom add recursive_path_builder HierarchyProto root_node lists draw dims assume integers lists dims integers booleans floats elements_of_type lists dims lists dims map partial lists dims flatmap lists dims ResetWorkspace SwitchWorkspace CurrentWorkspace deepcopy CopyFrom extend NetDef set set_input_record layers clone set_output_record add_operators Net shrink_output_schema _filter_layers set_input_record trainer_extra_schema layers output_schema set_output_record add_operators Net input_feature_schema shrink_output_schema metrics_schema _filter_layers set_input_record trainer_extra_schema metrics_schema layers output_schema set_output_record add_operators Net input_feature_schema shrink_output_schema create_init_net _filter_layers _generate_training_net_only loss apply_optimizers _generate_training_net_only AddGradientOperators field_blobs T min max round print astype float32 int32 append rnn_executor SoftmaxWithLoss ConstantFill set_rnn_executor_config num_layers UniformFill seq_length cudnn_LSTM Copy range format op AddGradientOperators startswith AddExternalInputs FeedBlob print LSTM extend hidden_dim zeros batch_size warning seq_length CreateNet name fixed_shape iters_to_report sum range format create_model RunNetOnce generate_data data_size info net FeedBlob param_init_net time min hidden_dim GetGPUMemoryUsageStats RunNet array gpu memonger_compute_blob_recycling_for_dag warn Proto NetDef list SerializeToString add encode input append external_output format op set ParseFromString info enumerate is_grad_op deepcopy time output memonger_compute_blob_recycling_for_dag Proto NetDef list external_input SerializeToString add encode input union external_output format op set ParseFromString info is_activation_blob deepcopy time output remove defaultdict output op add set num_bytes max external_output deepcopy list remove CreateOperator insert output op add set reversed extend intersection input range len append list predecessors append list successors deepcopy add_edge _next_available_idx _find_target_nodes add_node append min _get_path deepcopy bellman_ford edges add_edge DiGraph add_nodes_from zip _compute_tree_height _get_height _add_single_target_ifneeded _sort_tree_leaves list lexicographical_topological_sort descendants _build_tree viewvalues _get_longest_paths _find_source_nodes set add dict topological_sort append defaultdict min output _replace defined warning input max used enumerate max is_compatible _get_max_size append float abs enumerate deepcopy format _get_compatible_prev info append _find_best enumerate _get_max_live sorted format get_updated_ranges viewitems compute_assignments_greedy info compute_assignments_dp len zip add_edge DiGraph output any intersection add_node enumerate apply_recurrent_blob_assignments output op startswith input canonical_name enumerate format external_input debug viewitems extend apply_assignments Argument encode type enumerate canonical_name n NetDef ParseFromString memonger_optimize_inference_net SerializeToString deepcopy compute_ranges op extend apply_assignments ordering_function compute_interference_graph compute_blob_assignments compute_assignments op zip format print op zip parent_list nbytes viewvalues sum input op output blob_nbytes input op output op union output set ClearField issuperset rename_list max Proto str list external_input name intersection input validate_op append union external_output update arg debug op set Net type device_type min output extend difference cuda_gpu_id CUDA DeviceOption CPU DeviceOption list range len Copy Add str Copy Add str Copy Add Add Copy range len Lock acquire release Const stop_if LT Const Const NetDef hasattr isinstance name op Proto _rectify_operator_and_name str defaultdict Dot add_edge node_producer _escape_label output GetOpNodeProducer Edge Node input enumerate add_node update _rectify_operator_and_name add_edge defaultdict Dot all node_producer output GetOpNodeProducer Edge enumerate add_node HasField network op enumerate add_edge _escape_label Edge Node append enumerate add_node add_edge _draw_nets format concurrent_substeps _escape_label substep_edge get_label len Edge Node substep append network enumerate add_node execution_step Dot _draw_steps _rectify_operator_and_name str defaultdict input _escape_label output append enumerate len func GetPydotGraph get_name viewitems write minimal GetPydotGraphMinimal write_pdf output_prefix input define_blob need_blob output analyzer op define_blob Proto node AddStep Plan SerializeToString get_step len tasks analyzer epoch_group init_group str isinstance decode HasField ints strings floats min max enumerate isinstance join join list arg format_device_option input c2_net_name HasField output add call device_option type append name text op add call c2_syntax text Proto report_net Proto should_stop_blob Proto _get_step_context join text exit_group epoch_group init_group Printer printer str print_op extend op Net Text LogInfo get str update _prepare_blob_copy_op set add _do_op_sanity_check_and_process BlobReference zip _gen_subgradient_pass _prepare_gradient_do_op append update NetDef CopyFrom list _prepare_gradient_if_op name extend set _gen_if_branch_gradient _gen_grad_zero_init_ops BlobReference zip _get_net_argument str NetDef CopyFrom input name output extend add set _gen_subgradient_pass arg str list items IR op GetBackwardPass arg ints add set zip _get_net_argument OperatorDef extend NetDef CopyFrom OperatorDef list name extend append keys Argument items list OperatorDef extend append Argument OperatorDef CopyFrom name extend append Argument update param_init_net net InferBlobDevices str isinstance GradientSlice FeedBlob array str blob _calc_norm_ratio ConstantFill _get_param_to_device grad GetOptimizationParamInfo add_lr_multiplier Validate get_param_device append Mul _build WeightDecayBuilder SgdOptimizer MultiPrecisionSgdOptimizer FP16SgdOptimizer FtrlOptimizer AdagradOptimizer AdamOptimizer YellowFinOptimizer RmsPropOptimizer CreateOperator _device_pid CUDA InitOpsLibrary _generate_data Parallelize_BMUF RunInitNet format RunNetOnce astype _global_model_param_updates_net assert_equal CPU FetchBlob info RunOperatorOnce net FeedBlob reshape float32 dict RunNet CNNModelHelper Metrics add WorkerCoordinator add_metaclass start is_active run RunOperatorOnce CreateOperator RunOperatorOnce CreateOperator writer hasattr isinstance setup_ex Queue Net isinstance isinstance _pipe_step _pipe_step outputs hasattr str format current str format current ProcessingReader hasattr reader isinstance processor_name SafeEnqueueBlobs NextName SafeDequeueBlobs list NextName pop CloseBlobsQueue Net execution_step str get_ssa NextName viewkeys BlobReference GetBackwardPass Proto str list external_input Sum append unpack_triple external_output get_undefined_blobs RecurrentNetwork op set Net enumerate s remove extend output add_arg RunOperatorOnce str op CreateOperator list apply_over_sequence cell_class append range len FeedBlob astype float32 FetchBlob viewkeys append array append LSTMWithAttentionCell build_initial_coverage apply_over_sequence pop update locals create_lstm enumerate isinstance shape dtype fields Scalar add_child len zip _SchemaNode range split set_value isinstance all_scalars clone_schema zip all isinstance field_blobs feed field_blobs isinstance zip clone set_value isinstance NewRecord Const field_blobs zip list NewRecord ConstantFill field_blobs shape data_type_for_dtype zip field_types as_record all_scalars set_metadata CurrentNameScope namescope CurrentDeviceScope DeviceOption node_name CopyFrom CurrentDeviceScope CurrentNameScope DeviceOption format CUDA assertEqual CurrentDeviceScope update copy hasattr setup isinstance insert exit Net append append execution_step set notify WatcherThread start acquire release WatcherThread start seed normal reshape dot flatten prod qr zeros sum array range arange concatenate tt_svd reshape size transpose astype float32 copy flatten repeat tile array range len svd reshape size copy ravel dot range zeros sum diag INT16 int16 list uint8 INT32 uint16 int FLOAT float64 astype extend int8 UINT16 shape TensorProto INT8 UINT8 DOUBLE NetDef CopyFrom ndarray isinstance tolist SerializeToString extend asscalar generic Iterable encode Argument cls Parse viewitems TryReadProtoWithClass viewitems TryReadProtoWithClass read RunOperatorOnce FetchBlob CreateOperator RunOperatorOnce list CreateOperator ndim ndim socket bind close AF_INET connect_ex SOCK_STREAM Process _GetFreeFlaskPort format print root_folder start getfqdn hasattr isinstance makedirs create_blob RunOperatorOnce Plan ExecutionStep isinstance list TensorShapes dims data_type ParseFromString infer_shapes_and_types_from_map shapes infer_shapes_and_types_from_workspace isinstance NetDef isinstance str dtype format astype StringifyBlobName object warning Caffe2TensorToNumpyArray CurrentDeviceScope NetDef SerializeToString ParseFromString encode apply_transform NetDef apply_transform_if_faster SerializeToString ParseFromString encode float SwitchWorkspace CurrentWorkspace print IsImmediate StopImmediate rmtree NetDef OperatorDef hasattr PlanDef isinstance Proto StringifyProto format relpath clone file addLink Name CreateNet add DeviceOption print int format open param_init_net int CreateNet ModelHelper RunNetOnce format print name range FetchBlob RunNet TensorProtosDBInput net create_db read_db_with_caffe2 output_file image_input StopGradient ConstantFill FloatToHalf GaussianFill _device_prefix format save_to_db PredictorExportMeta FeedBlob format info PREDICT_INIT_NET_TYPE GLOBAL_INIT_NET_TYPE Net RunAllOnGPU FetchBlob load_from_db GetNet int format _devices name epoch_size log _device_prefix FetchBlob RunNet info num_epochs range CreateOperator num_gpus batch_size Parallelize OptimizeGradientMemory epoch_size endswith warning SaveModel shard_id LoadModel list CreateNet ModelHelper str len getenv model_parallel range format RunNetOnce num_shards RunEpoch ModelTrainerLog GetActivationBlobs set CreateDB ShiftActivationDevices info RunOperatorOnce net int param_init_net remove FinalizeAfterCheckpoint load_model_path dict isfile split Train update deepcopy __name__ get_current_scope pop print net add_if_op add_while_op net get int isinstance ExternalInitializer update_initializer extend create_param transform_inputs append param_init_net ScopedBlobReference WEIGHT BIAS AddParameter init_params param_init_net ScopedBlobReference DepthSplit WEIGHT Concat BIAS Conv AddParameter append init_params range param_init_net ScopedBlobReference WEIGHT BIAS AddParameter init_params ExternalInitializer update_initializer COMPUTED_PARAM create_param append update_initializer create_param param_init_net ScopedBlobReference ConstantFill AddParameter init_params print AddParameter ScopedBlobReference init_params AddParameter param_init_net LRN BIAS InstanceNorm AddParameter WEIGHT ExternalInitializer update_initializer SpatialBN create_param init_params Mul LayerNorm create_param Add tuple list ImageInput NHWC2NCHW VideoInput CurrentNameScope ConstantFill Accuracy CopyGPUToCPU _get_weights ConstantFill WeightedSum equal_schemas get_key all_scalars FeatureSpec set_metadata categorical_limit Metadata expected_value field_metadata format iter_modules import_module __path__ __name__ update __subclasses__ buildcontent find lineChart arange loadtxt add_serie sample max lineChart arange loadtxt add_serie min reshape sample max_curves max range root join endswith glob join root sort visualize_file listen HTTPServer start port WSGIContainer create_resnet50 ModelHelper mkl astype FeedBlob RunAllOnMKL int32 MKLDNN op list reversed enumerate CreateOperator external_output DeviceOption MergeFrom mkl_tmp op extend last_producer rewrite_run_net_simple deepcopy rewrite_init_net_simple Proto deepcopy extend op enumerate fc ModelHelper fc ModelHelper ModelHelper relu fc ModelHelper relu conv ModelHelper relu spatial_bn ModelHelper dropout lrn relu fc max_pool conv create_resnet_32x32 ModelHelper create_resnet50 ModelHelper Initializer initializer_class CurrentNameScope items list _normalize_namescope add_scope_overrides print exit join remove rmdir walk int write flush str int format print strip min urlopen progressBar remove format isdir input print getURLFromName exit downloadFromURLToFile realpath eval symlink deleteDirectory dirname install makedirs prev_blob format SoftmaxWithLoss relu fc add_bottleneck max_pool spatial_bn ResNetBuilder conv average_pool range prev_blob relu fc spatial_bn ResNetBuilder conv average_pool softmax add_simple_block range op union output set NetDef dirname namedtuple viewitems defaultdict append split apply_over_sequence extend DropoutCell LSTMCell append rnn_unidirectional_layer append GaussianFill get len layer_func append enumerate format fc ConstantFill append enumerate len get dropout_keep_prob apply_over_sequence Reshape build_initial_rnn_decoder_states get_output_dim DropoutCell LSTMCell LSTMWithAttentionDecoder append enumerate fc extend FC XavierFill list reversed append max len append sort shuffle format target_corpus max_length source_corpus_eval gen_vocab target_corpus_eval info source_corpus gen_batches unk_threshold len seed use_bidirectional_encoder decoder_num_layers encoder_num_layers run_seq2seq_model list len zip stdin decode get_numberized_sentence format target_corpus join print gen_vocab load_models info Seq2SeqModelCaffe2EnsembleDecoder source_corpus unk_threshold len run_seq2seq_beam_decoder arange cumsum argsort shape zeros sum max range integers draw GetCuDNNVersion assert_array_equal assert_allclose field_names _assert_arrays_equal field_blobs zip integers lists draw sum draw floats integers lists sum _sparse_features_map from_blob_list draw _dense_features_map integers Struct _conv_2d_output_size extend append randint uniform range append randint range int zeros fill_diagonal integers tuples permutations floats append extend append array range len tanh reshape astype sigmoid int32 T concatenate print reshape dot sigmoid gru_unit zeros range integers tuples integers tuples print format ModelHelper any crop COLOR_BGR2RGB print min COLOR_RGB2BGR resize float cvtColor crop swapaxes print open create_test rmtree mkdtemp draw lengths arrays integers sampled_from range append len int concatenate array len sampled_from draw COMM_WORLD IsOperatorWithEngine Get_rank Get_size integers lists append seed GlobalInit main append CUDA DeviceOption tanh reshape astype sigmoid int32 reshape square sqrt shape prod T layer_norm_with_scale_and_bias_ref print reshape dot shape lstm_unit zeros range T reshape dot lstm_unit zeros range T lstm_reference dot range len dot reshape T dot reshape T expand_dims transpose sum matmul dot reshape T T exp concatenate reshape transpose dot compute_attention_logits lstm_unit zeros sum range T reshape dot lstm_unit zeros range T layer_norm_with_scale_and_bias_ref reshape dot lstm_unit zeros range integers tuples FeedBlob param_init_net format ModelHelper RunNetOnce print astype extend int32 append generate_input_state enumerate AddExternalInputs print MultiRNNCell apply_over_sequence UnrolledCell exp sum flatten zeros range shape zeros range len print dot flatten zeros range len integers lists zeros ndarray len ndarray len zeros range FeedBlob str seed CreateNet SparseLengthsSum print ones SparseLengthsSum8BitsRowwise Name astype now float32 Net BenchmarkNet integers sampled_from tuples multiply copy sqrt range len NetDef CopyFrom get_ssa str external_input extend FetchBlob Net PredictorExportMeta CreateNet RunNetOnce PREDICT_INIT_NET_TYPE GLOBAL_INIT_NET_TYPE PREDICT_NET_TYPE Net load_from_db GetNet Net extend Load parameters inputs_name predict_init_name _global_init_net predict_net_name parameters_name inputs create_predict_net global_init_name parameters outputs_name outputs AddBlobs create_predict_init_net MetaNetDef AddNet CreateOperator parameters get_meta_net_def RunOperatorOnce CreateOperator deserialize_protobuf_struct value CopyFrom nets META_NET_DEF op FetchBlob MetaNetDef CurrentDeviceScope inputs op extend net_type num_workers parameters Net outputs zero_fill inputs extend extra_init_net Net outputs AppendNet _ProtoMapGet blobs value _ProtoMapGet blobs add append add add struct_type ParseFromString str format batch_size print num_layers hidden_dim float seq_length len FeedBlob param_init_net format ModelHelper RunNetOnce print astype extend float32 int32 randint enumerate AddExternalInputs AddExternalInput CNNModelHelper create_resnet50 ConstantFill WeightedSum GaussianFill AddGradientOperators params UniformIntFill iter LearningRate conv_model_generators ModelHelper Parallelize int format print _device_prefix FetchBlob range shape int float resize astype float32 swapaxes astype float32 int asarray print closed delete append float empty array enumerate load chw removeMean crop_center rescale bgr batch | ## AICamera-Style-Transfer <p align="center"> <img src="extra/sample.jpg"> <br><br> Neural style transfer on your Android phone. </p> [AICamera](https://github.com/bwasti/AICamera) is an Android application showcasing implementations of [Caffe2](https://github.com/caffe2/caffe2) models for mobile. This particular fork implements [Neural Style Transfer](https://arxiv.org/abs/1508.06576), a unique way of applying artistic styles to photos using deep neural networks. ## Requirements | 1,627 |
cagatayyildiz/npde | ['gaussian processes'] | ['Learning unknown ODE models with Gaussian processes', 'Learning Stochastic Differential Equations With Gaussian Processes Without Gradient Matching'] | npde_helper.py npde.py kernels.py integrators.py utils.py param.py SDEEM ODERK4 Integrator Kernel RBF OperatorKernel BrownianMotion NPSDE NPODE save_model load_model fit_model build_model Param g plot_model vdp gen_data em_int plot_data NPSDE BrownianMotion vstack linspace NPODE OperatorKernel max run ones shape append meshgrid range asarray zeros T print min global_variables_initializer len format print plot_model vstack global_variables_initializer range run ktype fix_sn eval fix_ell fix_Z whiten fix_U fix_sf NPSDE BrownianMotion NPODE global_variables_initializer OperatorKernel run asarray pdf rvs em_int linspace eye zeros array range plot_data len g sort reshape hstack f flatten sqrt linspace unique zeros max range len kern U GridSpec vstack linspace K around whiten xticks forward max abs yticks show subplot list set_title matrix_triangular_solve set_xlabel transpose matmul em_int colorbar imshow title scatter savefig quiver legend meshgrid range format plot Ug eval Zg int T print Kzz rc min set_ylabel figure cholesky eye len GridSpec around linspace xticks abs gtrue yticks subplot list set_title set_xlabel colorbar imshow meshgrid range plot tight_layout int T set_ylabel figure zeros len | ## Nonparametric Differential Equations (npde) with Gaussian Processes This repository contains a Python implementation of npde - a nonparametric model for learning unknown differential equations. Two related papers are * [Nonparametric stochastic differential equations](https://arxiv.org/abs/1807.05748) * [Nonparametric ordinary differential equations](https://arxiv.org/abs/1803.04303) Also, this repository overrides the [old MATLAB implementation](https://github.com/cagatayyildiz/npode) of our ODE model, which was published along with the paper. ### Demo Notebook More details, figures and usage examples can be found in this [demo notebook](https://github.com/cagatayyildiz/npde/blob/master/demo.ipynb). ### Python Code The implementation is in Python3.5, and it requires [TensorFlow(1.6.0+)](https://www.tensorflow.org/) and [GPflow(1.1+)](https://github.com/GPflow/GPflow). | 1,628 |
cagdasulas/ASL_CNN | ['denoising'] | ['DeepASL: Kinetic Model Incorporated Loss for Denoising Arterial Spin Labeled MRI via Deep Residual Learning'] | asl_model_process.py main.py asl_loss.py cnn_nets.py rmse_loss_l1 cbf_model asl_loss rmse_loss_l2 plot_stats rmse_metric model_train ssim_metric model_predict log10 psnr_metric conv_block consecutive_blocks dilated_conv_net level_block UNet conv_fully_con_net consecutive_net main split_data load_data exp time constant print reshape Adam shape lambda_blood scalar_constant alpha consecutive_net PLDs T1blood labelduration compile fit predict constant log show plot xlabel grid ylabel title savefig legend conv_block int print level_block Input print Input range print consecutive_blocks Input range print Input range int permutation arange setdiff1d xdata size ylabel mask M0 shape CBF zeros round time print model_train split_data model_predict load_data savemat subject_batch_size | # DeepASL This repository contains the implementation of the DeepASL paper published in MICCAI 2018: DeepASL: Kinetic Model Incorporated Loss for Denoising Arterial Spin Labeled MRI via Deep Residual Learning Publication Link: https://link.springer.com/chapter/10.1007/978-3-030-00928-1_4 ArXiv Link: https://arxiv.org/abs/1804.02755 The synthetic ASL data can be downloaded as .mat file from here: https://www.dropbox.com/s/vlmj8ty9oq5naak/synthetic_net_data.mat?dl=0 Put the synthetic data inside the project folder after downloading it. Some common ASL related variables are stored in 'synthetic_common_vars.mat' and already availble in the repository. The implementation is based on Keras framework with Tensorflow backend. Please ensure that both Keras and Tensorflow are installed to your machine before running the 'main.py' module. Please cite the paper if you use this implementation in your work. If you have questions regarding the implementation or want to report any bug, please drop me an email through [email protected] | 1,629 |
caglar/structured_mlp | ['unsupervised pre training'] | ['Knowledge Matters: Importance of Prior Information for Optimization'] | patch_mlp.py learning_algo.py mlp.py structured_mlp.py tests/test_small_structured_mlp_11output_1hot_10.py tests/test_small_structured_mlp_11output_1hot_2.py tests/test_small_structured_mlp_11output_1hot_4.py dataset.py tests/test_small_structured_mlp_11output_1hot.py tests/test_structured_mlp_50output.py tests/test_structured_mlp_100output.py tests/utils.py tests/test_structured_mlp_11output_1hot.py tests/test_structured_mlp_11output.py utils.py tests/ds_utils.py layer.py Dataset HiddenLayer PretrainingLayers LogisticRegressionLayer Layer LearningAlgorithm NeuralActivations Costs MLP PatchBasedMLP StructuredMLP NeuralActivations Costs get_dataset_obj_patches get_dataset_patches as_floatX get_three_obj_patches shared_dataset safe_update get_patches get_dataset_obj_patches get_dataset_patches get_three_obj_patches shared_dataset get_patches load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels load_file normalize_data experiment get_binary_labels as_floatX get_data_patches get_features standardize safe_update normalize reshape flatten sqrt vstack range shared asarray tolist _shared append get_patches append range get_patches append tolist range get_three_obj_patches ndarray isinstance items list asarray tolist vstack mean std append endswith load open print StructuredMLP train ftensor3 set_test_data get_dataset_patches abs max min mean std Dataset setup_pretraining_dataset function print h_fn encode zeros range | caglar/structured_mlp | 1,630 |
cagrell/gp_constr | ['gaussian processes'] | ['Gaussian processes with linear operator inequality constraints'] | GPConstr/model.py GPConstr/r_functions/python_wrappers.py GPConstr/util/linalg.py GPConstr/kern.py test_py.py GPConstr/util/div.py GPConstr/util/stats.py main fun kernel_Stationary kernel_RBF_generic kernel_Matern52 kernel_RBF GPmodel _scipyopt_test Constraint moments_from_samples mtmvnorm pmvnorm param_py_to_r rtmvnorm formattime len_none mulinv_solve_rev nearestPD triang_solve try_jitchol isPD_det is_symPD_svd chol_inv traceprod jitchol isPD_chol mulinv_solve symmetrify norm_cdf_int trunc_norm_moments_approx_corrfree normal_cdf_approx norm_cdf_int_approx mode_from_samples optimize print lhs kernel_RBF GPmodel array array minimize FloatVector r_rtmvnorm array param_py_to_r param_py_to_r r_mtmvnorm param_py_to_r rtmvnorm divmod svd T format print dot eigvals max cholesky jitchol svd T spacing norm min dot eye real eigvals isPD diag print dpotrf ascontiguousarray mean any cholesky eye diag asfortranarray triang_solve matrix solve T triu_indices_from dpotri matrix symmetrify norm normal_cdf_approx exp sqrt abs pi T fit zeros range differential_evolution sqrt normal_cdf_approx diag pdf | # GPConstr - Gaussian Process regression with linear operator constraints Python module for constrained GP regression. Code based on the paper [_C. Agrell (2019) Gaussian processes with linear operator inequality constraints_](https://arxiv.org/abs/1901.03134). The current implementation covers boundedness of the function to estimate, combined with bounds on its first order partial derivatives, using the RBF or Matérn5/2 kernel. ### Prerequisites Besides the standard numpy/scipy libraries, [rpy2](https://pypi.org/project/rpy2/) is used to access some useful R packages for working with the truncated multivariate normal distribution. The code has been tested with the following requirements: __Python 3 (3.6.3 64bit)__ - __numpy (1.14.0)__ - __scipy (1.1.0)__ - __pandas (0.22.0)__ - __sklearn (0.19.1)__ _Only uses the function sklearn.metrics.pairwise.euclidean_distances from this package for fast computation of Gram matrices (and could easily be replaced by custom code if needed)_ | 1,631 |
caijincen712/CE | ['video retrieval'] | ['Use What You Have: Video Retrieval Using Representations From Collaborative Experts', 'Learning a Text-Video Embedding from Incomplete and Heterogeneous Data'] | data_loader/ActivityNet_dataset.py misc/gen_readme.py data_loader/YouCook2_dataset.py utils/ranger.py utils/datastructures.py model/text.py misc/prepare_text_embeddings.py model/__init__.py utils/util.py misc/gen_tar_lists.py base/base_trainer.py train.py logger/visualization.py trainer/__init__.py data_loader/DiDeMo_dataset.py data_loader/LSMDC_dataset.py data_loader/VaTeX_dataset.py sent_feat_demo.py logger/logger.py data_loader/data_loaders.py model/net_vlad.py model/loss.py misc/generate_exps.py logger/log_parser.py utils/__init__.py trainer/trainer.py misc/generate_slurm_scripts.py misc/sync_experts.py data_loader/QuerYD_dataset.py misc/aggregate_logs_and_stats.py test.py misc/cvpr2020_challenge/prepare_submission.py utils/gen_ablations_for_dataset.py misc/cvpr2020_challenge/train_baselines.py logger/__init__.py misc/find_latest_checkpoints.py utils/html.py parse_config.py model/metric.py data_loader/QuerYDSegments_dataset.py data_loader/MSVD_dataset.py base/__init__.py model/model.py base/base_dataset.py model/mil_nce_net.py base/base_model.py utils/radam.py utils/cos_restart.py utils/visualizer.py misc/cvpr2020_challenge/test_baselines.py data_loader/MSRVTT_dataset.py _set_by_path ConfigParser _get_opt_name _update_config _get_by_path sent_feat compress_predictions evaluation get_model_and_data_loaders main run_exp BaseDataset BaseModel BaseTrainer ActivityNet dataset_loader ExpertDataLoader DiDeMo LSMDC MSRVTT MSVD QuerYDSegments QuerYD VaTeX YouCook2 setup_logging log_summary TensorboardWriter main summarise main formatted_summary generate_configs main parse_grid fill_template parse_group_ids aggregation_script_path2job_name generate_aggregation_script generate_script main jobn_name2agg_log_path generate_slurm_dependency_script generate_tar_lists parse_results sync_files generate_url parse_log parse_generate_readme gen_latex_version_of_table generate_readme multiprocessing_parsing model_specs2path generate_results_string main dataset_paths parse_geom_means_from_val_runs small_font_str generate_tar_lists main generate_tar_lists_for_challenge prepare_text_with_yaspi extract_embeddings validate_embeddings_against_reference prepare_embedding_model main extract_embeddings_for_video upload_to_server upload_models_to_robots get_archive_name fetch_from_server main validate_predictions main generate_predictions get_dataset_num_queries json_key2dataset_name main evaluate_from_ckpts launch_and_monitor_cmd train_baseline_for_dataset train_baselines train_baselines_with_yaspi main dataset_name2json_key parse_paths_from_logs BCEWithLogitsLoss CrossEntropyLoss MaxMarginRankingLoss retrieval_as_classification APMeter ClassErrorMeter v2t_metrics AverageMeter Meter cols2metrics mean_average_precision t2v_metrics APMeterChallenge MNNet RelationModuleMultiScale_Cat ContextGating TemporalAttention MimicCEGatedEmbeddingUnit drop_nans sharded_cross_view_inner_product Mish SpatialMLP ContextGatingReasoning GatedEmbeddingUnit kronecker_prod GatedEmbeddingUnitReasoning G_reason CEModule ReduceDim sharded_single_view_inner_product RelationModuleMultiScale CENet NetVLAD OpenAI_GPT TextEmbedding load_w2v_model_from_cache W2VEmbedding fetch_model verbose ctxt_mgr Trainer CosineAnnealingWithRestartsLR main ExpertStore gen_dict_store main handle_moee_config remove_audio_streams HTML AdamW RAdam PlainRAdam Ranger memory_summary compute_dims read_json parse_grid set_seeds Timer save_image ensure_tensor get_short_uuid mkdirs tensor2im compute_trn_config filter_cmd_args inf_loop mkdir write_json flatten_dict expert_tensor_storage path2str print_numpy update_src_web_video_dir Visualizer _set_by_path target _get_opt_name getattr flags startswith from_pretrained basicConfig asarray print convert_tokens_to_ids get_vector eval load_word2vec_format tensor to tokenize append split argsort shape load pop print compute_dims compute_trn_config DataParallel resume load_state_dict init info _config seed list str getattr to get_logger get format eval init get_model_and_data_loaders manual_seed info merge deepcopy items visualize_ranking update_src_web_video_dir _args endswith compute_dims Trainer set_seeds save_dir _config str strftime apply home get_logger get filterwarnings log_summary compute_trn_config gmtime mkdir init info optim merge enumerate lr_scheduler time deepcopy group_seed print system parameters filter update_src_web_video_dir evaluation train leaderboard ConfigParser print add_argument add_mutually_exclusive_group refresh_lru_cache ArgumentParser dbg run_exp YouCook2 MSVD MSRVTT print VaTeX DiDeMo dict ActivityNet LSMDC QuerYD QuerYDSegments str basicConfig list items print getcwd read_json dictConfig Path is_file argmax items list defaultdict search index array info append float gmean keys split items list sorted basicConfig parent getLogger print glob addHandler read_json log_summary extend StreamHandler OrderedDict removeHandler Path parse_args summarise items list sorted glob strptime relative_to print formatted_summary join list product print strftime mkdir append keys print append OrderedDict split generate_configs grid parse_grid append zip_longest finditer groups OrderedDict enumerate append split append join list items jobn_name2agg_log_path mkdir aggregation_script_path2job_name parse_group_ids parse_grid Path touch values list stem append range update fill_template replace generate_aggregation_script mkdir zip generate_slurm_dependency_script items print extend aggregation_script_path2job_name jobn_name2agg_log_path len generate_script pop join list NoEscape Tabular tuple dumps reversed index add_hline mkdir Path findall add_row append Path items list replace print call Path startswith expanduser items list Path append split import_module getattr Path get_dataset_paths update items list set add model_specs2path tqdm Path mkdir append dataset_paths items list search index zip append float gmean split int std replace print OrderedDict nan item zip parse_geom_means_from_val_runs split print parse_log summarise Path startswith listdir items list time Process join format print start Path mkdir append join list items print insert append replace zip millify print generate_url gen_latex_version_of_table extend groups upper startswith zip_longest append finditer generate_results_string split parse_results generate_readme sync_files parse_generate_readme print update deepcopy list isinstance print glob load_json_config set add model_specs2path any Path mkdir append dataset_paths values generate_tar_lists generate_tar_lists_for_challenge endswith update defaultdict Path update items list print memcache tqdm zip dataset_paths values append join text2vec extend put device to_iterator list set_device append sum memcache set validate_embeddings_against_reference mkdir func zip init pop items print extend tqdm remote prepare_embedding_model len submit join list extract_embeddings argv product Yaspi filter_cmd_args append update str extract_embeddings prepare_text_with_yaspi yaspify system dict slurm use_cnodes device home startswith items list get_archive_name time zip print insert system strftime call gmtime Path startswith mkdir append items list time print strftime call gmtime Path listdir get_archive_name print call unlink Path mkdir upload_to_server upload_models_to_robots fetch_from_server dataset print shape get_dataset_num_queries join sorted st_size print strftime mkdir naturalsize generate_predictions get items launch_and_monitor_cmd list json_key2dataset_name print strftime lower append generate_predictions parse_paths_from_logs evaluate_from_ckpts get sum index print lower launch_and_monitor_cmd parse_paths_from_logs items train_baseline_for_dataset print mkdir dataset_name2json_key generate_predictions submit join argv Yaspi extend filter_cmd_args train_baselines strftime timestamp train_baselines train_baselines_with_yaspi zs_dispFig zeros_like where reduceat str use matshow set_trace shape append home sum insert unique print sort argwhere array diag diff zs_dispFig where str use matshow ones shape append home sum range inf insert mean unique T sort array diag zs_dispFig str T use insert sort grid set_trace extend mean shape hist append home array range mean gmean median float sum APMeter add bmm size view flatten set_trace numel view print ones size reshape set_trace device div mean unsqueeze item zip zeros to enumerate len list reshape shape unsqueeze item device zeros keys enumerate mkdir print to items list print dict astype float16 get_data_paths ExpertStore astype dumps float16 gen_dict_store remove replace remove_audio_streams replace handle_moee_config src_dataset update_ablation_list any Path dest_dataset append split append sorted pop index items list deepcopy join product zip get_short_uuid enumerate seed manual_seed Path print virtual_memory update items list isinstance get items list all add set intersection str list items isinstance path2str repeat list keys get items sorted list hasattr OrderedDict split info append get_logger len from_numpy data isinstance transpose tile Tensor numpy fromarray save print float64 flatten astype mkdir makedirs | This repo provides code: - TeachText which leverages complementary cues from multiple text encoders to provide an enhanced supervisory signal to the retrieval model using a generalize distillation setup ([project page](https://www.robots.ox.ac.uk/~vgg/research/teachtext/)) - Learning and evaluating joint video-text embeddings for the task of video retrieval. The approach is described in the paper "Use What You Have: Video retrieval using representations from collaborative experts" ([paper](https://arxiv.org/abs/1907.13487), [project page](https://www.robots.ox.ac.uk/~vgg/research/collaborative-experts/)) - CVPR 2020 Pentathlon challenge **Requirements:** The code assumes PyTorch 1.4 and Python 3.7 (other versions may work, but have not been tested). See the section on dependencies towards the end of this file for specific package requirements. ### TeachText  **TeachText results on MSRVTT Benchmark** | Model | Split | Task | R@1 | R@5 | R@10 | R@50 | MdR | MnR | Geom | Links | | ----- | ------| ---- | --- | --- | ---- | ---- | --- | --- | --- | ----- | | 1,632 |
cairohy/hsp | ['semantic parsing'] | ['Complex Question Decomposition for Semantic Parsing'] | decomp_models/model_utils/attention.py decomp_models/model_utils/common.py utils/vocab.py utils/rouge_metric/rouge.py WebAsKB/SplitQA.py WebAsKB/webaskb_ptrnet.py WebAsKB/Executors/conjunction.py WebAsKB/common/embeddings.py WebAsKB/noisy_supervision.py WebAsKB/Executors/executor_base.py WebAsKB/Models/Pytorch/attention_decoder.py WebAsKB/Net/run.py utils/params.py preprocess/gen_data.py decomp_models/seq2seq_sketch_v7.py WebAsKB/common/annotations.py utils/parallel.py WebAsKB/config.py WebAsKB/Models/Pytorch/encoder.py train.py data/batcher.py utils/optimize.py inference.py prepare/build_vocab.py evaluate.py utils/bleu_metric/bleu.py data/infer_data_processer.py utils/query_preprocess.py WebAsKB/golden_supervision.py decomp_models/transformer.py WebAsKB/Executors/simple_search.py decomp_models/two_stage_sketch_v4.py decomp_models/model_utils/embedding.py WebAsKB/Executors/composition.py decomp_models/model_utils/copy_mechanism.py preprocess/annotate_sequence.py utils/train_utils.py WebAsKB/webaskb_run.py decomp_models/model_utils/module.py decomp_models/__init__.py WebAsKB/Models/webaskb_ptrnet.py decomp_models/model.py prepare/shuffle_dataset.py utils/bleu_metric/bleu_scorer.py WebAsKB/common/utils.py decomp_models/beamsearch.py decomp_models/model_utils/layer.py decomp_models/transformer_copy_anno_v2.py decomp_models/model_utils/lstm_module.py calculate_sketch_type_acc evaluate calculate_exact_match build_pred_ref_dict build_pred_dict_from_ref ori_res_eval res_eval compute_bleu_rouge res_eval_with_type_acc calculate_sketch_performance calculate_exact_match_for_each_q_type parse_args main parse_args default_parameters main parse_args default_parameters Sample Batcher Batch concat_enc_output prepare_inf_features_stage3 prepare_inf_features_stage2 prepare_inf_features get_interface_input BeamSearchState _beam_search_step create_inference_ops_general beam_search get_inference_fn_general Model Seq2SeqSketchV7 Transformer TransformerCopyAnnoV2 TwoStageSketchV4 get_decomp_model compute_copy_weights add_timing_signal fast_dot_product_attention multihead_attention copy_attention dot_product_attention compute_qkv split_heads combine_heads infer_shape_invariants gather_2d merge_first_two_dims tile_batch infer_shape split_first_two_dims tile_to_beam_size set_first_dim_shape_return article2ids _dynamic_padding copy_mechanism_preprocess target2ids get_embedding get_embedding_may_pretrain linear attention_bias residual_fn layer_norm layer_process ffn_layer smoothed_softmax_cross_entropy lstm_decoder lstm_encoder transformer_concated_decoder transformer_decoder transformer_encoder save_vocab save_pretrain_vocab main count_words parse_args main parse_args parse_args Annotator parse_args DataGen smooth_cross_entropy create_train_op _maybe_repeat shard_features parallel_model GPUParamServerDeviceSetter data_parallelism _create_device_setter prepare_dir override_parameters override_infer_parameters import_infer_params parse_params import_params export_params collect_params parse_infer_params merge_parameters preprocess_sparql extract_sketch_from_sparql valid preprocess_query restore_variables init_variables tf_trunct get_learning_rate_decay write_result_to_file trunct get_initializer session_config load_word_matrix load_simple_vocab load_vocab decode_target_ids load_pretrained_vocab decode_target_ids_copy Bleu precook BleuScorer cook_test cook_refs my_lcs Rouge Config GoldenSupervision NoisySupervision SplitQA WebAsKB_PtrNet Annotations Lang embeddings WebKB_Utils Composition Conjunction ExecutorBase SimpleSearch WebAsKB_PtrNet_Model AttnDecoderRNN EncoderRNN NNRun add_argument ArgumentParser update open enumerate compute_score enumerate join list format print to_csv compute_bleu_rouge append DataFrame keys load items list print preprocess_query open join format print build_pred_ref_dict compute_bleu_rouge prefix build_pred_dict_from_ref list keys basename format zip strip info open join calculate_sketch_performance dirname exists update join list defaultdict format print len strip build_pred_ref_dict dirname split keys enumerate open join list format calculate_exact_match calcu_origin print ori_res_eval build_pred_ref_dict to_csv compute_bleu_rouge res_eval_with_type_acc prefix append DataFrame keys format calculate_exact_match print build_pred_ref_dict res_eval_with_type_acc HParams model get_decomp_model set_verbosity default_parameters parse_infer_params validation prepare_dir join basename get_parameters namedtuple parse_params output ARGS INFO beam_size source_ids_oo source_len reshape decode_length shape pos_anno tile source_ids expand_dims beam_size sketch_ids sketch_len reshape shape tile expand_dims beam_size reshape second_sketch_len shape second_sketch_ids tile expand_dims concatenate preprocess_query copy_mechanism_preprocess split concat state top_k map_structure finish to_float BeamSearchState split_first_two_dims expand_dims gather_2d func fill equal constant merge_first_two_dims reshape min pow int32 constant reduce_any zeros_like while_loop BeamSearchState min reduce_max where set_shape int32 tile fill zeros bool top_beams beam_size decode_alpha use_pos convert_to_tensor eosId bosId embed_dim map_structure get_inference_fn_general getattr linear concat split dropout linear squeeze matmul softmax convert_to_tensor as_list shape append range len as_list range len pop infer_shape infer_shape expand_dims ndims ndims reshape stack gather_nd range as_list set_shape get unkId index append len get unkId index append len article2ids target2ids max use_pretrained_embedding get_variable random_normal_initializer get_variable random_normal_initializer dropout items list sorted Counter zip list items sorted join format print inputfile emb_dim open dirname append split save_vocab outputfile print inputfile save_pretrain_vocab dirname zip count_words sum len seed arange suffix shuffle_anno shuffle to_float one_hot reshape cast int32 clip_by_value isinstance items list _maybe_repeat isinstance tuple zip range _create_device_setter len convert_to_tensor items list tile append expand_dims range len data_parallelism shard_features join abspath join abspath join MkDir list getattr add_hparam HParams keys items list add_hparam HParams setattr values use_pretrained_embedding dev_params parse model load_word_matrix parameters dirname vocab use_pretrained_embedding models parse load_word_matrix parameters dirname join override_parameters model output import_params export_params collect_params merge_parameters join output makedirs lower strip sub replace lower strip sub replace findall join initializer_gain to_float warmup_steps hidden_size minimum join OptimizerOptions device_list GraphOptions ConfigProto trainable_variables get_tensor load_checkpoint assign infer_shape list_variables info append zeros append strip open split append open array split use_pretrained_embedding append integer_types isinstance isinstance integer_types source_oovs zip append defaultdict tuple split range len get items precook list min append float sum max len list items precook max range len | # Complex Question Decomposition for Semantic Parsing This is the code base for ACL'19 paper `Complex Question Decomposition for Semantic Parsing`. ## 1. Preprocess ### 1.1 Download raw data Download ComplexWebQ data, prepare environment and libraries. ### 1.2 Requirements for preprocess In order to run preprocess, you should put the following files in DATA_PATH directory, DATA_PATH is defined in the script. - ComplexWebQuestions_train.json - ComplexWebQuestions_dev.json - ComplexWebQuestions_test.json (we need any other information in above files) | 1,633 |
calclavia/tal-asrd | ['speech recognition', 'speaker diarization', 'data augmentation'] | ['Speech Recognition and Multi-Speaker Diarization of Long Conversations'] | tal/asr/data/segment.py tal/utils/expand_speakers.py tal/asr/speech_detect.py tal/baseline/reconcile.py tal/asr/data/baseline_speaker.py tal/asr/logger.py tal/data_scratch/librispeech_end_file_length.py tal/diarization/features/wav2vec/__init__.py tal/data_scratch/tal_alignment_operations.py tal/__init__.py tal/asr/train_embed.py tal/diarization/features/wav2vec/extract_features_callhome.py tal/vad/__init__.py tal/data_scratch/convert_wav.py tal/diarization/uisrnn/train_large.py tal/utils/average_weights.py tal/diarization/features/dvec/__init__.py tal/vad/webrtcvad.py tal/diarization/uisrnn/loss_func.py tal/schedules.py tal/diarization/uisrnn/utils.py tal/vad/vad_tal_test.py tal/tsne_file_format.py tal/data_scratch/chunk_audio.py tal/diarization/uisrnn/arguments.py tal/wder_search.py tal/asr/tokenizers/sentencepiece.py tal/data_scratch/librispeech_speakers.py tal/diarization/uisrnn/evals.py tal/asr/data/aligned.py tal/utils/strip_output.py tal/optimizers.py tal/alignment/aeneas.py tal/wder.py tal/asr/data/util.py tal/diarization/features/wav2vec/extract_features_tal.py tal/utils/aligned_to_wder_format.py tal/utils/eval_transcripts.py tal/diarization/uisrnn/__init__.py tal/diarization/features/__init__.py tal/asr/transcribe.py tal/asr/tokenizers/__init__.py tal/baseline/speaker_system.py tal/asr/tokenizers/transformers.py tal/utils/prune_bad_utterances.py tal/utils/merge_outputs.py tal/asr/data/audio.py tal/apply_role_names_unaligned.py tal/wder_search_emb.py tal/asr/util.py tal/asr/gen_embed.py tal/modules.py tal/asr/train.py tal/utils/audio.py tal/asr/args.py tal/asr/data/__init__.py tal/vad/eval.py tal/wder_search_emb_new_format.py tal/asr/models.py tal/data_scratch/librispeech_fix.py tal/data_scratch/tal-cased.py tal/diarization/uisrnn/train.py tal/baseline/train.py tal/diarization/uisrnn/uisrnn.py tal/asr/test.py tal/asr/system.py tal/data_scratch/move_files.py weight_init PositionalEncoding RAdam Lookahead Lamb Adafactor inv_sqrt_schedule triangle_schedule corpus_wder cosine_distance wder_segment inverse_dot_product convert_to_wder_format get_list_inverse_index compute_sequence_match calculate_wer neg_dot_product tweet_tokenize hyperopt_obj cosine_similarity cluster_speakers calculate_wder cosine_distance get_word_speakers get_wder_edits wder_segment inverse_dot_product pairwise_ndp get_list_inverse_index pairwise_idp compute_sequence_match get_wder neg_dot_product tweet_tokenize cosine_similarity cluster corpus_wder_map cosine_distance get_word_speakers get_wder_edits wder_segment inverse_dot_product pairwise_ndp get_list_inverse_index pairwise_idp compute_sequence_match get_wder neg_dot_product tweet_tokenize cosine_similarity cluster corpus_wder_map cosine_distance get_word_speakers get_wder_edits wder_segment inverse_dot_product pairwise_ndp get_list_inverse_index pairwise_idp compute_sequence_match get_wder neg_dot_product tweet_tokenize cosine_similarity cluster corpus_wder_map debug_log set_seed SuppressPrint count_parameters get_device align_episode full_force_align tokenize get_lm_argparser get_argparser WandbLoggerWrapper LogMelSpec ASRModel SDModel TDSBlock freq_mask time_mask ModRZTXDecoderLayer TDS frame_generator read_wave get_speech_frames Frame write_wave main vad_collector transcribe_file load_model splice_ix DefaultArgs splice_strings transcribe_batch overlap_ix build_segment_cache_single AudioCollator RandomSegmentDataset is_valid_segment SDUtteranceDataset build_index SDUtteranceCollater Tokenizer Tokenizer _Tokenizer get_speaker_frames get_relative_ids get_speaker_ids System split_file convert_audio convert_wav convert_to_wav convert_time extend_utterance truncate_utterance push_utterance get_trained_wav2vec download_model str2bool parse_arguments compute_sequence_match_accuracy get_list_inverse_index regularization_loss weighted_mse_loss sigma2_prior_loss main run_experiment diarization_experiment main run_experiment diarization_experiment CoreRNN BeamState UISRNN enforce_cluster_id_uniqueness output_result concatenate_training_data estimate_transition_bias sample_permuted_segments resize_sequence Logger pack_sequence generate_random_string get_hyp_dict_wder convert_audio get_audio_info get_audio_info_wav convert_sphere prune_bad_utterances dict enumerate sorted linear_sum_assignment get_list_inverse_index set zip zeros sum len HDBSCAN fit_predict format isinstance print len extend index append cluster_speakers array enumerate eval list len zip list format print SequenceMatcher map compute_sequence_match from_iterable set eval zip len print convert_to_wder_format format calculate_wder list format print mean zip sum enumerate dot norm print int BayesianGaussianMixture isinstance DBSCAN PCA HDBSCAN fit_transform fit_predict AgglomerativeClustering get list format isinstance print len tokenizer index extend zip append array enumerate SequenceMatcher list sorted map compute_sequence_match from_iterable dict set zip range len get_word_speakers get_wder_edits now set dict get_wder eval cluster len items list defaultdict format sorted print ljust append format print fit now translate from_numpy mean isinstance stack enumerate float64 astype cuda normalize clip concatenate format print device is_available current_device seed manual_seed_all format print manual_seed sum format hasattr ndarray isinstance isneginf nditer isnan co_name log_fxn Tensor type isposinf join format print now output_sync_map_file Task execute getsize exists len load join int format list remove print now tqdm Task enumerate save zip execute getsize output_sync_map_file append len add_argument ArgumentParser add_argument ArgumentParser size range clone randrange size range clone randrange list format concatenate Vad print frame_generator vad_collector len int float clear int bytes duration write is_speech timestamp deque append len int list write_wave Vad read_wave print write exit frame_generator vad_collector enumerate join len SequenceMatcher len find_longest_match overlap_ix strip range splice_ix len resample get_speech_frames debug_fxn transcribe_batch list squeeze ceil append range format partial Resample info load int print extend tqdm len load format half_precision print count_parameters DefaultArgs half eval on_load_checkpoint load_state_dict to weights_path length join rate info join sum format isnan is_valid_segment append get_duration range len range len append arange tqdm load half append index load join format size save range convert_audio rsplit remove write call startswith flush load format replace print Resample now mean save cpu getsize cuda parse isinstance range len range len range len call getsize format print load join download_model format build_model print count_parameters now load_state_dict makedirs parse_known_args parse_args add_argument ArgumentParser sorted linear_sum_assignment get_list_inverse_index set zip zeros sum len float mm diag view load join output_result format list zip print debug count_parameters now UISRNN mean save out_dir __name__ rnn_model fit arange run_experiment test_seq quick_test exp_name values seed list set_seed from_iterable range format train_clusters shuffle mean train_seq load items print now dict test_clusters cross_validation len parse_arguments diarization_experiment shape type enumerate makedirs len glob ndarray isinstance tolist append generate_random_string enforce_cluster_id_uniqueness list concatenate shuffle shape zip enumerate permutation concatenate append range len sample_permuted_segments where unique append range len sort pack_padded_sequence choice zeros to range len rnn_dropout format learning_rate batch_size sigma_alpha mean rnn_depth rnn_hidden_size crp_alpha zip sigma_beta regularization_weight range len call format convert_sphere encoder_info hasattr length bitrate sample_rate channels codec info getsize __name__ getsize get_duration | # Speech Recognition and Multi-Speaker Diarization of Long Conversations Paper: https://arxiv.org/abs/2005.08072 To obtain our dataset of transcripts, please download it from: https://www.kaggle.com/shuyangli94/this-american-life-podcast-transcriptsalignments | 1,634 |
caleb221/MTCNN-Leaf | ['face detection', 'face alignment'] | ['Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks'] | jfda/detector.py jfda/utils.py join_bb_lm_Files.py jfda/lnet.py jfda/train.py jfda/mdetector.py jfda/prepare.py cleanDisData.py simpledemo.py readCaffeModel.py layers_new/data_layer.py get_centerLandmarks.py simplewebcam.py combineAlltext.py jfda/config.py jfda/minibatch.py layers/data_layer.py nameG nameG extract_caffe_model nms bbox_reg make_square gen_bbox crop_face nms bbox_reg make_square mtcnn_detection gen_bbox crop_face nms convert_image_pyramid get_original_bboxes JfdaDetector lnet_writer_func remove prepare fill_queues lnet_reader_func train MiniCaffeDetector MiniBatcher gen_wider celeba_reader_func celeba_writer_func test wider_writer_func gen_celeba wider_reader_func remove_if_exists sliding_windows fill_queues proposal get_detector Solver init_caffe load_cheat crop_face Timer load_wider load_scutbrainwashcheat get_logger load_celeba FaceDataLayer FaceDataLayer append str range data str list items print Net save copy_from TEST makedirs shape transpose reshape where append maximum minimum transpose print zeros data nms crop_face reshape transpose len astype float32 make_square vstack resize zeros forward gen_bbox enumerate bbox_reg zip resize append zeros max enumerate zeros vstack logical_and put range len exists SAMPLE_RADIUS warn put LNET_FACE_SCALES resize name transpose IMREAD_COLOR imread range get astype copy info crop_face LNET_SAMPLE_PER_FACE reshape float32 zeros get remove output_data info append gen load_celeba info seed epoch snapshot RNG_SEED GPU_ID get_data_size set_device lrp solve copyfile set_random_seed set_mode_gpu lr set_mode_cpu SolverParameter lrw SGDSolver print path rmtree info exists JfdaDetector GPU_ID set_device set_mode_gpu set_mode_cpu arange transpose hstack meshgrid array rand NEG_PROPOSAL_RATIO sliding_windows argmax max POS_PROPOSAL_STRIDE POS_PROPOSAL_SCALES NEG_PER_IMAGE append range asarray NEG_PROPOSAL_SCALES NEG_PROPOSAL_STRIDE shuffle PART_PROPOSAL_STRIDE detect NEG_FROM_FR_RATIO crop_face int print reshape PART_PROPOSAL_SCALES extend randint bbox_overlaps len reduce info gen load_wider len get name resize IMREAD_COLOR tostring put warning info imread proposal get_detector begin get encode commit print close put info fill append open load_celeba info gen NET_TYPE len get name reshape resize shuffle copy IMREAD_COLOR tostring put warning info imread proposal get_detector close info open asarray imwrite JfdaDetector print system IMREAD_COLOR info load_wider imread enumerate proposal len seed RNG_SEED GPU_ID set_device set_random_seed set_mode_gpu set_mode_cpu int parse asarray replace print text min getroot iter append listdir find int parse asarray replace print text min getroot iter append listdir find join get_dirmapper WIDER_DIR gen join int asarray CelebA_DIR print reshape len min append max range split setFormatter getLogger addHandler StreamHandler Formatter setLevel INFO | # MTCNN-Leaf An experiment to re-purpose MTCNN for other uses than facial detection This repo is the source code for implementing MTCNN using Caffe. # Introduction This was the first half of my Thesis project. The goal is to re-purpose the MTCNN Facial detection model and use it on an ESP-32 AI-Thinker WiFi Camera module. --> That code is in another repository: <a href="https://github.com/caleb221/ESP32-Leaf"> ESP32-Leaf</a> # MTCNN https://arxiv.org/pdf/1604.02878.pdf | 1,635 |
calmevtime/DCTNet | ['instance segmentation', 'semantic segmentation'] | ['Learning in the Frequency Domain'] | segmentation/mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py segmentation/mmdet/models/detectors/__init__.py segmentation/mmdet/core/utils/misc.py segmentation/mmdet/datasets/registry.py segmentation/mmdet/datasets/custom.py segmentation/mmdet/models/backbones/resnetDCT.py segmentation/mmdet/core/anchor/point_generator.py segmentation/mmdet/models/roi_extractors/single_level.py segmentation/mmdet/models/mask_heads/maskiou_head.py segmentation/mmdet/models/detectors/single_stage.py classification/utils/progress/progress/helpers.py segmentation/mmdet/models/detectors/htc.py segmentation/mmdet/models/anchor_heads/reppoints_head.py segmentation/mmdet/models/detectors/test_mixins.py segmentation/mmdet/models/anchor_heads/retina_head.py segmentation/mmdet/models/roi_extractors/__init__.py segmentation/mmdet/datasets/pipelines/test_aug.py segmentation/mmdet/models/utils/conv_ws.py segmentation/mmdet/models/losses/balanced_l1_loss.py segmentation/mmdet/models/detectors/base.py segmentation/mmdet/ops/dcn/deform_conv.py segmentation/mmdet/core/post_processing/__init__.py segmentation/mmdet/models/anchor_heads/fcos_head.py segmentation/mmdet/models/backbones/gate.py segmentation/mmdet/datasets/loader/sampler.py segmentation/mmdet/models/anchor_heads/ssd_head.py segmentation/mmdet/apis/env.py segmentation/mmdet/models/losses/accuracy.py segmentation/mmdet/models/bbox_heads/__init__.py segmentation/mmdet/apis/__init__.py classification/datasets/cvfunctional.py segmentation/mmdet/core/evaluation/eval_hooks.py segmentation/mmdet/models/detectors/fast_rcnn.py classification/utils/progress/progress/bar.py segmentation/mmdet/apis/train.py segmentation/mmdet/models/mask_heads/fcn_mask_head.py segmentation/mmdet/ops/__init__.py segmentation/mmdet/apis/inference.py segmentation/tools/test.py segmentation/mmdet/datasets/builder.py segmentation/mmdet/models/__init__.py segmentation/mmdet/models/anchor_heads/guided_anchor_head.py segmentation/mmdet/models/detectors/rpn.py segmentation/mmdet/core/utils/__init__.py segmentation/mmdet/models/shared_heads/__init__.py segmentation/mmdet/models/detectors/cascade_rcnn.py segmentation/mmdet/models/losses/mse_loss.py segmentation/mmdet/core/post_processing/merge_augs.py segmentation/mmdet/utils/transfer_model.py segmentation/mmdet/models/detectors/mask_scoring_rcnn.py segmentation/mmdet/core/bbox/transforms.py segmentation/mmdet/models/backbones/__init__.py segmentation/mmdet/utils/__init__.py classification/main/imagenet_resnet_upscaled_static.py segmentation/mmdet/core/evaluation/class_names.py segmentation/mmdet/core/fp16/decorators.py segmentation/mmdet/datasets/xml_style.py segmentation/mmdet/datasets/pipelines/formating.py segmentation/mmdet/models/losses/iou_loss.py segmentation/mmdet/core/__init__.py segmentation/mmdet/models/utils/scale.py classification/datasets/cvtransforms.py segmentation/mmdet/core/anchor/anchor_target.py segmentation/mmdet/models/detectors/double_head_rcnn.py segmentation/mmdet/datasets/coco.py segmentation/setup.py segmentation/mmdet/core/bbox/assigners/base_assigner.py classification/datasets/vision.py segmentation/mmdet/models/losses/utils.py classification/utils/visualize.py segmentation/mmdet/core/bbox/samplers/instance_balanced_pos_sampler.py segmentation/mmdet/models/utils/__init__.py segmentation/mmdet/datasets/loader/__init__.py classification/models/imagenet/resnet.py segmentation/mmdet/models/bbox_heads/double_bbox_head.py segmentation/mmdet/datasets/pipelines/dct_channel_index.py segmentation/mmdet/core/post_processing/bbox_nms.py segmentation/mmdet/models/utils/conv_module.py segmentation/mmdet/models/backbones/ssd_vgg.py classification/models/imagenet/mobilenetv2.py segmentation/mmdet/ops/nms/nms_wrapper.py segmentation/mmdet/utils/draw_inputgate.py segmentation/mmdet/models/plugins/non_local.py classification/utils/__init__.py segmentation/mmdet/models/losses/ghm_loss.py segmentation/mmdet/ops/dcn/deform_pool.py segmentation/mmdet/datasets/pipelines/loading.py segmentation/mmdet/core/anchor/anchor_generator.py segmentation/configs/faster_rcnn_r50_fpn_1x_static_24_wofreeze.py classification/datasets/dataset_imagenet_dct.py segmentation/mmdet/core/bbox/samplers/ohem_sampler.py segmentation/mmdet/models/builder.py segmentation/mmdet/ops/roi_align/gradcheck.py classification/utils/progress/setup.py segmentation/mmdet/ops/masked_conv/__init__.py segmentation/mmdet/models/utils/norm.py segmentation/tests/test_utils.py segmentation/mmdet/models/plugins/generalized_attention.py segmentation/mmdet/models/backbones/resnetDCT_dynamic.py segmentation/mmdet/core/anchor/__init__.py segmentation/mmdet/models/losses/focal_loss.py segmentation/mmdet/models/detectors/mask_rcnn.py segmentation/mmdet/core/bbox/samplers/random_sampler.py segmentation/mmdet/models/bbox_heads/convfc_bbox_head.py segmentation/mmdet/models/mask_heads/fused_semantic_head.py segmentation/mmdet/models/necks/bfp.py segmentation/mmdet/models/utils/weight_init.py segmentation/mmdet/core/mask/__init__.py segmentation/mmdet/core/bbox/assigners/assign_result.py segmentation/mmdet/datasets/dataset_wrappers.py segmentation/mmdet/core/evaluation/recall.py segmentation/configs/mask_rcnn_r50_rpn_1x_DCT_static_64_wofreeze.py segmentation/mmdet/models/necks/__init__.py segmentation/mmdet/models/detectors/reppoints_detector.py segmentation/mmdet/models/losses/smooth_l1_loss.py segmentation/mmdet/core/evaluation/mean_ap.py segmentation/mmdet/ops/nms/__init__.py segmentation/configs/mask_rcnn_r50_rpn_1x_DCT_static_24_wofreeze.py classification/main/imagenet_mobilenetv2_upscaled_static.py segmentation/mmdet/datasets/transforms.py segmentation/mmdet/datasets/pipelines/formatingDCT.py segmentation/mmdet/core/bbox/bbox_target.py segmentation/mmdet/models/detectors/grid_rcnn.py classification/models/imagenet/__init__.py classification/utils/logger.py segmentation/mmdet/datasets/extra_aug.py segmentation/mmdet/datasets/pipelines/transformsDCT.py segmentation/mmdet/models/plugins/__init__.py classification/utils/eval.py segmentation/mmdet/core/bbox/samplers/iou_balanced_neg_sampler.py segmentation/mmdet/utils/plot_dct.py segmentation/mmdet/models/mask_heads/htc_mask_head.py segmentation/mmdet/ops/sigmoid_focal_loss/__init__.py segmentation/configs/mean_std.py segmentation/mmdet/models/backbones/hrnet.py segmentation/mmdet/core/evaluation/coco_utils.py segmentation/mmdet/models/detectors/faster_rcnn.py classification/utils/misc.py segmentation/mmdet/utils/registry.py segmentation/mmdet/core/anchor/point_target.py classification/utils/init_weights.py segmentation/mmdet/datasets/wider_face.py segmentation/mmdet/core/bbox/assigners/approx_max_iou_assigner.py classification/datasets/dataloader_imagenet_dct.py segmentation/mmdet/models/detectors/two_stage.py segmentation/mmdet/models/backbones/resnet_dynamic.py segmentation/mmdet/models/anchor_heads/anchor_head.py segmentation/mmdet/models/mask_heads/grid_head.py segmentation/mmdet/models/necks/fpn.py segmentation/mmdet/ops/roi_align/__init__.py segmentation/mmdet/core/evaluation/__init__.py segmentation/mmdet/core/bbox/samplers/pseudo_sampler.py segmentation/mmdet/core/bbox/samplers/__init__.py segmentation/mmdet/core/evaluation/bbox_overlaps.py segmentation/mmdet/models/backbones/resnet_static.py classification/datasets/__init__.py classification/utils/progress/test_progress.py segmentation/mmdet/core/utils/dist_utils.py segmentation/mmdet/ops/roi_align/roi_align.py segmentation/mmdet/models/detectors/fcos.py segmentation/mmdet/datasets/__init__.py segmentation/mmdet/datasets/pipelines/compose.py segmentation/mmdet/core/bbox/assign_sampling.py classification/utils/progress/progress/__init__.py segmentation/mmdet/core/fp16/utils.py segmentation/mmdet/apis/mean_std_cal.py segmentation/mmdet/core/mask/mask_target.py segmentation/mmdet/models/losses/__init__.py segmentation/mmdet/models/registry.py classification/utils/progress/progress/spinner.py segmentation/configs/faster_rcnn_r50_fpn_1x_static_64_wofreeze.py segmentation/mmdet/datasets/loader/build_loader.py segmentation/mmdet/core/bbox/geometry.py segmentation/mmdet/datasets/cityscapes.py segmentation/mmdet/models/anchor_heads/__init__.py segmentation/mmdet/models/detectors/retinanet.py segmentation/mmdet/core/anchor/guided_anchor_target.py segmentation/mmdet/core/bbox/samplers/sampling_result.py segmentation/mmdet/datasets/voc.py segmentation/mmdet/__init__.py segmentation/mmdet/models/anchor_heads/ga_retina_head.py segmentation/mmdet/ops/roi_pool/__init__.py classification/utils/progress/progress/counter.py segmentation/mmdet/core/mask/utils.py segmentation/mmdet/models/backbones/resnet.py segmentation/mmdet/models/bbox_heads/bbox_head.py segmentation/mmdet/models/backbones/gumbel.py segmentation/mmdet/ops/dcn/__init__.py segmentation/mmdet/core/bbox/samplers/combined_sampler.py segmentation/mmdet/models/shared_heads/res_layer.py segmentation/mmdet/core/bbox/assigners/point_assigner.py segmentation/mmdet/models/backbones/resnext.py segmentation/mmdet/ops/roi_pool/gradcheck.py segmentation/mmdet/ops/masked_conv/masked_conv.py segmentation/mmdet/models/anchor_heads/rpn_head.py segmentation/mmdet/core/bbox/assigners/__init__.py segmentation/mmdet/ops/roi_pool/roi_pool.py segmentation/mmdet/models/mask_heads/__init__.py segmentation/mmdet/core/fp16/__init__.py segmentation/mmdet/models/necks/hrfpn.py segmentation/mmdet/utils/flops_counter.py segmentation/mmdet/core/bbox/__init__.py segmentation/mmdet/core/bbox/samplers/base_sampler.py segmentation/mmdet/datasets/pipelines/transforms.py segmentation/mmdet/models/anchor_heads/ga_rpn_head.py segmentation/mmdet/models/losses/cross_entropy_loss.py segmentation/mmdet/datasets/pipelines/__init__.py segmentation/mmdet/ops/context_block.py segmentation/mmdet/core/fp16/hooks.py classification/models/utils.py classification/main/__init__.py segmentation/mmdet/core/bbox/assigners/max_iou_assigner.py hflip salt_and_pepper resize to_rgb_bgr to_tensor_dct cv_transform pil_transform to_grayscale center_crop transform_dct rotate imshow pad five_crop resized_crop normalize to_tensor _is_tensor_image adjust_gamma ten_crop adjust_saturation _is_numpy_image upscale crop perspective gaussian_noise affine6 to_cv_image affine poisson_noise adjust_hue adjust_brightness vflip adjust_contrast CenterCrop RandomRotation ToTensor RandomApply TransformUpscaledDCT RandomCrop RandomChoice RandomAffine RandomSPNoise RandomTransforms ToCVImage ToTensorDCT TenCrop Average AverageYUV AdjustDCT RandomPoissonNoise Resize RandomResizedCrop RandomHorizontalFlip FiveCrop RandomGrayscale Pad RandomPerspective NormalizeDCT Lambda Compose RandomVerticalFlip Normalize SubsetDCT adjust_size Upscale Grayscale RandomAffine6 Aggregate DCTCenterCrop RandomGaussianNoise LinearTransformation RandomOrder ColorJitter valloader_upscaled_static is_image_file make_dataset ImageFolderDCT accimage_loader default_loader has_file_allowed_extension DatasetFolderDCT adjust_size opencv_loader pil_loader StandardTransform VisionDataset main validate main str2bool test xavier_init constant_init uniform_init get_upsample_filter normal_init kaiming_init caffe2_xavier_init conv_1x1_bn conv_3x3_bn MobileNetV2DCT_Deconv_Subset mobilenetv2dct_deconv_subset MobileNetV2DCT_Subset_woinp_from_scratch mobilenetv2dct MobileNetV2 MobileNetV2DCT_Subpixel MobileNetV2DCT_Subset_woinp mobilenetv2 MobileNetV2DCT MobileNetV2DCT_Upscaled mobilenetv2dct_subset_woinp_from_scratch mobilenetv2dct_subset_woinp _make_divisible MobileNetV2DCT_Subpixel_Subset mobilenetv2dct_subpixel mobilenetv2dct_subpixel_subset InvertedResidual mobilenetv2dct_upscaled_subset mobilenetv2dct_upscaled MobileNetV2DCT_Upscaled_Subset conv1x1 resnext50_32x4d ResNet resnet50 ResNet50DCT resnext101_32x8d Bottleneck resnet152 ResNetDCT_Upscaled_Static conv3x3 _resnet resnet34 resnet18 main BasicBlock ResNet50DCT_Upscaled resnet101 accuracy weights_init_orthogonal weights_init_normal weights_init_xavier weights_init weights_init_kaiming plot_overlap savefig Logger LoggerMonitor get_mean_and_std_yuv AverageMeter init_params get_mean_and_std_dct yuv_loader mkdir_p get_mean_and_std_dct_resized make_image show_mask_single show_mask gauss colorize show_batch sleep FillingSquaresBar FillingCirclesBar IncrementalBar ChargingBar ShadyBar PixelBar Bar Countdown Stack Counter Pie SigIntMixin WriteMixin WritelnMixin PieSpinner MoonSpinner Spinner PixelSpinner LineSpinner Progress Infinite make_cuda_ext write_version_py readme get_requirements get_version get_git_hash get_hash make_cython_ext _init_dist_pytorch _init_dist_slurm init_dist set_random_seed get_root_logger _init_dist_mpi inference_detector show_result_pyplot LoadImage init_detector show_result _dist_train build_optimizer batch_processor _non_dist_train train_detector parse_losses _dist_train build_optimizer batch_processor _non_dist_train train_detector parse_losses AnchorGenerator anchor_target unmap anchor_inside_flags images_to_levels anchor_target_single ga_loc_target ga_shape_target_single calc_region images_to_levels ga_shape_target PointGenerator images_to_levels point_target unmap point_target_single assign_and_sample build_assigner build_sampler bbox_target_single expand_target bbox_target bbox_overlaps delta2bbox roi2bbox bbox_flip distance2bbox bbox2delta bbox_mapping bbox2result bbox_mapping_back bbox2roi ApproxMaxIoUAssigner AssignResult BaseAssigner MaxIoUAssigner PointAssigner BaseSampler CombinedSampler InstanceBalancedPosSampler IoUBalancedNegSampler OHEMSampler PseudoSampler RandomSampler SamplingResult bbox_overlaps get_classes imagenet_vid_classes voc_classes imagenet_det_classes coco_classes cityscapes_classes wider_face_classes coco_eval segm2json proposal2json fast_eval_recall xyxy2xywh results2json det2json CocoDistEvalRecallHook DistEvalmAPHook DistEvalHook CocoDistEvalmAPHook eval_map tpfp_imagenet print_map_summary average_precision get_cls_results tpfp_default plot_iou_recall set_recall_param print_recall_summary _recalls eval_recalls plot_num_recall force_fp32 auto_fp16 Fp16OptimizerHook wrap_fp16_model patch_forward_method patch_norm_fp32 cast_tensor_type mask_target mask_target_single split_combined_polys multiclass_nms merge_aug_scores merge_aug_masks merge_aug_bboxes merge_aug_proposals DistOptimizerHook allreduce_grads _allreduce_coalesced unmap tensor2imgs multi_apply build_dataset _concat_dataset CityscapesDataset CocoDataset CustomDataset RepeatDataset ConcatDataset PhotoMetricDistortion Expand RandomCrop ExtraAugmentation MaskTransform SegMapTransform bbox_flip ImageTransformDCT Numpy2Tensor BboxTransform VOCDataset WIDERFaceDataset XMLDataset build_dataloader GroupSampler DistributedSampler DistributedGroupSampler Compose DefaultFormatBundle Transpose Average ToTensor Collect DynamicInput to_tensor ImageToTensor ToDataContainer NormalizeDCTUpscaledStatic DefaultFormatBundleDCT NormalizeDCT LoadImageFromFile LoadProposals LoadAnnotations MultiScaleFlipAug RandomFlip Pad Corrupt PhotoMetricDistortion MinIoURandomCrop Resize RandomCrop SegResizeFlipPadRescale Normalize Expand ToDCTUpscaledStatic ToDCT build_shared_head build_detector build_loss build build_backbone build_roi_extractor build_head build_neck AnchorHead FCOSHead GARetinaHead GARPNHead FeatureAdaption GuidedAnchorHead RepPointsHead RetinaHead RPNHead SSDHead GateModule GateModule192 GumbleSoftmax HRModule HRNet ResNet BasicBlock make_res_layer Bottleneck BasicBlock make_res_layer Bottleneck ResNetDCT BasicBlock make_res_layer Bottleneck ResNetDCT_Dynamic BasicBlock make_res_layer Bottleneck ResNetUpscaledDynamic BasicBlock make_res_layer Bottleneck ResNetUpscaledStatic ResNeXt make_res_layer Bottleneck SSDVGG L2Norm BBoxHead SharedFCBBoxHead ConvFCBBoxHead DoubleConvFCBBoxHead BasicResBlock BaseDetector CascadeRCNN DoubleHeadRCNN FasterRCNN FastRCNN FCOS GridRCNN HybridTaskCascade MaskRCNN MaskScoringRCNN RepPointsDetector RetinaNet RPN SingleStageDetector MaskTestMixin BBoxTestMixin RPNTestMixin TwoStageDetector Accuracy accuracy BalancedL1Loss balanced_l1_loss binary_cross_entropy mask_cross_entropy _expand_binary_labels CrossEntropyLoss cross_entropy sigmoid_focal_loss py_sigmoid_focal_loss FocalLoss _expand_binary_labels GHMR GHMC bounded_iou_loss BoundedIoULoss iou_loss IoULoss MSELoss smooth_l1_loss SmoothL1Loss weight_reduce_loss weighted_loss reduce_loss FCNMaskHead FusedSemanticHead GridHead HTCMaskHead MaskIoUHead BFP FPN HRFPN GeneralizedAttention NonLocal2D SingleRoIExtractor ResLayer ConvModule build_conv_layer conv_ws_2d ConvWS2d build_norm_layer Scale xavier_init bias_init_with_prob uniform_init normal_init kaiming_init last_zero_init ContextBlock DeformConvFunction ModulatedDeformConv DeformConvPack ModulatedDeformConvPack DeformConv ModulatedDeformConvFunction DeformRoIPoolingPack DeformRoIPoolingFunction ModulatedDeformRoIPoolingPack DeformRoIPooling MaskedConv2dFunction MaskedConv2d nms soft_nms RoIAlign RoIAlignFunction RoIPool RoIPoolFunction SigmoidFocalLoss SigmoidFocalLossFunction draw_from_npy zigZag draw_inputgate add_flops_counting_methods add_flops_counter_hook_function bn_flops_counter_hook reset_flops_count deconv_flops_counter_hook relu_flops_counter_hook get_model_parameters_number add_flops_mask flops_to_string params_to_string remove_flops_mask remove_batch_counter_hook_function start_flops_count add_batch_counter_variables_or_reset pool_flops_counter_hook empty_flops_counter_hook add_flops_mask_variable_or_reset add_batch_counter_hook_function get_model_complexity_info conv_flops_counter_hook remove_flops_counter_hook_function batch_counter_hook add_flops_counter_variable_or_reset is_supported_instance stop_flops_count upsample_flops_counter_hook linear_flops_counter_hook compute_average_flops_cost print_model_with_flops unblockshaped plot_dct dct_flatten_2d build_from_cfg Registry test_params_to_string multi_gpu_test single_gpu_test collect_results main parse_args encode loads ascontiguousarray float shape show subplot set_title transpose axis zip enumerate len _is_tensor_image COLOR_GRAY2RGB _is_numpy_image transpose from_numpy cvtColor byte isinstance FloatTensor squeeze transpose numpy is_tensor _is_tensor_image _is_numpy_image zip div_ shape int isinstance Number copyMakeBorder isinstance int Number isinstance shape round crop resize Number isinstance center_crop shape crop Number isinstance hflip five_crop vflip clip astype float32 astype float32 mean round clip COLOR_GRAY2RGB COLOR_RGB2GRAY astype float32 clip cvtColor uint8 astype COLOR_RGB2HSV_FULL COLOR_HSV2RGB_FULL cvtColor power clip astype float32 COLOR_GRAY2RGB COLOR_RGB2GRAY cvtColor dtype warpAffine int min ceil getRotationMatrix2D shape floor append abs max warpAffine radians cos shape sin array warpAffine radians cos shape sin array dtype radians tan getPerspectiveTransform cos float32 dot shape sqrt sin zeros warpPerspective array range dtype clip astype float32 dtype astype float32 log2 unique ceil float clip poisson len dtype rand copy salt_and_pepper data join Compose DataLoader ImageFolderDCT join sorted is_valid_file append expanduser keys walk str COLOR_BGR2RGB COLOR_BGR2YCrCb imread cvtColor validate warn gpu_id pretrained DistributedDataParallel DataParallel arch features cuda seed load_state_dict dirname valloader_upscaled_static format init_process_group distributed resume mkdir_p startswith manual_seed checkpoint load evaluate print isfile eval AverageMeter Bar ResNetDCT_Upscaled_Static sum test eval AverageMeter Bar weight constant_ bias bias xavier_uniform_ xavier_normal_ weight constant_ normal_ weight constant_ bias uniform_ weight constant_ bias kaiming_uniform_ bias weight kaiming_normal_ constant_ kaiming_init abs int max load load_state_dict MobileNetV2 MobileNetV2DCT MobileNetV2DCT_Deconv_Subset MobileNetV2DCT_Upscaled MobileNetV2DCT_Upscaled_Subset MobileNetV2DCT_Subpixel MobileNetV2DCT_Subpixel_Subset MobileNetV2DCT_Subset_woinp MobileNetV2DCT_Subset_woinp_from_scratch ResNet load_state_dict load_state_dict_from_url _resnet SE_ResNet50DCT resnet50 ResNet50DCT model_seresnet50dct shape float model_resnet50dct topk size t eq mul_ expand_as append sum max uniform_ data __name__ constant_ data xavier_normal uniform_ __name__ constant_ data uniform_ __name__ constant_ kaiming_normal data print orthogonal uniform_ __name__ constant_ print apply asarray arange plot numbers enumerate len format print Compose ImageFolderDCT DataLoader div_ enumerate len time format print Compose ImageFolderDCT DataLoader iter div_ next range enumerate len str imread cvtColor COLOR_BGR2YCrCb print Compose DataLoader ImageFolder div_ zeros enumerate normal constant isinstance kaiming_normal Conv2d bias modules BatchNorm2d weight Linear makedirs numpy range zeros unsqueeze gauss show make_image imshow make_grid make_image subplot make_grid size clone axis upsampling imshow expand_as range make_image subplot make_grid size clone axis upsampling imshow expand_as cpu range len decode _minimal_ext_cmd exists get_hash cythonize Extension format realpath dirname _init_dist_mpi set_start_method _init_dist_slurm _init_dist_pytorch int set_device init_process_group device_count int str format init_process_group set_device device_count getoutput seed manual_seed_all manual_seed basicConfig setLevel get_dist_info getLogger get_classes isinstance model load_checkpoint warn eval build_detector fromfile to Compose cfg dict test_pipeline device bool concat_list isinstance concatenate imshow_det_bboxes astype copy vstack randint imread bgr2rgb imshow show_result figure items list isinstance OrderedDict mean item Tensor sum dict parse_losses model log_level _non_dist_train get_root_logger _dist_train pop get hasattr endswith search copy named_parameters getattr append optim module workflow log_level MMDistributedDataParallel DistSamplerSeedHook cuda run total_epochs issubclass build_optimizer checkpoint_config work_dir module get val CocoDistEvalRecallHook load_from resume_from register_training_hooks resume type optimizer DistOptimizerHook lr_config DistEvalmAPHook isinstance CocoDataset load_checkpoint register_hook CocoDistEvalmAPHook Runner log_config Fp16OptimizerHook workflow log_level cuda run total_epochs build_optimizer checkpoint_config work_dir optimizer_config get load_from resume_from register_training_hooks resume optimizer lr_config load_checkpoint Runner log_config Fp16OptimizerHook multi_apply images_to_levels any sum range cat len append stack squeeze assign_and_sample zeros_like PseudoSampler pos_gt_bboxes size pos_weight anchor_inside_flags unmap sample new_zeros build_assigner assign pos_inds bbox2delta allowed_border neg_inds pos_bboxes assigner uint8 type new_full clamp long new_full zeros_like calc_region size sqrt log2 floor full_like item append zeros float sum long range len multi_apply images_to_levels any append sum range cat len ga_assigner build_sampler ga_sampler PseudoSampler zeros_like reshape pos_gt_bboxes size unmap build_assigner assign pos_inds sample neg_inds pos_bboxes multi_apply images_to_levels any sum range cat len assign_and_sample zeros_like PseudoSampler pos_gt_bboxes size pos_weight unmap new_zeros build_assigner assign pos_inds sample neg_inds assigner BaseAssigner isinstance BaseSampler isinstance build_sampler sampler build_assigner assign sample assigner multi_apply cat bbox2delta size new_zeros squeeze new_zeros clamp size min max stack unsqueeze div_ float log exp clamp size repeat expand_as view_as abs log addcmul Tensor ndarray isinstance clone bbox_flip new_full new_zeros append cat enumerate cpu append unique numpy clamp minimum T astype maximum float32 zeros range items list eval is_str list format isinstance COCOeval print evaluate summarize is_str COCO accumulate getImgIds loadRes fast_eval_recall array enumerate load getAnnIds is_str mean getImgIds eval_recalls append zeros loadAnns array range len tolist dict append float xyxy2xywh range len dict append float xyxy2xywh range len decode isinstance dict append float xyxy2xywh range len dump format ndarray isinstance segm2json dict proposal2json det2json arange ones hstack maximum zeros sum range minimum zeros_like len argsort zeros bbox_overlaps range enumerate zeros_like len argsort bbox_overlaps zeros argmax max enumerate append zeros range len eps cumsum tuple maximum average_precision argsort enumerate mean any vstack print_map_summary item zip append zeros range get_cls_results len get_classes table print len is_str AsciiTable append zeros range enumerate sum sort hstack copy zeros float argmax fliplr range enumerate array isinstance min set_recall_param print_recall_summary _recalls array append zeros bbox_overlaps range len arange table insert print size tolist AsciiTable append array enumerate show ndarray plot isinstance xlabel tolist axis ylabel figure show ndarray plot isinstance xlabel tolist axis ylabel figure hasattr patch_norm_fp32 modules half children isinstance half patch_forward_method float forward ndarray isinstance Iterable Tensor Mapping list map cat mask_size imresize size astype maximum new_zeros int32 device append to numpy range _pair tolist append slice_list range len pop new_full sort copy nms_op new_zeros getattr append range cat nms nms_thr sort min clone max_num zip append bbox_mapping_back cat append mean bbox_mapping_back zip Tensor isinstance average mean array list _take_tensors _flatten_dense_tensors zip _unflatten_dense_tensors OrderedDict all_reduce copy_ div_ append type values all_reduce _allreduce_coalesced get_world_size div_ uint8 transpose size astype ascontiguousarray append array range list map get deepcopy isinstance append build_dataset range len isinstance ConcatDataset _concat_dataset build_from_cfg RepeatDataset copy get get_dist_info DistributedSampler DataLoader DistributedGroupSampler Tensor ndarray isinstance isinstance block Sequential build_conv_layer append range expansion isinstance log abs e where float weight_reduce_loss new_full size squeeze expand size weight_reduce_loss binary_cross_entropy_with_logits _expand_binary_labels float squeeze arange type_as sigmoid pow weight_reduce_loss binary_cross_entropy_with_logits _sigmoid_focal_loss weight_reduce_loss view clamp view zeros_like size min where abs max abs where get_enum sum reduce_loss dict conv_layer pop copy size view pop str setdefault norm_layer copy parameters _specify_ddp_gpu_num hasattr hasattr hasattr hasattr float Sequential isinstance constant_init ndarray isinstance new_zeros Tensor to numpy is_cuda ndarray soft_nms_cpu isinstance Tensor numpy get_ticklabels set_tick_params concatenate squeeze set_xlabel average set_visible set_ylabel savefig save barplot get_xticks enumerate append range insert load subplot list arange print reshape savefig figure heatmap flops_model get_model_parameters_number input_constructor stop_flops_count add_flops_counting_methods start_flops_count compute_average_flops_cost new_empty print_model_with_flops print compute_average_flops_cost apply sum __get__ reset_flops_count apply __batch_counter__ is_supported_instance modules add_batch_counter_hook_function apply remove_batch_counter_hook_function apply add_batch_counter_variables_or_reset apply apply apply isinstance numel shape affine prod groups kernel_size out_channels in_channels list kernel_size out_channels groups in_channels expand sum prod print len register_forward_hook hasattr remove hasattr is_supported_instance register_forward_hook is_supported_instance isinstance hasattr remove is_supported_instance hasattr is_supported_instance shape int unblockshaped astype shape sqrt imshow title savefig figure dct_flatten_2d pop get list items setdefault copy is_str isclass params_to_string assert_equal update show_result size ProgressBar eval append dataset range enumerate len update get_dist_info size collect_results ProgressBar eval append dataset range enumerate len rstrip tensor broadcast list get_dist_info mkdtemp encode append range dump format bytearray zip load join barrier extend rmtree mkdir_or_exist full str add_argument ArgumentParser local_rank config model tmpdir coco_eval launcher MMDistributedDataParallel show get_dist_info build_detector fromfile parse_args build_dataset get dump CLASSES init_dist single_gpu_test build_dataloader wrap_fp16_model json_out eval results2json join load_checkpoint coco multi_gpu_test out MMDataParallel | # Learning in the Frequency Domain ## Highlights * We propose a method of learning in the frequency domain (using DCT coefficients as input), which requires little modification to the existing CNN models that take RGB input. * We show that learning in the frequency domain better preserves image information in the pre-processing stage than the conventional spatial downsampling approach. * We propose a learning-based dynamic channel selection method to identify the trivial frequency components for static removal during inference. Experiment results on ResNet-50 show that one can prune up to $87.5\%$ of the frequency channels using the proposed channel selection method with no or little accuracy degradation in the ImageNet classification task. * To the best of our knowledge, this is the first work that explores learning in the frequency domain for high-level vision tasks, such as object detection and instance segmentation. Please refer to the [image classfication](classification) and [instance segmentation](segmentation) sections for more details. If you use our code/models in your research, please cite our paper: ``` @InProceedings{Xu_2020_CVPR, | 1,636 |
calmevtime1990/supp | ['instance segmentation', 'semantic segmentation'] | ['Learning in the Frequency Domain'] | segmentation/mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py segmentation/mmdet/models/detectors/__init__.py segmentation/mmdet/core/utils/misc.py segmentation/mmdet/datasets/registry.py segmentation/mmdet/datasets/custom.py segmentation/mmdet/models/backbones/resnetDCT.py segmentation/mmdet/core/anchor/point_generator.py segmentation/mmdet/models/roi_extractors/single_level.py segmentation/mmdet/models/mask_heads/maskiou_head.py segmentation/mmdet/models/detectors/single_stage.py classification/utils/progress/progress/helpers.py segmentation/mmdet/models/detectors/htc.py segmentation/mmdet/models/anchor_heads/reppoints_head.py segmentation/mmdet/models/detectors/test_mixins.py segmentation/mmdet/models/anchor_heads/retina_head.py segmentation/mmdet/models/roi_extractors/__init__.py segmentation/mmdet/datasets/pipelines/test_aug.py segmentation/mmdet/models/utils/conv_ws.py segmentation/mmdet/models/losses/balanced_l1_loss.py segmentation/mmdet/models/detectors/base.py segmentation/mmdet/ops/dcn/deform_conv.py segmentation/mmdet/core/post_processing/__init__.py segmentation/mmdet/models/anchor_heads/fcos_head.py segmentation/mmdet/models/backbones/gate.py segmentation/mmdet/datasets/loader/sampler.py segmentation/mmdet/models/anchor_heads/ssd_head.py segmentation/mmdet/apis/env.py segmentation/mmdet/models/losses/accuracy.py segmentation/mmdet/models/bbox_heads/__init__.py segmentation/mmdet/apis/__init__.py classification/datasets/cvfunctional.py segmentation/mmdet/core/evaluation/eval_hooks.py segmentation/mmdet/models/detectors/fast_rcnn.py classification/utils/progress/progress/bar.py segmentation/mmdet/apis/train.py segmentation/mmdet/models/mask_heads/fcn_mask_head.py segmentation/mmdet/ops/__init__.py segmentation/mmdet/apis/inference.py segmentation/tools/test.py segmentation/mmdet/datasets/builder.py segmentation/mmdet/models/__init__.py segmentation/mmdet/models/anchor_heads/guided_anchor_head.py segmentation/mmdet/models/detectors/rpn.py segmentation/mmdet/core/utils/__init__.py segmentation/mmdet/models/shared_heads/__init__.py segmentation/mmdet/models/detectors/cascade_rcnn.py segmentation/mmdet/models/losses/mse_loss.py segmentation/mmdet/core/post_processing/merge_augs.py segmentation/mmdet/utils/transfer_model.py segmentation/mmdet/models/detectors/mask_scoring_rcnn.py segmentation/mmdet/core/bbox/transforms.py segmentation/mmdet/models/backbones/__init__.py segmentation/mmdet/utils/__init__.py classification/main/imagenet_resnet_upscaled_static.py segmentation/mmdet/core/evaluation/class_names.py segmentation/mmdet/core/fp16/decorators.py segmentation/mmdet/datasets/xml_style.py segmentation/mmdet/datasets/pipelines/formating.py segmentation/mmdet/models/losses/iou_loss.py segmentation/mmdet/core/__init__.py segmentation/mmdet/models/utils/scale.py classification/datasets/cvtransforms.py segmentation/mmdet/core/anchor/anchor_target.py segmentation/mmdet/models/detectors/double_head_rcnn.py segmentation/mmdet/datasets/coco.py segmentation/setup.py segmentation/mmdet/core/bbox/assigners/base_assigner.py classification/datasets/vision.py segmentation/mmdet/models/losses/utils.py classification/utils/visualize.py segmentation/mmdet/core/bbox/samplers/instance_balanced_pos_sampler.py segmentation/mmdet/models/utils/__init__.py segmentation/mmdet/datasets/loader/__init__.py classification/models/imagenet/resnet.py segmentation/mmdet/models/bbox_heads/double_bbox_head.py segmentation/mmdet/datasets/pipelines/dct_channel_index.py segmentation/mmdet/core/post_processing/bbox_nms.py segmentation/mmdet/models/utils/conv_module.py segmentation/mmdet/models/backbones/ssd_vgg.py classification/models/imagenet/mobilenetv2.py segmentation/mmdet/ops/nms/nms_wrapper.py segmentation/mmdet/utils/draw_inputgate.py segmentation/mmdet/models/plugins/non_local.py classification/utils/__init__.py segmentation/mmdet/models/losses/ghm_loss.py segmentation/mmdet/ops/dcn/deform_pool.py segmentation/mmdet/datasets/pipelines/loading.py segmentation/mmdet/core/anchor/anchor_generator.py segmentation/configs/faster_rcnn_r50_fpn_1x_static_24_wofreeze.py classification/datasets/dataset_imagenet_dct.py segmentation/mmdet/core/bbox/samplers/ohem_sampler.py segmentation/mmdet/models/builder.py segmentation/mmdet/ops/roi_align/gradcheck.py classification/utils/progress/setup.py segmentation/mmdet/ops/masked_conv/__init__.py segmentation/mmdet/models/utils/norm.py segmentation/tests/test_utils.py segmentation/mmdet/models/plugins/generalized_attention.py segmentation/mmdet/models/backbones/resnetDCT_dynamic.py segmentation/mmdet/core/anchor/__init__.py segmentation/mmdet/models/losses/focal_loss.py segmentation/mmdet/models/detectors/mask_rcnn.py segmentation/mmdet/core/bbox/samplers/random_sampler.py segmentation/mmdet/models/bbox_heads/convfc_bbox_head.py segmentation/mmdet/models/mask_heads/fused_semantic_head.py segmentation/mmdet/models/necks/bfp.py segmentation/mmdet/models/utils/weight_init.py segmentation/mmdet/core/mask/__init__.py segmentation/mmdet/core/bbox/assigners/assign_result.py segmentation/mmdet/datasets/dataset_wrappers.py segmentation/mmdet/core/evaluation/recall.py segmentation/configs/mask_rcnn_r50_rpn_1x_DCT_static_64_wofreeze.py segmentation/mmdet/models/necks/__init__.py segmentation/mmdet/models/detectors/reppoints_detector.py segmentation/mmdet/models/losses/smooth_l1_loss.py segmentation/mmdet/core/evaluation/mean_ap.py segmentation/mmdet/ops/nms/__init__.py segmentation/configs/mask_rcnn_r50_rpn_1x_DCT_static_24_wofreeze.py classification/main/imagenet_mobilenetv2_upscaled_static.py segmentation/mmdet/datasets/transforms.py segmentation/mmdet/datasets/pipelines/formatingDCT.py segmentation/mmdet/core/bbox/bbox_target.py segmentation/mmdet/models/detectors/grid_rcnn.py classification/models/imagenet/__init__.py classification/utils/logger.py segmentation/mmdet/datasets/extra_aug.py segmentation/mmdet/datasets/pipelines/transformsDCT.py segmentation/mmdet/models/plugins/__init__.py classification/utils/eval.py segmentation/mmdet/core/bbox/samplers/iou_balanced_neg_sampler.py segmentation/mmdet/utils/plot_dct.py segmentation/mmdet/models/mask_heads/htc_mask_head.py segmentation/mmdet/ops/sigmoid_focal_loss/__init__.py segmentation/configs/mean_std.py segmentation/mmdet/models/backbones/hrnet.py segmentation/mmdet/core/evaluation/coco_utils.py segmentation/mmdet/models/detectors/faster_rcnn.py classification/utils/misc.py segmentation/mmdet/utils/registry.py segmentation/mmdet/core/anchor/point_target.py classification/utils/init_weights.py segmentation/mmdet/datasets/wider_face.py segmentation/mmdet/core/bbox/assigners/approx_max_iou_assigner.py classification/datasets/dataloader_imagenet_dct.py segmentation/mmdet/models/detectors/two_stage.py segmentation/mmdet/models/backbones/resnet_dynamic.py segmentation/mmdet/models/anchor_heads/anchor_head.py segmentation/mmdet/models/mask_heads/grid_head.py segmentation/mmdet/models/necks/fpn.py segmentation/mmdet/ops/roi_align/__init__.py segmentation/mmdet/core/evaluation/__init__.py segmentation/mmdet/core/bbox/samplers/pseudo_sampler.py segmentation/mmdet/core/bbox/samplers/__init__.py segmentation/mmdet/core/evaluation/bbox_overlaps.py segmentation/mmdet/models/backbones/resnet_static.py classification/datasets/__init__.py classification/utils/progress/test_progress.py segmentation/mmdet/core/utils/dist_utils.py segmentation/mmdet/ops/roi_align/roi_align.py segmentation/mmdet/models/detectors/fcos.py segmentation/mmdet/datasets/__init__.py segmentation/mmdet/datasets/pipelines/compose.py segmentation/mmdet/core/bbox/assign_sampling.py classification/utils/progress/progress/__init__.py segmentation/mmdet/core/fp16/utils.py segmentation/mmdet/apis/mean_std_cal.py segmentation/mmdet/core/mask/mask_target.py segmentation/mmdet/models/losses/__init__.py segmentation/mmdet/models/registry.py classification/utils/progress/progress/spinner.py segmentation/configs/faster_rcnn_r50_fpn_1x_static_64_wofreeze.py segmentation/mmdet/datasets/loader/build_loader.py segmentation/mmdet/core/bbox/geometry.py segmentation/mmdet/datasets/cityscapes.py segmentation/mmdet/models/anchor_heads/__init__.py segmentation/mmdet/models/detectors/retinanet.py segmentation/mmdet/core/anchor/guided_anchor_target.py segmentation/mmdet/core/bbox/samplers/sampling_result.py segmentation/mmdet/datasets/voc.py segmentation/mmdet/__init__.py segmentation/mmdet/models/anchor_heads/ga_retina_head.py segmentation/mmdet/ops/roi_pool/__init__.py classification/utils/progress/progress/counter.py segmentation/mmdet/core/mask/utils.py segmentation/mmdet/models/backbones/resnet.py segmentation/mmdet/models/bbox_heads/bbox_head.py segmentation/mmdet/models/backbones/gumbel.py segmentation/mmdet/ops/dcn/__init__.py segmentation/mmdet/core/bbox/samplers/combined_sampler.py segmentation/mmdet/models/shared_heads/res_layer.py segmentation/mmdet/core/bbox/assigners/point_assigner.py segmentation/mmdet/models/backbones/resnext.py segmentation/mmdet/ops/roi_pool/gradcheck.py segmentation/mmdet/ops/masked_conv/masked_conv.py segmentation/mmdet/models/anchor_heads/rpn_head.py segmentation/mmdet/core/bbox/assigners/__init__.py segmentation/mmdet/ops/roi_pool/roi_pool.py segmentation/mmdet/models/mask_heads/__init__.py segmentation/mmdet/core/fp16/__init__.py segmentation/mmdet/models/necks/hrfpn.py segmentation/mmdet/utils/flops_counter.py segmentation/mmdet/core/bbox/__init__.py segmentation/mmdet/core/bbox/samplers/base_sampler.py segmentation/mmdet/datasets/pipelines/transforms.py segmentation/mmdet/models/anchor_heads/ga_rpn_head.py segmentation/mmdet/models/losses/cross_entropy_loss.py segmentation/mmdet/datasets/pipelines/__init__.py segmentation/mmdet/ops/context_block.py segmentation/mmdet/core/fp16/hooks.py classification/models/utils.py classification/main/__init__.py segmentation/mmdet/core/bbox/assigners/max_iou_assigner.py hflip salt_and_pepper resize to_rgb_bgr to_tensor_dct cv_transform pil_transform to_grayscale center_crop transform_dct rotate imshow pad five_crop resized_crop normalize to_tensor _is_tensor_image adjust_gamma ten_crop adjust_saturation _is_numpy_image upscale crop perspective gaussian_noise affine6 to_cv_image affine poisson_noise adjust_hue adjust_brightness vflip adjust_contrast CenterCrop RandomRotation ToTensor RandomApply TransformUpscaledDCT RandomCrop RandomChoice RandomAffine RandomSPNoise RandomTransforms ToCVImage ToTensorDCT TenCrop Average AverageYUV AdjustDCT RandomPoissonNoise Resize RandomResizedCrop RandomHorizontalFlip FiveCrop RandomGrayscale Pad RandomPerspective NormalizeDCT Lambda Compose RandomVerticalFlip Normalize SubsetDCT adjust_size Upscale Grayscale RandomAffine6 Aggregate DCTCenterCrop RandomGaussianNoise LinearTransformation RandomOrder ColorJitter valloader_upscaled_static is_image_file make_dataset ImageFolderDCT accimage_loader default_loader has_file_allowed_extension DatasetFolderDCT adjust_size opencv_loader pil_loader StandardTransform VisionDataset main validate main str2bool test xavier_init constant_init uniform_init get_upsample_filter normal_init kaiming_init caffe2_xavier_init conv_1x1_bn conv_3x3_bn MobileNetV2DCT_Deconv_Subset mobilenetv2dct_deconv_subset MobileNetV2DCT_Subset_woinp_from_scratch mobilenetv2dct MobileNetV2 MobileNetV2DCT_Subpixel MobileNetV2DCT_Subset_woinp mobilenetv2 MobileNetV2DCT MobileNetV2DCT_Upscaled mobilenetv2dct_subset_woinp_from_scratch mobilenetv2dct_subset_woinp _make_divisible MobileNetV2DCT_Subpixel_Subset mobilenetv2dct_subpixel mobilenetv2dct_subpixel_subset InvertedResidual mobilenetv2dct_upscaled_subset mobilenetv2dct_upscaled MobileNetV2DCT_Upscaled_Subset conv1x1 resnext50_32x4d ResNet resnet50 ResNet50DCT resnext101_32x8d Bottleneck resnet152 ResNetDCT_Upscaled_Static conv3x3 _resnet resnet34 resnet18 main BasicBlock ResNet50DCT_Upscaled resnet101 accuracy weights_init_orthogonal weights_init_normal weights_init_xavier weights_init weights_init_kaiming plot_overlap savefig Logger LoggerMonitor get_mean_and_std_yuv AverageMeter init_params get_mean_and_std_dct yuv_loader mkdir_p get_mean_and_std_dct_resized make_image show_mask_single show_mask gauss colorize show_batch sleep FillingSquaresBar FillingCirclesBar IncrementalBar ChargingBar ShadyBar PixelBar Bar Countdown Stack Counter Pie SigIntMixin WriteMixin WritelnMixin PieSpinner MoonSpinner Spinner PixelSpinner LineSpinner Progress Infinite make_cuda_ext write_version_py readme get_requirements get_version get_git_hash get_hash make_cython_ext _init_dist_pytorch _init_dist_slurm init_dist set_random_seed get_root_logger _init_dist_mpi inference_detector show_result_pyplot LoadImage init_detector show_result _dist_train build_optimizer batch_processor _non_dist_train train_detector parse_losses _dist_train build_optimizer batch_processor _non_dist_train train_detector parse_losses AnchorGenerator anchor_target unmap anchor_inside_flags images_to_levels anchor_target_single ga_loc_target ga_shape_target_single calc_region images_to_levels ga_shape_target PointGenerator images_to_levels point_target unmap point_target_single assign_and_sample build_assigner build_sampler bbox_target_single expand_target bbox_target bbox_overlaps delta2bbox roi2bbox bbox_flip distance2bbox bbox2delta bbox_mapping bbox2result bbox_mapping_back bbox2roi ApproxMaxIoUAssigner AssignResult BaseAssigner MaxIoUAssigner PointAssigner BaseSampler CombinedSampler InstanceBalancedPosSampler IoUBalancedNegSampler OHEMSampler PseudoSampler RandomSampler SamplingResult bbox_overlaps get_classes imagenet_vid_classes voc_classes imagenet_det_classes coco_classes cityscapes_classes wider_face_classes coco_eval segm2json proposal2json fast_eval_recall xyxy2xywh results2json det2json CocoDistEvalRecallHook DistEvalmAPHook DistEvalHook CocoDistEvalmAPHook eval_map tpfp_imagenet print_map_summary average_precision get_cls_results tpfp_default plot_iou_recall set_recall_param print_recall_summary _recalls eval_recalls plot_num_recall force_fp32 auto_fp16 Fp16OptimizerHook wrap_fp16_model patch_forward_method patch_norm_fp32 cast_tensor_type mask_target mask_target_single split_combined_polys multiclass_nms merge_aug_scores merge_aug_masks merge_aug_bboxes merge_aug_proposals DistOptimizerHook allreduce_grads _allreduce_coalesced unmap tensor2imgs multi_apply build_dataset _concat_dataset CityscapesDataset CocoDataset CustomDataset RepeatDataset ConcatDataset PhotoMetricDistortion Expand RandomCrop ExtraAugmentation MaskTransform SegMapTransform bbox_flip ImageTransformDCT Numpy2Tensor BboxTransform VOCDataset WIDERFaceDataset XMLDataset build_dataloader GroupSampler DistributedSampler DistributedGroupSampler Compose DefaultFormatBundle Transpose Average ToTensor Collect DynamicInput to_tensor ImageToTensor ToDataContainer NormalizeDCTUpscaledStatic DefaultFormatBundleDCT NormalizeDCT LoadImageFromFile LoadProposals LoadAnnotations MultiScaleFlipAug RandomFlip Pad Corrupt PhotoMetricDistortion MinIoURandomCrop Resize RandomCrop SegResizeFlipPadRescale Normalize Expand ToDCTUpscaledStatic ToDCT build_shared_head build_detector build_loss build build_backbone build_roi_extractor build_head build_neck AnchorHead FCOSHead GARetinaHead GARPNHead FeatureAdaption GuidedAnchorHead RepPointsHead RetinaHead RPNHead SSDHead GateModule GateModule192 GumbleSoftmax HRModule HRNet ResNet BasicBlock make_res_layer Bottleneck BasicBlock make_res_layer Bottleneck ResNetDCT BasicBlock make_res_layer Bottleneck ResNetDCT_Dynamic BasicBlock make_res_layer Bottleneck ResNetUpscaledDynamic BasicBlock make_res_layer Bottleneck ResNetUpscaledStatic ResNeXt make_res_layer Bottleneck SSDVGG L2Norm BBoxHead SharedFCBBoxHead ConvFCBBoxHead DoubleConvFCBBoxHead BasicResBlock BaseDetector CascadeRCNN DoubleHeadRCNN FasterRCNN FastRCNN FCOS GridRCNN HybridTaskCascade MaskRCNN MaskScoringRCNN RepPointsDetector RetinaNet RPN SingleStageDetector MaskTestMixin BBoxTestMixin RPNTestMixin TwoStageDetector Accuracy accuracy BalancedL1Loss balanced_l1_loss binary_cross_entropy mask_cross_entropy _expand_binary_labels CrossEntropyLoss cross_entropy sigmoid_focal_loss py_sigmoid_focal_loss FocalLoss _expand_binary_labels GHMR GHMC bounded_iou_loss BoundedIoULoss iou_loss IoULoss MSELoss smooth_l1_loss SmoothL1Loss weight_reduce_loss weighted_loss reduce_loss FCNMaskHead FusedSemanticHead GridHead HTCMaskHead MaskIoUHead BFP FPN HRFPN GeneralizedAttention NonLocal2D SingleRoIExtractor ResLayer ConvModule build_conv_layer conv_ws_2d ConvWS2d build_norm_layer Scale xavier_init bias_init_with_prob uniform_init normal_init kaiming_init last_zero_init ContextBlock DeformConvFunction ModulatedDeformConv DeformConvPack ModulatedDeformConvPack DeformConv ModulatedDeformConvFunction DeformRoIPoolingPack DeformRoIPoolingFunction ModulatedDeformRoIPoolingPack DeformRoIPooling MaskedConv2dFunction MaskedConv2d nms soft_nms RoIAlign RoIAlignFunction RoIPool RoIPoolFunction SigmoidFocalLoss SigmoidFocalLossFunction draw_from_npy zigZag draw_inputgate add_flops_counting_methods add_flops_counter_hook_function bn_flops_counter_hook reset_flops_count deconv_flops_counter_hook relu_flops_counter_hook get_model_parameters_number add_flops_mask flops_to_string params_to_string remove_flops_mask remove_batch_counter_hook_function start_flops_count add_batch_counter_variables_or_reset pool_flops_counter_hook empty_flops_counter_hook add_flops_mask_variable_or_reset add_batch_counter_hook_function get_model_complexity_info conv_flops_counter_hook remove_flops_counter_hook_function batch_counter_hook add_flops_counter_variable_or_reset is_supported_instance stop_flops_count upsample_flops_counter_hook linear_flops_counter_hook compute_average_flops_cost print_model_with_flops unblockshaped plot_dct dct_flatten_2d build_from_cfg Registry test_params_to_string multi_gpu_test single_gpu_test collect_results main parse_args encode loads ascontiguousarray float shape show subplot set_title transpose axis zip enumerate len _is_tensor_image COLOR_GRAY2RGB _is_numpy_image transpose from_numpy cvtColor byte isinstance FloatTensor squeeze transpose numpy is_tensor _is_tensor_image _is_numpy_image zip div_ shape int isinstance Number copyMakeBorder isinstance int Number isinstance shape round crop resize Number isinstance center_crop shape crop Number isinstance hflip five_crop vflip clip astype float32 astype float32 mean round clip COLOR_GRAY2RGB COLOR_RGB2GRAY astype float32 clip cvtColor uint8 astype COLOR_RGB2HSV_FULL COLOR_HSV2RGB_FULL cvtColor power clip astype float32 COLOR_GRAY2RGB COLOR_RGB2GRAY cvtColor dtype warpAffine int min ceil getRotationMatrix2D shape floor append abs max warpAffine radians cos shape sin array warpAffine radians cos shape sin array dtype radians tan getPerspectiveTransform cos float32 dot shape sqrt sin zeros warpPerspective array range dtype clip astype float32 dtype astype float32 log2 unique ceil float clip poisson len dtype rand copy salt_and_pepper data join Compose DataLoader ImageFolderDCT join sorted is_valid_file append expanduser keys walk str COLOR_BGR2RGB COLOR_BGR2YCrCb imread cvtColor validate warn gpu_id pretrained DistributedDataParallel DataParallel arch features cuda seed load_state_dict dirname valloader_upscaled_static format init_process_group distributed resume mkdir_p startswith manual_seed checkpoint load evaluate print isfile eval AverageMeter Bar ResNetDCT_Upscaled_Static sum test eval AverageMeter Bar weight constant_ bias bias xavier_uniform_ xavier_normal_ weight constant_ normal_ weight constant_ bias uniform_ weight constant_ bias kaiming_uniform_ bias weight kaiming_normal_ constant_ kaiming_init abs int max load load_state_dict MobileNetV2 MobileNetV2DCT MobileNetV2DCT_Deconv_Subset MobileNetV2DCT_Upscaled MobileNetV2DCT_Upscaled_Subset MobileNetV2DCT_Subpixel MobileNetV2DCT_Subpixel_Subset MobileNetV2DCT_Subset_woinp MobileNetV2DCT_Subset_woinp_from_scratch ResNet load_state_dict load_state_dict_from_url _resnet SE_ResNet50DCT resnet50 ResNet50DCT model_seresnet50dct shape float model_resnet50dct topk size t eq mul_ expand_as append sum max uniform_ data __name__ constant_ data xavier_normal uniform_ __name__ constant_ data uniform_ __name__ constant_ kaiming_normal data print orthogonal uniform_ __name__ constant_ print apply asarray arange plot numbers enumerate len format print Compose ImageFolderDCT DataLoader div_ enumerate len time format print Compose ImageFolderDCT DataLoader iter div_ next range enumerate len str imread cvtColor COLOR_BGR2YCrCb print Compose DataLoader ImageFolder div_ zeros enumerate normal constant isinstance kaiming_normal Conv2d bias modules BatchNorm2d weight Linear makedirs numpy range zeros unsqueeze gauss show make_image imshow make_grid make_image subplot make_grid size clone axis upsampling imshow expand_as range make_image subplot make_grid size clone axis upsampling imshow expand_as cpu range len decode _minimal_ext_cmd exists get_hash cythonize Extension format realpath dirname _init_dist_mpi set_start_method _init_dist_slurm _init_dist_pytorch int set_device init_process_group device_count int str format init_process_group set_device device_count getoutput seed manual_seed_all manual_seed basicConfig setLevel get_dist_info getLogger get_classes isinstance model load_checkpoint warn eval build_detector fromfile to Compose cfg dict test_pipeline device bool concat_list isinstance concatenate imshow_det_bboxes astype copy vstack randint imread bgr2rgb imshow show_result figure items list isinstance OrderedDict mean item Tensor sum dict parse_losses model log_level _non_dist_train get_root_logger _dist_train pop get hasattr endswith search copy named_parameters getattr append optim module workflow log_level MMDistributedDataParallel DistSamplerSeedHook cuda run total_epochs issubclass build_optimizer checkpoint_config work_dir module get val CocoDistEvalRecallHook load_from resume_from register_training_hooks resume type optimizer DistOptimizerHook lr_config DistEvalmAPHook isinstance CocoDataset load_checkpoint register_hook CocoDistEvalmAPHook Runner log_config Fp16OptimizerHook workflow log_level cuda run total_epochs build_optimizer checkpoint_config work_dir optimizer_config get load_from resume_from register_training_hooks resume optimizer lr_config load_checkpoint Runner log_config Fp16OptimizerHook multi_apply images_to_levels any sum range cat len append stack squeeze assign_and_sample zeros_like PseudoSampler pos_gt_bboxes size pos_weight anchor_inside_flags unmap sample new_zeros build_assigner assign pos_inds bbox2delta allowed_border neg_inds pos_bboxes assigner uint8 type new_full clamp long new_full zeros_like calc_region size sqrt log2 floor full_like item append zeros float sum long range len multi_apply images_to_levels any append sum range cat len ga_assigner build_sampler ga_sampler PseudoSampler zeros_like reshape pos_gt_bboxes size unmap build_assigner assign pos_inds sample neg_inds pos_bboxes multi_apply images_to_levels any sum range cat len assign_and_sample zeros_like PseudoSampler pos_gt_bboxes size pos_weight unmap new_zeros build_assigner assign pos_inds sample neg_inds assigner BaseAssigner isinstance BaseSampler isinstance build_sampler sampler build_assigner assign sample assigner multi_apply cat bbox2delta size new_zeros squeeze new_zeros clamp size min max stack unsqueeze div_ float log exp clamp size repeat expand_as view_as abs log addcmul Tensor ndarray isinstance clone bbox_flip new_full new_zeros append cat enumerate cpu append unique numpy clamp minimum T astype maximum float32 zeros range items list eval is_str list format isinstance COCOeval print evaluate summarize is_str COCO accumulate getImgIds loadRes fast_eval_recall array enumerate load getAnnIds is_str mean getImgIds eval_recalls append zeros loadAnns array range len tolist dict append float xyxy2xywh range len dict append float xyxy2xywh range len decode isinstance dict append float xyxy2xywh range len dump format ndarray isinstance segm2json dict proposal2json det2json arange ones hstack maximum zeros sum range minimum zeros_like len argsort zeros bbox_overlaps range enumerate zeros_like len argsort bbox_overlaps zeros argmax max enumerate append zeros range len eps cumsum tuple maximum average_precision argsort enumerate mean any vstack print_map_summary item zip append zeros range get_cls_results len get_classes table print len is_str AsciiTable append zeros range enumerate sum sort hstack copy zeros float argmax fliplr range enumerate array isinstance min set_recall_param print_recall_summary _recalls array append zeros bbox_overlaps range len arange table insert print size tolist AsciiTable append array enumerate show ndarray plot isinstance xlabel tolist axis ylabel figure show ndarray plot isinstance xlabel tolist axis ylabel figure hasattr patch_norm_fp32 modules half children isinstance half patch_forward_method float forward ndarray isinstance Iterable Tensor Mapping list map cat mask_size imresize size astype maximum new_zeros int32 device append to numpy range _pair tolist append slice_list range len pop new_full sort copy nms_op new_zeros getattr append range cat nms nms_thr sort min clone max_num zip append bbox_mapping_back cat append mean bbox_mapping_back zip Tensor isinstance average mean array list _take_tensors _flatten_dense_tensors zip _unflatten_dense_tensors OrderedDict all_reduce copy_ div_ append type values all_reduce _allreduce_coalesced get_world_size div_ uint8 transpose size astype ascontiguousarray append array range list map get deepcopy isinstance append build_dataset range len isinstance ConcatDataset _concat_dataset build_from_cfg RepeatDataset copy get get_dist_info DistributedSampler DataLoader DistributedGroupSampler Tensor ndarray isinstance isinstance block Sequential build_conv_layer append range expansion isinstance log abs e where float weight_reduce_loss new_full size squeeze expand size weight_reduce_loss binary_cross_entropy_with_logits _expand_binary_labels float squeeze arange type_as sigmoid pow weight_reduce_loss binary_cross_entropy_with_logits _sigmoid_focal_loss weight_reduce_loss view clamp view zeros_like size min where abs max abs where get_enum sum reduce_loss dict conv_layer pop copy size view pop str setdefault norm_layer copy parameters _specify_ddp_gpu_num hasattr hasattr hasattr hasattr float Sequential isinstance constant_init ndarray isinstance new_zeros Tensor to numpy is_cuda ndarray soft_nms_cpu isinstance Tensor numpy get_ticklabels set_tick_params concatenate squeeze set_xlabel average set_visible set_ylabel savefig save barplot get_xticks enumerate append range insert load subplot list arange print reshape savefig figure heatmap flops_model get_model_parameters_number input_constructor stop_flops_count add_flops_counting_methods start_flops_count compute_average_flops_cost new_empty print_model_with_flops print compute_average_flops_cost apply sum __get__ reset_flops_count apply __batch_counter__ is_supported_instance modules add_batch_counter_hook_function apply remove_batch_counter_hook_function apply add_batch_counter_variables_or_reset apply apply apply isinstance numel shape affine prod groups kernel_size out_channels in_channels list kernel_size out_channels groups in_channels expand sum prod print len register_forward_hook hasattr remove hasattr is_supported_instance register_forward_hook is_supported_instance isinstance hasattr remove is_supported_instance hasattr is_supported_instance shape int unblockshaped astype shape sqrt imshow title savefig figure dct_flatten_2d pop get list items setdefault copy is_str isclass params_to_string assert_equal update show_result size ProgressBar eval append dataset range enumerate len update get_dist_info size collect_results ProgressBar eval append dataset range enumerate len rstrip tensor broadcast list get_dist_info mkdtemp encode append range dump format bytearray zip load join barrier extend rmtree mkdir_or_exist full str add_argument ArgumentParser local_rank config model tmpdir coco_eval launcher MMDistributedDataParallel show get_dist_info build_detector fromfile parse_args build_dataset get dump CLASSES init_dist single_gpu_test build_dataloader wrap_fp16_model json_out eval results2json join load_checkpoint coco multi_gpu_test out MMDataParallel | # Learning in the Frequency Domain ## Highlights * We propose a method of learning in the frequency domain (using DCT coefficients as input), which requires little modification to the existing CNN models that take RGB input. * We show that learning in the frequency domain better preserves image information in the pre-processing stage than the conventional spatial downsampling approach. * We propose a learning-based dynamic channel selection method to identify the trivial frequency components for static removal during inference. Experiment results on ResNet-50 show that one can prune up to $87.5\%$ of the frequency channels using the proposed channel selection method with no or little accuracy degradation in the ImageNet classification task. * To the best of our knowledge, this is the first work that explores learning in the frequency domain for high-level vision tasks, such as object detection and instance segmentation. Please refer to the [image classfication](classification) and [instance segmentation](segmentation) sections for more details. If you use our code/models in your research, please cite our paper: ``` @InProceedings{Xu_2020_CVPR, | 1,637 |
candacelax/bias-in-vision-and-language | ['word embeddings'] | ['Measuring Social Biases in Grounded Vision and Language Embeddings'] | models/vlbert/common/nlp/roberta/modeling_roberta.py models/vlbert/external/pytorch_pretrained_bert/convert_openai_checkpoint_to_pytorch.py models/vlbert/external/pytorch_pretrained_bert/convert_tf_checkpoint_to_pytorch.py dataloaders/file_utils.py dataloaders/__init__.py models/vlbert/common/nlp/bert/optimization.py models/vlbert/common/nlp/roberta/__init__.py models/vilbert/__init__.py models/vlbert/common/utils/pad_sequence.py scripts/weat/weat_images_targ_specific.py models/vlbert/common/trainer.py models/vlbert/external/pytorch_pretrained_bert/optimization_openai.py models/vlbert/external/pytorch_pretrained_bert/modeling_transfo_xl.py models/vlbert/common/metrics/pretrain_metrics.py scripts/weat/weat_images_masked_regions.py models/vlbert/external/pytorch_pretrained_bert/tokenization_gpt2.py dataloaders/lxmert/lxmert_bias_data.py models/vlbert/external/pytorch_pretrained_bert/file_utils.py dataloaders/visualbert/bert_data_utils.py models/vlbert/common/metrics/refcoco_metrics.py dataloaders/lxmert/utils.py models/vlbert/common/utils/mask.py models/vlbert/external/pytorch_pretrained_bert/tokenization_transfo_xl.py scripts/weat/weat_images_intra_targ.py models/vlbert/common/utils/clip_pad.py scripts/utils.py models/vlbert/common/fast_rcnn.py models/vlbert/common/metrics/composite_eval_metric.py models/vilbert/utils.py models/vlbert/common/nlp/time_distributed.py models/vlbert/common/backbone/__init__.py models/vlbert/__init__.py models/vlbert/common/utils/bbox.py dataloaders/bias_dataloader.py models/vlbert/common/nlp/input_variational_dropout.py scripts/__init__.py models/__init__.py scripts/weat/weat_text_only.py models/vlbert/common/metrics/vqa_metrics.py dataloaders/visualbert/box_utils.py dataloaders/vilbert/bias_dataset.py models/vlbert/common/lib/roi_pooling/roi_pool.py models/vlbert/common/lr_scheduler.py models/vlbert/external/pytorch_pretrained_bert/modeling_gpt2.py models/vilbert/vilbert.py models/vlbert/common/callbacks/batch_end_callbacks/speedometer.py main.py models/vlbert/common/nlp/bert_encoder_wrapper.py models/vlbert/common/lib/roi_pooling/debug.py models/vlbert/common/utils/zipreader.py models/vlbert/common/lib/roi_pooling/setup.py scripts/format_shutter.py dataloaders/visualbert/vcr.py dataloaders/vilbert/_image_features_reader.py models/vlbert/external/pytorch_pretrained_bert/tokenization.py models/vlbert/external/pytorch_pretrained_bert/optimization.py models/vlbert/modules/__init__.py models/vlbert/common/utils/multi_task_dataloader.py scripts/weat/weat_images_union.py models/lxmert/modeling_lxmert_bias.py scripts/writer.py scripts/get_relevant_image_features.py models/vlbert/common/module.py dataloaders/visualbert/bert_field.py models/vlbert/common/utils/flatten.py models/vlbert/external/pytorch_pretrained_bert/convert_transfo_xl_checkpoint_to_pytorch.py models/vlbert/config.py models/vlbert/external/pytorch_pretrained_bert/modeling_openai.py models/vlbert/common/callbacks/epoch_end_callbacks/validation_monitor.py dataloaders/vlbert/__init__.py dataloaders/vlbert/bias_dataset.py models/vlbert/common/visual_linguistic_bert.py dataloaders/tokenization.py scripts/bias_test.py models/vlbert/external/pytorch_pretrained_bert/__init__.py models/vlbert/common/utils/misc.py models/vlbert/common/backbone/resnet/__init__.py models/vlbert/external/pytorch_pretrained_bert/modeling_transfo_xl_utilities.py scripts/format_image_features.py models/vlbert/common/lib/roi_pooling/__init__.py models/vlbert/common/backbone/resnet/resnet.py models/vlbert/common/lib/roi_pooling/roi_align.py models/vlbert/common/nlp/misc.py models/vlbert/common/nlp/roberta/utils.py models/vlbert/common/nlp/roberta/tokenization_roberta.py models/vlbert/external/pytorch_pretrained_bert/__main__.py models/vlbert/common/metrics/vcr_metrics.py scripts/weat/general_vals.py models/visualbert/model.py models/vlbert/common/nlp/encoder_base.py models/vlbert/common/utils/create_logger.py models/vlbert/external/pytorch_pretrained_bert/tokenization_openai.py dataloaders/visualbert/bias_dataset.py scripts/download_gdrive.py models/vlbert/modules/resnet_vlbert_for_pretraining.py models/vlbert/common/callbacks/epoch_end_callbacks/checkpoint.py models/vlbert/common/utils/masked_softmax.py models/visualbert/model_wrapper.py models/modeling.py models/vlbert/common/metrics/eval_metric.py models/vlbert/common/utils/load.py models/visualbert/__init__.py models/vlbert/external/pytorch_pretrained_bert/modeling.py dataloaders/visualbert/mask_utils.py models/vlbert/external/pytorch_pretrained_bert/convert_gpt2_checkpoint_to_pytorch.py main load_image_features load_eval_params BiasDataLoader VLBERTDataLoader LXMERTDataLoader ViLBERTDataLoader VisualBERTDataLoader cached_path s3_etag http_get s3_request s3_get read_set_from_file get_from_cache filename_to_url url_to_filename split_s3_path get_file_extension BasicTokenizer WordpieceTokenizer load_vocab whitespace_tokenize _is_whitespace _is_control BertTokenizer _is_punctuation create_dataloader LXMERTBiasDataset LXMERTBiasTorchDataset make_uid InputExample load_obj_tsv format_lmdb iou BiasDataset assert_eq InputFeatures InputExample BertPreprocessBatch ImageFeaturesH5Reader ImageFeaturesH5ReaderWithObjClasses HWC_feat_reader InputFeatures get_image_feat_reader screen_feature padded_faster_RCNN_feat_reader InputExample CHW_feat_reader faster_RCNN_feat_reader get_one_image_feature_npz_screening_parameters read_in_image_feats compute_answer_scores dim_3_reader get_one_image_feature padded_faster_RCNN_with_bbox_feat_reader parse_npz_img_feat IntArrayTensorField BertField ArrayTensorField IntArrayField BiasDataset load_image to_tensor_and_normalize resize_image make_mask _spaced_points VCR VCRLoader BiasDataset LXMERTWrapper ViLBERTWrapper VisualBertWrapper ModelWrapper VLBERTWrapper LxmertForPreTrainingBiasOutput LxmertForPreTrainingBias cached_path s3_etag http_get s3_request s3_get read_set_from_file tbLogger get_from_cache filename_to_url url_to_filename lr_warmup split_s3_path get_file_extension BertPreTrainingHeads BertImageSelfAttention BertEncoder BertImagePredictionHead BertSelfAttention BertImgPredictionHeadTransform BertOnlyMLMHead BertImageLayer BertOnlyNSPHead BertImageAttention BertEmbeddings BertTextPooler BertImagePooler BertOutput BertImageOutput BertPredictionHeadTransform BertAttention BertBiOutput BertConnectionLayer gelu BertPreTrainedModel BertForMultiModalPreTraining VILBertForVLTasks BertConfig BertImageIntermediate BertLayer BertModel BertIntermediate BertBiAttention swish BertImageSelfOutput BertLMPredictionHead load_tf_weights_in_bert SimpleClassifier BertSelfOutput BertImageEmbeddings VisualBERTFixedImageEmbedding VisualBERTDetector SimpleReportMetric InferenceModelWrapper update_config FastRCNN WarmupMultiStepLR Module train _multiple_callbacks to_cuda VisualLinguisticBertRelationshipPredictionHead VisualLinguisticBert VisualLinguisticBertMVRCHeadTransform VisualLinguisticBertMVRCHead VisualLinguisticBertForPretraining BaseModel ResNet resnet50 Bottleneck resnet152 conv3x3 resnet34 resnet18 BasicBlock resnet101 Speedometer Checkpoint ValidationMonitor ROIAlign _ROIAlign _ROIPool ROIPool get_extensions CompositeEvalMetric EvalMetric MVRCAccuracy MLMAccuracyAUX RelationshipAccuracy MLMAccuracy MLMAccuracyWVC LossLogger LossLogger ClsPosAccuracy ClsPosFraction ClsAccuracy RefAccuracy JointAccuracy AnsLoss CNNRegLoss PositiveFraction Accuracy LossLogger LossLogger SoftAccuracy BertEncoderWrapper _EncoderBase get_lengths_from_binary_sequence_mask sort_batch_by_length InputVariationalDropout random_word_with_token_ids get_all_ngrams get_align_matrix TimeDistributed AdamW WarmupCosineSchedule WarmupCosineWithHardRestartsSchedule WarmupLinearSchedule WarmupConstantSchedule ConstantLRSchedule RobertaConfig RobertaForSequenceClassification RobertaLMHead RobertaClassificationHead RobertaEmbeddings RobertaForMaskedLM RobertaModel RobertaTokenizer cached_path bytes_to_unicode get_pairs s3_etag http_get s3_request s3_get get_from_cache url_to_filename split_s3_path PreTrainedTokenizer nonlinear_transform bbox_iou_py_vectorized coordinate_embeddings clip_pad_2d clip_pad_images clip_pad_1d clip_pad_boxes create_logger makedirsExist Flattener smart_load_model_state_dict smart_resume smart_partial_load_model_state_dict generate_instance_mask masked_softmax summary_parameters soft_cross_entropy clip_grad print_and_log bn_fp16_half_eval block_digonal_matrix prod MultiTaskDataLoader pad_sequence ZipReader convert_gpt2_checkpoint_to_pytorch convert_openai_checkpoint_to_pytorch convert_tf_checkpoint_to_pytorch convert_transfo_xl_checkpoint_to_pytorch cached_path s3_etag http_get s3_request s3_get read_set_from_file get_from_cache filename_to_url url_to_filename split_s3_path get_file_extension BertPreTrainingHeads BertForQuestionAnswering BertEncoder BertSelfAttention BertForMaskedLM BertOnlyMLMHead BertOnlyNSPHead BertEmbeddings BertOutput BertPredictionHeadTransform BertAttention BertPooler gelu BertPreTrainedModel BertForMultipleChoice BertConfig BertLayer BertForTokenClassification BertModel BertForNextSentencePrediction BertIntermediate BertForSequenceClassification BertForPreTraining swish BertLMPredictionHead load_tf_weights_in_bert BertSelfOutput GPT2LMHeadModel Block GPT2DoubleHeadsModel load_tf_weights_in_gpt2 MLP gelu GPT2PreTrainedModel GPT2Model GPT2LMHead Conv1D GPT2MultipleChoiceHead Attention GPT2Config Attention Block OpenAIGPTPreTrainedModel OpenAIGPTLMHeadModel OpenAIGPTMultipleChoiceHead OpenAIGPTConfig MLP gelu swish OpenAIGPTLMHead OpenAIGPTDoubleHeadsModel Conv1D load_tf_weights_in_openai_gpt OpenAIGPTModel DecoderLayer TransfoXLModel PositionalEmbedding load_tf_weights_in_transfo_xl RelLearnableDecoderLayer AdaptiveEmbedding RelLearnableMultiHeadAttn TransfoXLPreTrainedModel MultiHeadAttn RelPartialLearnableDecoderLayer TransfoXLLMHeadModel PositionwiseFF TransfoXLConfig RelMultiHeadAttn build_tf_to_pytorch_map RelPartialLearnableMultiHeadAttn ProjectedAdaptiveLogSoftmax LogUniformSampler sample_logits warmup_cosine warmup_constant warmup_linear BertAdam warmup_cosine warmup_constant warmup_linear OpenAIAdam BasicTokenizer WordpieceTokenizer load_vocab whitespace_tokenize _is_whitespace _is_control BertTokenizer _is_punctuation bytes_to_unicode get_pairs GPT2Tokenizer get_pairs text_standardize OpenAIGPTTokenizer LMOrderedIterator TransfoXLCorpus TransfoXLTokenizer LMMultiFileIterator get_lm_corpus _is_whitespace _is_control _is_punctuation LMShuffledIterator main ResNetVLBERTForPretraining BiasTest download_file_from_google_drive rename_images_by_number setup_logging_results load_query_params Writer s_wAB stdev_s_wAB mean_s_wAB s_XAB p_val_permutation_test effect_size get_general_vals construct_cossim_lookup convert_keys_to_ints convert_keys_to_ints_combine s_XYAB s_wAB stdev_s_wAB mean_s_wAB p_val_permutation_test inner_p_test effect_size construct_cossim_lookup convert_keys_to_ints run_test s_wAB run_test stdev_s_wAB mean_s_wAB s_XAB p_val_permutation_test effect_size construct_cossim_lookup convert_keys_to_ints convert_keys_to_ints_combine s_XYAB s_wAB run_test stdev_s_wAB mean_s_wAB s_XAB p_val_permutation_test effect_size construct_cossim_lookup convert_keys_to_ints s_XYAB s_wAB run_test stdev_s_wAB mean_s_wAB s_XAB p_val_permutation_test effect_size construct_cossim_lookup convert_keys_to_ints convert_keys_to_ints_combine s_XYAB cossim s_wAB run_test stdev_s_wAB mean_s_wAB s_XAB p_val_permutation_test effect_size construct_cossim_lookup convert_keys_to_ints s_XYAB add_model_args join add_argument device_count model_type ArgumentParser out_dir parse_args AttrDict makedirs getattr run_weat_intra load_image_features run_weat_union open list setup_logging_results load_eval_params model_type Writer add_results_exp3 tests add_results_exp4_mask_v run_weat_mask add_results_exp1 BiasTest close info add_results_exp4_mask_t flush load items encode_data test_name print num_samples add_results_exp2 run_weat_specific test2features_path encode hexdigest sha256 str join isinstance str urlparse isinstance exists path netloc urlparse startswith resource split_s3_path Object resource split_s3_path download_fileobj get update write close tqdm iter_content len get str s3_etag join isinstance url_to_filename startswith head makedirs set OrderedDict strip split category category startswith startswith category ord getattr print time open view size min expand max isinstance item min float32 set zeros count append join read enumerate read get read get arange union1d pad size min resize _spaced_points reshape Path meshgrid zeros bisect float load_variable join int format zip print transpose fullmatch from_numpy any getattr list_variables abspath append split callbacks cb isinstance list isinstance len Tensor cuda range enumerate to_cuda clip_grad_norm_ zero_grad ReduceLROnPlateau BatchEndParam str len master_params range get update _multiple_callbacks mean net enumerate time isinstance backward print validation_monitor set_epoch parameters reset step add_scalar load load_pretrained_state_dict ResNet load_url max load load_pretrained_state_dict ResNet load_url max load load_pretrained_state_dict ResNet load_url max load load_pretrained_state_dict ResNet load_url max load load_pretrained_state_dict ResNet load_url max glob join dirname abspath sort arange index_select len zeros sum max len append range len append random enumerate append list range ord add set decode list filter listdir clamp log cat cos arange sin new_zeros view clamp min meshgrid max zeros as_tensor zeros as_tensor zeros as_tensor zeros as_tensor makedirs join basicConfig format getLogger strftime setLevel makedirsExist INFO items list load_state_dict startswith load best_epoch smart_load_model_state_dict format host_metric_name info print BEGIN_EPOCH END_EPOCH AUTO_RESUME load_state_dict RESUME best_val range exists update items list format print load_state_dict startswith append keys state_dict clamp clone float32 polygon zeros float type dtype sum unsqueeze softmax type zeros zip print info join format print_and_log sum len items norm format sorted info print tuple size isnan mul_ item float prod str __class__ half sum new_zeros len max enumerate new_zeros dict format load_tf_weights_in_gpt2 print GPT2Model save GPT2Config state_dict format OpenAIGPTConfig print save load_tf_weights_in_openai_gpt OpenAIGPTModel state_dict str format print BertForPreTraining save load_tf_weights_in_bert from_json_file state_dict pop str join format __dict__ load_tf_weights_in_transfo_xl print TransfoXLLMHeadModel save abspath TransfoXLConfig state_dict load_variable int format zip print squeeze fullmatch from_numpy getattr list_variables abspath append split load pop int format zip print cumsum fullmatch from_numpy getattr split open update r_r_bias hasattr tie_weight layers out_layers tie_projs emb_layers r_w_bias transformer emb_projs untie_r zip append out_projs enumerate load_variable pop list format items join print transpose from_numpy list_variables keys build_tf_to_pytorch_map enumerate embedding view size einsum masked_fill_ sample cat detach sub replace load join format TransfoXLCorpus print save exists pop convert_openai_checkpoint_to_pytorch convert_transfo_xl_checkpoint_to_pytorch convert_tf_checkpoint_to_pytorch convert_gpt2_checkpoint_to_pytorch get get_confirm_token save_response_content Session join format move listdir enumerate join add_argument device_count model_type ArgumentParser out_dir parse_args AttrDict makedirs join log_dir info addHandler localtime model_type out_dir FileHandler makedirs Size expand stack torch_cossim zeros s_wAB binom warning list s_XAB array append range s_XYAB format concatenate shuffle mean info sf shapiro int combinations std len mean_s_wAB list stdev_s_wAB update list copy info construct_cossim_lookup convert_keys_to_ints sum array convert_keys_to_ints_combine append sum warn tqdm Manager ceil sum max numpy concatenate update copy p_val_permutation_test effect_size info convert_keys_to_ints cuda f_cossim construct_cossim_lookup convert_keys_to_ints_combine list iter next values len intersection set s_wAB cat cossim | # Measuring Social Biases in Grounded Visual and Language Embeddings This is the repo for our paper [Measuring Social Biases in Grounded Vision and Language Embeddings](https://arxiv.org/abs/2002.08911). We implement a version of WEAT/SEAT for visually grounded word embeddings. This is code borrowed and modified from [this repo](https://github.com/W4ngatang/sent-bias). Authors: [Candace Ross](candaceross.io), [Boris Katz](https://www.csail.mit.edu/person/boris-katz), [Andrei Barbu](0xab.com) ## Installation Create the conda environment. ```bash git clone [email protected]:candacelax/bias-in-vision-and-language.git && cd bias-in-vision-and-language conda env create -f environment.yml pip install --no-deps allennlp==0.8.0 python -m spacy download en # download specific model repos | 1,638 |
carVaba/video-classification-3d-cnn-pytorch | ['action recognition'] | ['Can Spatiotemporal 3D CNNs Retrace the History of 2D CNNs and ImageNet?'] | generate_result_video/generate_result_video.py train.py validation.py models/pre_act_resnet.py models/resnext.py temporal_transforms.py spatial_transforms.py test.py dataset.py models/wide_resnet.py opts.py mean.py models/densenet.py classify.py main.py execute.py models/resnet.py model.py classify_video Video get_class_labels load_annotation_data video_loader make_dataset accimage_loader get_default_image_loader get_default_video_loader pil_loader get_video_names_and_annotations printProgressBar get_mean generate_model parse_opts CenterCrop ToTensor Compose Scale Normalize LoopPadding TemporalCenterCrop calculate_video_results test get_fps get_fine_tuning_parameters DenseNet densenet201 densenet169 densenet264 _DenseLayer _DenseBlock _Transition densenet121 conv3x3x3 get_fine_tuning_parameters resnet50 downsample_basic_block resnet152 PreActivationBasicBlock resnet34 resnet200 PreActivationBottleneck resnet18 PreActivationResNet resnet101 conv3x3x3 get_fine_tuning_parameters ResNet downsample_basic_block resnet50 Bottleneck resnet152 resnet34 resnet200 resnet18 resnet10 BasicBlock resnet101 ResNeXtBottleneck conv3x3x3 get_fine_tuning_parameters resnet50 downsample_basic_block ResNeXt resnet152 resnet101 conv3x3x3 get_fine_tuning_parameters WideBottleneck resnet50 downsample_basic_block WideResNet data Video model Variable size Compose tolist DataLoader sample_duration append LoopPadding max range cat enumerate join format image_loader append exists get_default_image_loader append items list format deepcopy list IntTensor append listdir range len print int float format densenet169 densenet201 resnet50 densenet264 DataParallel resnet101 resnet34 resnet200 resnet18 resnet152 resnet10 cuda densenet121 parse_args set_defaults add_argument ArgumentParser topk size mean stack append range update time format model print Variable cpu AverageMeter size eval calculate_video_results append range enumerate len decode format communicate len round float listdir Popen find DenseNet DenseNet DenseNet DenseNet append format range named_parameters data isinstance FloatTensor Variable zero_ avg_pool3d cuda cat PreActivationResNet PreActivationResNet PreActivationResNet PreActivationResNet PreActivationResNet PreActivationResNet ResNet ResNet ResNet ResNet ResNet ResNet ResNet ResNeXt ResNeXt ResNeXt WideResNet | # Video Classification Using 3D ResNet This is a pytorch code for video (action) classification using 3D ResNet trained by [this code](https://github.com/kenshohara/3D-ResNets-PyTorch). The 3D ResNet is trained on the Kinetics dataset, which includes 400 action classes. This code uses videos as inputs and outputs class names and predicted class scores for each 16 frames in the score mode. In the feature mode, this code outputs features of 512 dims (after global average pooling) for each 16 frames. **Torch (Lua) version of this code is available [here](https://github.com/kenshohara/video-classification-3d-cnn).** ## Requirements * [PyTorch](http://pytorch.org/) ``` conda install pytorch torchvision cuda80 -c soumith | 1,639 |
carla-simulator/imitation-learning | ['imitation learning'] | ['End-to-end Driving via Conditional Imitation Learning'] | run_CIL.py agents/imitation/imitation_learning.py agents/imitation/imitation_learning_network.py ImitationLearning load_imitation_learning_network bias_variable weight_xavi_init Network weight_ones constant get_variable constant conv_block print reshape concat fc_block shape range Network len | Conditional Imitation Learning at CARLA =============== Repository to store the conditional imitation learning based AI that runs on carla. The trained model is the one used on "CARLA: An Open Urban Driving Simulator" paper. Requirements ------- tensorflow_gpu 1.1 or more numpy scipy | 1,640 |
carlini/AmI | ['adversarial defense', 'adversarial attack'] | ['Is AmI (Attacks Meet Interpretability) Robust to Adversarial Examples?'] | src/attack_phase_1.py src/utils.py src/attack_phase_2.py vgg_model generate_data VGGFaceModel strengthen attribute_model get_witnesses my_get_prob weaken get_vgg_data get_identity get_data get_layers read_list get_layer_size get_prob Model Input load_weights img_to_array load_img print append array pop list map index extend open listdir split forward abs min get_data mean shape resize append sum std range len forward append strip open COLOR_BGR2RGB float32 resize imread cvtColor get_data forward append blobs | # Attacking "Attacks Meet Interpretability" This repository contains an attack on the the NeurIPS 2018 spotlight paper [Attacks Meet Interpretability](https://arxiv.org/abs/1902.02322). ## Prerequisite * [opencv-python](https://pypi.org/project/opencv-python/) * [dlib](https://pypi.org/project/dlib/) * [caffe](http://caffe.berkeleyvision.org/) ## Setup * Please download VGG-Face caffe model from [here](http://www.robots.ox.ac.uk/~vgg/software/vgg_face/). * Unzip the model under `data/` folder. ## Usage | 1,641 |
carlini/nn_robust_attacks | ['adversarial attack'] | ['Towards Evaluating the Robustness of Neural Networks'] | li_attack.py setup_cifar.py verify.py setup_inception.py train_models.py l0_attack.py l2_attack.py setup_mnist.py test_attack.py CarliniL0 CarliniL2 CarliniLi CIFARModel CIFAR load_batch readimg NodeLookup ImageNet create_graph InceptionModel main maybe_download_and_extract run_inference_on_image MNIST extract_data MNISTModel extract_labels show generate_data train train_distillation read transpose fromstring append range create_graph read fatal join urlretrieve print extractall stat model_dir makedirs maybe_download_and_extract run_inference_on_image imread array imresize flatten join print range list sample append array range print compile Sequential fit SGD add shape Dense load_weights MaxPooling2D train_labels save Conv2D train_data Activation Flatten Dropout print train train_data predict | ### About Corresponding code to the paper "Towards Evaluating the Robustness of Neural Networks" by Nicholas Carlini and David Wagner, at IEEE Symposium on Security & Privacy, 2017. Implementations of the three attack algorithms in Tensorflow. It runs correctly on Python 3 (and probably Python 2 without many changes). To evaluate the robustness of a neural network, create a model class with a predict method that will run the prediction network *without softmax*. The model should have variables model.image_size: size of the image (e.g., 28 for MNIST, 32 for CIFAR) | 1,642 |
carlini/pixel-deflection | ['adversarial attack'] | ['Deflecting Adversarial Attacks with Pixel Deflection'] | utils.py main.py methods.py process_image classify_images process_image_parallel attack get_arguments pixel_deflection denoiser get_img rgb2ycc batches ycc2rgb get_imagenet_labels get_map add_argument ArgumentParser preprocess_input join format decode_predictions print stack zip predict get_img window deflections get_map pixel_deflection zeros sigma format batches glob directory batch_size cpu_count print classify_images append preprocess_input clip get_session model print imsave float32 placeholder copy sparse_softmax_cross_entropy_with_logits sign classify_images range array log shape range dot T array float array astype load_img Normalize load open | # Deflecting Adversarial Attacks with Pixel Deflection The code in this repository demonstrates that [Deflecting Adversarial Attacks with Pixel Deflection](https://arxiv.org/abs/1801.08926) (Prakash et al. 2018) is ineffective in the white-box threat model. With an L-infinity perturbation of 4/255, we generate targeted adversarial examples with 97% success rate, and can reduce classifier accuracy to 0%. See [our note](TODO) for more context and details. ## Pretty pictures Obligatory picture of sample of adversarial examples against this defense. | 1,643 |
carlosabrx/solubility_model | ['imbalanced classification'] | ['MoleculeNet: A Benchmark for Molecular Machine Learning'] | predicting_solubilities.py | # Modeling Graph Convolutional Networks to Predict Compounds' Solubilities Using DeepChem This study focused on utilizing the DeepChem package to effectively predict the solubilities of chemical compounds. Solubility is the measure of how fast a compound can dissolve in solution. This is important for drug-discovery and applied chemistry techniques. Using a sample CSV data from DeepChem repository, the parameters were selected directly from the data to explore. After defining the parameters for the model, a transformer was initiated in order to split the data and load features. Pearson's r^2 coefficient is used to measure accuracy, number of features was set to 75, while the batch size is 128. In this study Graph Convolutional Networks (GCN) were used because they provide easy manipulation to simulate chemical compounds. Following Stephen Wolfram's newly published article "Finally We May Have a Path to the Fundamental Laws of Physics... and It's Beautiful" (https://writings.stephenwolfram.com/2020/04/finally-we-may-have-a-path-to-the-fundamental-theory-of-physics-and-its-beautiful/), he suggests atoms being nodes and bonds being edges in a hypergraph. This metaphor is perfect for GCNs because it could simulate entire compounds from convoluted layers of hypergraphs. GCNs have been proven very effective to train models, however they have the huge limitation of only working with molecular graphs. After deciding on the model, the data is fit to be trained and tested. Metrics are computed predicting a 95% accuracy rate. Finally, after designing the model, a simple example was tested to predict the solubility of random molecules using SMILES notation. This study follows the original paper from Stanford/Schrodinger Inc's MoleculeNet: A Benchmark for Molecular Machine Learning. (https://arxiv.org/pdf/1703.00564.pdf) | 1,644 |
carlotes247/IGGI19_Imitation_Learning_Workshop | ['unity'] | ['Unity: A General Platform for Intelligent Agents'] | ml-agents-envs/mlagents/envs/communicator_objects/unity_rl_input_pb2.py ml-agents/mlagents/trainers/components/reward_signals/curiosity/model.py ml-agents-envs/mlagents/envs/communicator_objects/unity_to_external_pb2.py ml-agents/mlagents/trainers/components/reward_signals/reward_signal.py gym-unity/gym_unity/envs/__init__.py ml-agents/mlagents/trainers/learn.py ml-agents-envs/mlagents/envs/communicator_objects/custom_observation_pb2.py ml-agents/mlagents/trainers/meta_curriculum.py ml-agents/mlagents/trainers/tests/test_barracuda_converter.py ml-agents/mlagents/trainers/ppo/models.py gym-unity/gym_unity/__init__.py utils/validate_meta_files.py ml-agents/mlagents/trainers/trainer_controller.py ml-agents/mlagents/trainers/components/bc/model.py ml-agents/mlagents/trainers/tests/test_curriculum.py ml-agents-envs/mlagents/envs/communicator.py ml-agents-envs/mlagents/envs/communicator_objects/custom_reset_parameters_pb2.py ml-agents/mlagents/trainers/tests/test_ppo.py ml-agents-envs/mlagents/envs/tests/test_rpc_communicator.py ml-agents/mlagents/trainers/components/reward_signals/__init__.py ml-agents-envs/setup.py ml-agents/mlagents/trainers/tests/mock_brain.py ml-agents-envs/mlagents/envs/action_info.py ml-agents-envs/mlagents/envs/rpc_communicator.py ml-agents/mlagents/trainers/tests/test_bcmodule.py ml-agents/mlagents/trainers/tests/test_trainer_controller.py ml-agents/mlagents/trainers/components/reward_signals/reward_signal_factory.py ml-agents/setup.py ml-agents/mlagents/trainers/barracuda.py ml-agents-envs/mlagents/envs/tests/test_envs.py ml-agents-envs/mlagents/envs/env_manager.py ml-agents/mlagents/trainers/ppo/trainer.py ml-agents-envs/mlagents/envs/tests/test_timers.py ml-agents-envs/mlagents/envs/communicator_objects/unity_rl_output_pb2.py ml-agents-envs/mlagents/envs/communicator_objects/unity_rl_initialization_output_pb2.py ml-agents-envs/mlagents/envs/communicator_objects/unity_input_pb2.py ml-agents/mlagents/trainers/tests/test_meta_curriculum.py ml-agents/mlagents/trainers/components/reward_signals/curiosity/signal.py ml-agents-envs/mlagents/envs/subprocess_env_manager.py ml-agents/mlagents/trainers/bc/trainer.py ml-agents/mlagents/trainers/components/reward_signals/curiosity/__init__.py ml-agents-envs/mlagents/envs/communicator_objects/agent_action_proto_pb2.py ml-agents/mlagents/trainers/curriculum.py ml-agents/mlagents/trainers/tests/test_policy.py ml-agents/mlagents/trainers/ppo/policy.py ml-agents-envs/mlagents/envs/communicator_objects/space_type_proto_pb2.py ml-agents/mlagents/trainers/tests/test_learn.py ml-agents-envs/mlagents/envs/communicator_objects/brain_parameters_proto_pb2.py ml-agents/mlagents/trainers/tests/test_demo_loader.py ml-agents/mlagents/trainers/components/bc/__init__.py ml-agents/mlagents/trainers/models.py ml-agents/mlagents/trainers/__init__.py ml-agents-envs/mlagents/envs/communicator_objects/agent_info_proto_pb2.py ml-agents-envs/mlagents/envs/communicator_objects/environment_parameters_proto_pb2.py ml-agents-envs/mlagents/envs/policy.py ml-agents/mlagents/trainers/exception.py gym-unity/gym_unity/tests/test_gym.py ml-agents/mlagents/trainers/tests/test_environments/test_simple.py ml-agents/mlagents/trainers/components/reward_signals/extrinsic/__init__.py ml-agents/mlagents/trainers/buffer.py ml-agents/mlagents/trainers/bc/online_trainer.py ml-agents-envs/mlagents/envs/communicator_objects/engine_configuration_proto_pb2.py ml-agents/mlagents/trainers/ppo/__init__.py ml-agents/mlagents/trainers/tensorflow_to_barracuda.py ml-agents-envs/mlagents/envs/communicator_objects/unity_to_external_pb2_grpc.py ml-agents-envs/mlagents/envs/mock_communicator.py ml-agents-envs/mlagents/envs/timers.py gym-unity/setup.py ml-agents-envs/mlagents/envs/communicator_objects/unity_message_pb2.py ml-agents-envs/mlagents/envs/environment.py ml-agents-envs/mlagents/envs/communicator_objects/custom_action_pb2.py ml-agents/mlagents/trainers/bc/policy.py ml-agents-envs/mlagents/envs/simple_env_manager.py ml-agents-envs/mlagents/envs/base_unity_environment.py ml-agents/mlagents/trainers/bc/__init__.py ml-agents-envs/mlagents/envs/communicator_objects/unity_output_pb2.py ml-agents/mlagents/trainers/components/reward_signals/extrinsic/signal.py ml-agents/mlagents/trainers/components/reward_signals/gail/__init__.py ml-agents-envs/mlagents/envs/sampler_class.py ml-agents-envs/mlagents/envs/exception.py gym-unity/gym_unity/envs/unity_env.py ml-agents/mlagents/trainers/components/reward_signals/gail/model.py ml-agents-envs/mlagents/envs/communicator_objects/header_pb2.py ml-agents/mlagents/trainers/tests/test_reward_signals.py ml-agents-envs/mlagents/envs/brain.py ml-agents/mlagents/trainers/components/reward_signals/gail/signal.py ml-agents-envs/mlagents/envs/communicator_objects/demonstration_meta_proto_pb2.py ml-agents-envs/mlagents/envs/communicator_objects/resolution_proto_pb2.py ml-agents-envs/mlagents/envs/communicator_objects/__init__.py ml-agents/mlagents/trainers/demo_loader.py ml-agents-envs/mlagents/envs/__init__.py ml-agents/mlagents/trainers/components/bc/module.py ml-agents/mlagents/trainers/tests/test_trainer_metrics.py ml-agents-envs/mlagents/envs/tests/test_sampler_class.py ml-agents/mlagents/trainers/tests/test_buffer.py ml-agents-envs/mlagents/envs/communicator_objects/command_proto_pb2.py ml-agents/mlagents/trainers/trainer.py ml-agents-envs/mlagents/envs/socket_communicator.py ml-agents-envs/mlagents/envs/tests/test_subprocess_env_manager.py ml-agents/mlagents/trainers/bc/models.py ml-agents/mlagents/trainers/bc/offline_trainer.py ml-agents/mlagents/trainers/tf_policy.py ml-agents/mlagents/trainers/tests/test_bc.py ml-agents-envs/mlagents/envs/communicator_objects/unity_rl_initialization_input_pb2.py ml-agents/mlagents/trainers/trainer_metrics.py UnityGymException ActionFlattener UnityEnv create_mock_vector_braininfo test_gym_wrapper test_multi_agent test_branched_flatten setup_mock_unityenvironment create_mock_brainparams BarracudaWriter fuse print_known_operations compress Build sort lstm write fuse_batchnorm_weights trim mean gru Model summary Struct parse_args to_json rnn BufferException Buffer Curriculum make_demo_buffer load_demonstration demo_to_buffer CurriculumError MetaCurriculumError TrainerError create_environment_factory create_sampler_manager run_training prepare_for_docker_run try_create_meta_curriculum main load_config MetaCurriculum EncoderType LearningModel get_layer_shape pool_to_HW flatten sqr_diff process_layer process_model get_layer_rank slow_but_stable_topological_sort get_attr basic_lstm ModelBuilderContext order_by get_epsilon get_tensor_dtype replace_strings_in_list debug embody by_op get_tensor_dims strided_slice remove_duplicates_from_list axis_to_barracuda by_name locate_actual_output_node convert strides_to_HW get_tensor_data very_slow_but_stable_topological_sort gru TFPolicy UnityPolicyException UnityTrainerException Trainer TrainerController TrainerMetrics BehavioralCloningModel OfflineBCTrainer OnlineBCTrainer BCPolicy BCTrainer BCModel BCModule RewardSignal create_reward_signal CuriosityModel CuriosityRewardSignal ExtrinsicRewardSignal GAILModel GAILRewardSignal PPOModel PPOPolicy PPOTrainer get_gae discount_rewards create_buffer simulate_rollout create_mock_banana_brain setup_mock_unityenvironment create_mock_braininfo create_mock_brainparams create_mock_3dball_brain test_barracuda_converter test_dc_bc_model test_cc_bc_model test_visual_cc_bc_model test_bc_policy_evaluate dummy_config test_visual_dc_bc_model test_bc_trainer test_bcmodule_rnn_update test_bcmodule_update test_bcmodule_dc_visual_update dummy_config create_ppo_policy_with_bc_mock test_bcmodule_defaults test_bcmodule_rnn_dc_update assert_array test_buffer location default_reset_parameters test_init_curriculum_bad_curriculum_raises_error test_init_curriculum_happy_path test_increment_lesson test_get_config test_load_demo test_load_demo_dir basic_options test_docker_target_path test_run_training test_init_meta_curriculum_happy_path test_increment_lessons_with_reward_buff_sizes default_reset_parameters MetaCurriculumTest test_increment_lessons measure_vals reward_buff_sizes test_set_all_curriculums_to_lesson_num test_get_config test_set_lesson_nums test_init_meta_curriculum_bad_curriculum_folder_raises_error more_reset_parameters basic_mock_brain test_take_action_returns_action_info_when_available basic_params test_take_action_returns_nones_on_missing_values test_take_action_returns_empty_with_no_agents test_trainer_increment_step test_rl_functions test_ppo_model_dc_vector_rnn test_ppo_model_cc_vector_rnn test_ppo_policy_evaluate test_ppo_model_cc_visual dummy_config test_ppo_model_dc_vector test_ppo_model_dc_visual test_ppo_get_value_estimates test_ppo_model_cc_vector test_gail_visual reward_signal_update reward_signal_eval test_extrinsic test_curiosity_cc test_gail_rnn test_gail_cc create_ppo_policy_mock test_curiosity_dc curiosity_dummy_config dummy_config test_gail_dc test_curiosity_visual test_curiosity_rnn gail_dummy_config test_initialize_online_bc_trainer basic_trainer_controller assert_bc_trainer_constructed test_initialize_trainer_parameters_uses_defaults dummy_bad_config test_take_step_adds_experiences_to_trainer_and_trains test_initialize_trainer_parameters_override_defaults test_initialize_invalid_trainer_raises_exception test_start_learning_trains_until_max_steps_then_saves dummy_config dummy_offline_bc_config_with_override test_initialization_seed test_initialize_ppo_trainer test_start_learning_updates_meta_curriculum_lesson_number assert_ppo_trainer_constructed test_start_learning_trains_forever_if_no_train_model dummy_offline_bc_config trainer_controller_with_take_step_mocks trainer_controller_with_start_learning_mocks dummy_online_bc_config TestTrainerMetrics clamp test_simple Simple1DEnvironment ActionInfo BaseUnityEnvironment safe_concat_np_ndarray BrainInfo BrainParameters safe_concat_lists Communicator UnityEnvironment EnvManager StepInfo SamplerException UnityWorkerInUseException UnityException UnityCommunicationException UnityTimeOutException UnityEnvironmentException UnityActionException MockCommunicator Policy RpcCommunicator UnityToExternalServicerImplementation MultiRangeUniformSampler UniformSampler SamplerFactory SamplerManager GaussianSampler Sampler SimpleEnvManager SocketCommunicator worker EnvironmentResponse UnityEnvWorker StepResponse SubprocessEnvManager EnvironmentCommand TimerNode hierarchical_timer get_timer_root get_timer_tree reset_timers timed TimerStack UnityToExternalServicer UnityToExternalStub add_UnityToExternalServicer_to_server test_initialization test_reset test_close test_step test_handles_bad_filename test_rpc_communicator_checks_port_on_create test_rpc_communicator_create_multiple_workers test_rpc_communicator_close test_empty_samplers sampler_config_1 check_value_in_intervals incorrect_uniform_sampler test_incorrect_sampler test_sampler_config_1 sampler_config_2 incorrect_sampler_config test_incorrect_uniform_sampler test_sampler_config_2 mock_env_factory SubprocessEnvManagerTest MockEnvWorker test_timers decorated_func main create_mock_vector_braininfo sample UnityEnv setup_mock_unityenvironment step create_mock_brainparams create_mock_vector_braininfo UnityEnv setup_mock_unityenvironment step create_mock_brainparams setup_mock_unityenvironment create_mock_vector_braininfo create_mock_brainparams UnityEnv Mock list Mock array 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 layers isinstance print tensors inputs zip to_json globals Build array_equal pool reduce Build tanh mad tanh mul Build concat add sigmoid sub mad _ tanh mul Build concat add sigmoid mad print sorted keys Buffer reset_local_buffers number_visual_observations append_update_buffer append range enumerate make_demo_buffer load_demonstration join read suffix isdir endswith BrainParametersProto from_agent_proto DemonstrationMetaProto ParseFromString AgentInfoProto isfile append from_proto listdir _DecodeVarint32 start_learning int str format create_environment_factory create_sampler_manager TrainerController put try_create_meta_curriculum reset_parameters load_config SubprocessEnvManager pop SamplerManager load_config list MetaCurriculum reset_parameters keys chmod format basename isdir glob copyfile copytree prepare_for_docker_run replace int Process join docopt getLogger print run_training start Queue info append randint setLevel range endswith len print HasField hasattr get_attr isinstance 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 Build mul sub insert Build tolist append range len locate_actual_output_node name find_tensor_by_name split locate_actual_output_node name lstm find_tensor_by_name find_forget_bias split get_layer_shape id Struct tensor get_layer_rank layer_ranks hasattr name patch_data rank input_shapes out_shapes input get_attr append replace_strings_in_list tensors embody astype op inputs zip enumerate print float32 patch_data_fn model_tensors map_ignored_layer_to_its_input co_argcount len items list hasattr get_tensors name print process_layer eval slow_but_stable_topological_sort ModelBuilderContext sort assign_ids pop range insert len layers verbose Struct process_model open print_known_operations fuse compress node GraphDef Model dims_to_barracuda_shape insert get_tensor_dims inputs MessageToJson ParseFromString cleanup_layers read memories print sort write trim summary print_supported_ops get check_config rcls list zeros_like size reversed range append discount_rewards Mock list ones array range create_buffer brain sequence_length append range Buffer ones number_visual_observations append_update_buffer shape append range enumerate create_mock_brainparams create_mock_brainparams join remove _get_candidate_names convert _get_default_tempdir dirname abspath isfile next BCTrainer simulate_rollout increment_step mock_env update_policy dirname abspath setup_mock_unityenvironment policy create_mock_braininfo create_mock_3dball_brain BCPolicy evaluate close reset MockCommunicator reset_default_graph UnityEnvironment reset_default_graph reset_default_graph reset_default_graph reset_default_graph mock_env dirname abspath PPOPolicy setup_mock_unityenvironment create_mock_braininfo create_ppo_policy_with_bc_mock close create_mock_3dball_brain update items list close create_ppo_policy_with_bc_mock create_mock_3dball_brain update items list close create_ppo_policy_with_bc_mock create_mock_3dball_brain update items list close create_mock_banana_brain create_ppo_policy_with_bc_mock update items list close create_mock_banana_brain create_ppo_policy_with_bc_mock flatten list range len get_batch Buffer assert_array append_update_buffer make_mini_batch append reset_agent array range Curriculum Curriculum Curriculum make_demo_buffer load_demonstration dirname abspath make_demo_buffer load_demonstration dirname abspath MagicMock basic_options MagicMock MetaCurriculum assert_has_calls MetaCurriculumTest increment_lessons assert_called_with MetaCurriculumTest increment_lessons assert_called_with assert_not_called MetaCurriculumTest set_all_curriculums_to_lesson_num MetaCurriculumTest dict update MetaCurriculumTest MagicMock TFPolicy basic_mock_brain basic_params BrainInfo get_action MagicMock TFPolicy basic_mock_brain basic_params BrainInfo get_action MagicMock TFPolicy basic_mock_brain ActionInfo basic_params BrainInfo get_action evaluate close reset MockCommunicator PPOPolicy reset_default_graph UnityEnvironment get_value_estimates items list close reset MockCommunicator PPOPolicy reset_default_graph UnityEnvironment reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph assert_array_almost_equal array discount_rewards Mock increment_step BrainParameters assert_called_with PPOTrainer update mock_env PPOPolicy setup_mock_unityenvironment create_mock_braininfo create_mock_brainparams reset evaluate simulate_rollout update_buffer update create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval reward_signal_update reward_signal_eval create_ppo_policy_mock dirname abspath create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval create_ppo_policy_mock reward_signal_update reward_signal_eval dummy_offline_bc_config TrainerController assert_called_with SamplerManager BrainParametersMock basic_trainer_controller assert_bc_trainer_constructed dummy_offline_bc_config summaries_dir model_path keep_checkpoints BrainParametersMock basic_trainer_controller assert_bc_trainer_constructed summaries_dir model_path keep_checkpoints dummy_offline_bc_config_with_override BrainParametersMock basic_trainer_controller assert_bc_trainer_constructed summaries_dir model_path keep_checkpoints dummy_online_bc_config BrainParametersMock basic_trainer_controller assert_ppo_trainer_constructed summaries_dir dummy_config model_path keep_checkpoints dummy_bad_config basic_trainer_controller MagicMock basic_trainer_controller start_learning assert_called_once MagicMock external_brains assert_not_called dummy_config trainer_controller_with_start_learning_mocks assert_called_once_with start_learning assert_called_once MagicMock external_brains dummy_config trainer_controller_with_start_learning_mocks assert_called_once_with start_learning MagicMock dummy_config trainer_controller_with_start_learning_mocks assert_called_once_with lesson MagicMock basic_trainer_controller assert_called_once Mock MagicMock StepInfo current_all_brain_info advance outputs assert_not_called trainer_controller_with_take_step_mocks assert_called_once_with previous_all_brain_info extend copy global_done get_timer_root reset_timers put _send_response reset_parameters StepResponse env_factory memory list action value external_brains payload items EnvironmentResponse text reset step perf_counter push reset method_handlers_generic_handler add_generic_rpc_handlers UnityEnvironment close MockCommunicator UnityEnvironment close MockCommunicator reset str local_done print agents step close reset MockCommunicator UnityEnvironment len UnityEnvironment close MockCommunicator close RpcCommunicator close RpcCommunicator close RpcCommunicator SamplerManager sample_all sampler_config_1 sampler_config_2 SamplerManager SamplerManager sample_all incorrect_uniform_sampler incorrect_sampler_config replace endswith add set walk | # This is the repo (from the Unity ML-Agents main repo) for the IMITATION LEARNING WORKSHOP at [IGGI2019](http://2019.iggi.org.uk/) ## The workshop was run by [Cristina Dobre](https://twitter.com/shesCristina) and [Carlos Gonzalez Diaz](https://twitter.com/Carlotes247) Thank you so such if you have participated. If you have any questions or feedback, please feel free to get in touch! Also, if you'd like to have a look at the slides I used, [you can find the presentation at this link](https://docs.google.com/presentation/d/1Q7S3RcUPYF3c8m5Y22ruEv24_OBPnffpIoDStV60VY4/edit?usp=sharing). __________________________________________________________________ <img src="docs/images/unity-wide.png" align="middle" width="3000"/> <img src="docs/images/image-banner.png" align="middle" width="3000"/> # Unity ML-Agents Toolkit (Beta) [](docs/Readme.md) [](LICENSE) **The Unity Machine Learning Agents Toolkit** (ML-Agents) is an open-source | 1,645 |
carnotaur/crnn-tutorial | ['optical character recognition', 'scene text detection', 'scene text recognition'] | ['An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition', 'Scene Text Detection and Recognition: The Deep Learning Era'] | utils/plotting.py layers.py utils/__init__.py utils/utils.py blockCNN blockRNN plot_loss print_prediction decode_prediction strLabelConverter show clear_output subplots set_title plot asarray convert axis imshow title decode_prediction cpu randint len join argmax numpy split | Введение в работу __Convolutional Recurrent Neural Networks (CRNN)__ используя _PyTorch_ Туториал можно просмотреть в jupyter notebook  Процесс тренировки сети написан в __CRNN Training.ipynb__ Вместо VGG сети которая использовалсь в статье для основы был использован Resnet18, но ничто не мешает вам поменять ее. __Requirements:__ _pytorch >= 1.0.0_ Слайды сделаны на основе статей: https://arxiv.org/abs/1507.05717 и https://arxiv.org/abs/1811.04256 Туториалы по работе _Convolutional Neural Networks_: | 1,646 |
cas995/Thesis-PDG | ['text generation'] | ['Towards Knowledge-Based Personalized Product Description Generation in E-commerce'] | core/utils/__init__.py core/lr_scheduler.py core/preprocess.py core/api.py core/models/tensor2tensor.py core/models/__init__.py core/models/seq2seq.py core/utils/dict_helper.py scripts/score_diversity.py scripts/download_preprocessed_tao.py core/train.py core/dataset.py core/models/attention.py core/models/beam.py core/models/rnn.py core/models/transformer.py core/models/optims.py core/utils/metrics.py core/utils/misc_utils.py core/opts.py core/utils/data_helper.py DescriptionGeneratorProxy DescriptionGenerator DescriptionGeneratorMultiprocessing load_data ExponentialLR StepLR LambdaLR MultiStepLR _LRScheduler ReduceLROnPlateau CosineAnnealingLR model_opts makeData makeVocabulary saveVocabulary main train_model save_model eval_model build_model luong_attention luong_gate_attention bahdanau_attention maxout Multihead_Attention Beam Optim StackedGRU add_unk rnn_encoder StackedLSTM rnn_decoder seq2seq LabelSmoothingLoss tensor2tensor LabelSmoothingLoss tile PositionwiseFeedForward init_state TransformerDecoderLayer TransformerDecoder BiAttention PositionalEncoding TransformerEncoder TransformerEncoderLayer knowledge_padding BiTestDataset padding BiDataset ae_padding splitDataset split_padding BiKnowledgeDataset Dict bleu rouge eval_metrics set_tensorboard AttrDict set_seed set_cuda untar download move generate_n_grams distinct_n_grams load int data join hasattr valid_batch_size batch_size print size BiDataset knowledge DataLoader scale BiKnowledgeDataset open add_argument ArgumentParser print size prune print writeFile str readline BOS_WORD join convertToIdx list print strip write map close lower EOS_WORD UNK_WORD open src_dict writeFile tgt_filter open makeData makeVocabulary tgt_trun Dict dump tgt_dict save_data tgt_char src_filter src_trun share tgt_vocab_size src_vocab_size src_char print sum learning_rate pretrain Optim print set_parameters repr xavier_uniform_ parameters optim load_state_dict max_grad_norm param_init_glorot uniform_ to param_init save_model model schesamp save_individual zero_grad rl epoch_decay report_interval str defaultdict knowledge append sum updateLearningRate eval_model item metrics backward print sort t index_select rl_coef train step add_scalar metrics print tqdm eval knowledge eval_metrics zip append to save state_dict list view size contiguous range len str range device seed int list Random infos BiDataset shuffle append range len list LongTensor zip long enumerate list LongTensor zip long enumerate BOS list zip long EOS enumerate int list num_samples zip append long range enumerate len call print_log remove refF WARNING Rouge155 output_to_dict print_log convert_and_evaluate mkdir setLevel range len get_metrics mkdir prepare_label range len is_available seed gpu manual_seed join remove listdir print startswith expname logdir makedirs seed manual_seed update join move print close tqdm isfile getsize n print join remove unpack_archive list zip generate_n_grams | # KOBE ### [Project](https://sites.google.com/view/kobe2019) | [arXiv](https://arxiv.org/abs/1903.12457) Towards **K**n**O**wledge-**B**ased p**E**rsonalized Product Description Generation in E-commerce.<br> [Qibin Chen](https://www.qibin.ink)<sup>\*</sup>, [Junyang Lin](https://justinlin610.github.io)<sup>\*</sup>, Yichang Zhang, [Hongxia Yang](https://sites.google.com/site/hystatistics/home), [Jingren Zhou](http://www.cs.columbia.edu/~jrzhou/), [Jie Tang](http://keg.cs.tsinghua.edu.cn/jietang/).<br> <sup>*</sup>Equal contribution.<br> In KDD 2019 (Applied Data Science Track) ## Prerequisites - Linux or macOS - Python 3.6 - PyTorch 1.0.1 | 1,647 |
casperhansen/CPTW | ['word embeddings'] | ['Contextually Propagated Term Weights for Document Representation'] | CPTW.py allmeasures constructDict runCPWE_IDF tokenizeFile computeWordToWordMatrix report computeBOW getStopWordList densify testFunctions constructCorpus loadDataWithPreDefTest constructAndSave computeW2W makeBOW loadDataWithTest run_CPWE_IDF_experiment orderData computeTFIDF removeStopWords loadDataSet f1_score zeros_like concatenate roc_curve len accuracy_score unique zeros auc ravel range enumerate items list filter_tokens append compactify isdir extend filter append zeros len loadDataSet append loadDataSet computeWordToWordMatrix constructDict add_documents tokenizeFile removeStopWords Dictionary getStopWordList T arange print tril similarity eye save load_word2vec_format diag len doc2bow densify tokenizeFile zeros len zeros len densify TfidfModel zeros doc2bow tokenizeFile append zeros len format print mean_validation_score parameters cv_validation_scores std enumerate print loadDataSet loadDataWithTest floor array len allmeasures print runCPWE_IDF orderData append permutation arange log2 KNeighborsClassifier accuracy_score argmax todense csr_matrix shape normalize train_test_split diags range computeW2W predict makeBOW concatenate copy mean predict_proba power TfidfModel print fit dot unravel_index zeros array len print run_CPWE_IDF_experiment load | # CPTW Code for "Contextually Propagated Term Weights for Document Representation" (SIGIR 2019). Casper Hansen, Christian Hansen, Stephen Alstrup, Jakob Grue Simonsen and Christina Lioma. | 1,648 |
cassidylaidlaw/ReColorAdv | ['adversarial attack'] | ['Functional Adversarial Attacks'] | recoloradv/mister_ed/adversarial_attacks.py recoloradv/mister_ed/cifar10/cifar_resnets.py recoloradv/utils.py recoloradv/mister_ed/utils/checkpoints.py recoloradv/color_transformers.py recoloradv/mister_ed/cifar10/cifar_loader.py recoloradv/mister_ed/loss_functions.py recoloradv/mister_ed/cifar10/wide_resnets.py recoloradv/perturbations.py recoloradv/examples/evaluate_imagenet.py recoloradv/mister_ed/adversarial_training.py recoloradv/color_spaces.py recoloradv/examples/evaluate_cifar10.py recoloradv/mister_ed/spatial_transformers.py recoloradv/mister_ed/utils/discretization.py recoloradv/mister_ed/utils/image_utils.py recoloradv/mister_ed/utils/pytorch_ssim.py recoloradv/mister_ed/utils/pytorch_utils.py recoloradv/mister_ed/scripts/setup_cifar.py recoloradv/mister_ed/config.py recoloradv/mister_ed/adversarial_perturbations.py setup.py recoloradv/norms.py ColorSpace ApproxHSVColorSpace CIEXYZColorSpace RGBColorSpace HSVConeColorSpace YPbPrColorSpace CIELUVColorSpace AffineTransform ParameterizedTransformation FullSpatial smoothness ReColorAdv load_pretrained_cifar10_model get_attack_from_name FGSM PGD AdversarialAttack CarliniWagner PerturbationParameters DeltaAddition ParameterizedXformAdv ThreatModel AdversarialPerturbation SequentialPerturbation initialized AdversarialAttackParameters AdversarialTraining path_resolver SSIMRegularization PartialXentropy ReferenceRegularizer LpipsRegularization PerturbationNormLoss RegularizedLoss CombinedTransformerLoss L2Regularization SoftLInfRegularization RelaxedTransformerLoss PartialLoss IncorrectIndicator FullSpatialLpLoss CWLossF6 FullSpatial TranslationTransform RotationTransform AffineTransform ParameterizedTransformation PointScaleTransform load_pretrained_cifar_resnet load_cifar_data load_pretrained_cifar_wide_resnet resnet110 resnet20 ResNet LambdaLayer resnet44 test resnet1202 resnet56 resnet32 _weights_init BasicBlock conv_init conv3x3 wide_basic Wide_ResNet file_hash check_cifar_data_loaded load_cifar_classifiers load_state_dict_from_filename CustomDataSaver list_saved_epochs clear_experiment load_state_dict params_to_filename save_state_dict CustomDataLoader discretized_adversarial discretize_image flip_greedy_pixel flip_random_pixel display_adversarial_notebook nchw_l2 show_images nhwc255_xform display_adversarial_2row create_window gaussian _ssim SSIM ssim fold_mask cuda_assert random_from_lp_ball tuple_setter torch_arctanh IdentityNormalize clamp_ref summed_lp_norm get_gpu_memory_map DifferentiableNormalize unset_global_gpu tanh_transform accuracy_int torch_argmin safe_var tanh_rescale random_linf_pertubation use_gpu tuple_getter checkpoint_incremental_array set_global_gpu batchwise_lp_project rough_gpu_estimate TrainingLogger batchwise_norm sizeof_fmt clamp_0_1_delta clip_0_1 AverageMeter accuracy safe_tensor torch_argmax Variable tuple size add_ pow zeros sum range len load load_state_dict DifferentiableNormalize PerturbationParameters ReColorAdv ParameterizedXformAdv DeltaAddition PerturbationNormLoss RegularizedLoss ThreatModel SequentialPerturbation PGD CWLossF6 append split startswith load use_gpu join load_state_dict DifferentiableNormalize load join Wide_ResNet load_state_dict DifferentiableNormalize update use_gpu ToTensor Compose extend Normalize append weight kaiming_normal_ __name__ print constant xavier_uniform bias weight __name__ print DEFAULT_DATASETS_DIR CIFAR10 sha256 join read MODEL_PATH print close add set urlopen makedirs join params_to_filename params_to_filename join basename isinstance glob select_epoch append valid_epoch join state_dict save params_to_filename len load join right_dict load_state_dict params_to_filename list view shape stack unsqueeze zip append data tuple_setter sign next_pixel_to_flip unsqueeze forward add append safe_var range ne tuple_getter set float enumerate pop Variable clone safe_tensor discretize_image len shape show list transpose squeeze shape imshow figure append zeros show list print transpose min sample imshow eval selector type append zeros forward max range cat enumerate pow sum dim range Tensor Variable contiguous unsqueeze pow conv2d create_window size type_as get_device cuda is_cuda is_available str unsetenv _TensorBase isinstance warn _TensorBase ndarray isinstance warn max numel view min numel view save concatenate ones type rand isinstance sum max transpose pow abs dim range unsqueeze renorm min expand type unsqueeze abs batchwise_norm isinstance zeros_like Variable add_ make_broadcastable type safe_tensor check_output get listprod size get_objects get_device t topk eq expand_as topk size t eq mul_ expand_as append sum max | # ReColorAdv This is an implementation of the ReColorAdv adversarial attack and other attacks described in the NeurIPS 2019 paper ["Functional Adversarial Attacks"](https://arxiv.org/abs/1906.00001). ## Getting Started Clone this repository by running git clone https://github.com/cassidylaidlaw/ReColorAdv You can experiment with the ReColorAdv attack, by itself and combined with other attacks, in the [`getting_started.ipynb`](getting_started.ipynb) Jupyter notebook. You can also open the notebook in Google Colab via the badge below. [](https://colab.research.google.com/github/cassidylaidlaw/ReColorAdv/blob/master/getting_started_colab.ipynb) You can also install the ReColorAdv package with pip by running pip install recoloradv ## Evaluation Script (CIFAR-10) | 1,649 |
catcd/RbSP | ['relation extraction'] | ['A Richer-but-Smarter Shortest Dependency Path with Attentive Augmentation for Relation Extraction'] | dataset/dataset_sem2010.py build_data.py model/dep_a_cnn.py dataset/dataset.py test_sem2010.py utils.py data/sem2010/constants.py build_sem2010 main get_trimmed_w2v_vectors WordNet _pad_sequences pad_sequences Log load_wordnet_superset load_vocab Timer load_vocab_utf8 load_wordnet_node2vec merge_dataset Dataset Sem2010Dataset DepACNN load_wordnet_superset Timer open RAW_DATA ALL_RELATIONS HIGHEST_PROTOCOL Sem2010Dataset dump format PICKLE_DATA start listdir ALL_CHARS rsplit print ALL_POSES load_vocab stop ALL_WORDS TRIMMED_W2V load_wordnet_superset PATIENCE REPLACEMENT open BATCH_SIZE identities build EPOCHS range get_trimmed_w2v_vectors format DepACNN close PICKLE_DATA run_train load clone write load_data predict_on_test JOB_IDENTITY EARLY_STOPPING PERCENTAGE len dict dict dict dict list max len _pad_sequences max child_positions list positions relations poses identities words labels indexes child_indexes directions chars wordnet_supersets s_relations chain Dataset | catcd/RbSP | 1,650 |
catniplab/tree_structured_rslds | ['data augmentation'] | ['Tree-Structured Recurrent Switching Linear Dynamical Systems for Multi-Scale Modeling'] | test/test_plotting.py examples/circle.py trslds/initialize.py trslds/models.py examples/tree_nascar.py examples/fhn_spikes.py test/test_models.py setup.py test/test_conditionals.py trslds/fit_greedy_mse.py test/test_misc.py trslds/utils.py trslds/conditionals.py examples/lorenz.py trslds/plotting.py simulate_circle plot_rotated_vf resample resample FitzHugh fhn_vf noisy_FitzHugh resample f simulate_tree_nascar resample _internal_dynamics pg_kalman_batch emission_parameters pg_kalman emission_parameters_spike_train pg_spike_train discrete_latent_recurrent_only pg_tree_posterior hyper_planes leaf_dynamics top_to_bottom initialize_discrete initialize TroSLDS gradient_cmap vector_field rot_contour_plt rot_vector_field contour_plt gaussian_kernel_smoother generate_trajectory compute_ss_mniw rotate_latent create_balanced_binary_tree rotate_dynamics create_batches sample_internal_dynamics MAP_dynamics optimize_tree log_mvn sigmoid_vectorized sample_mniw projection compute_leaf_log_prob_vectorized compute_residual sigmoid sample_hyperplanes sample_leaf_dynamics compute_leaf_log_prob list _generate_data randint pi create_balanced_binary_tree TroSLDS tqdm uniform repeat eye append zeros array range list _sample_continuous_latent _sample_hyperplanes tqdm _initialize_polya_gamma _sample_emission range _sample_discrete_latent _sample_dynamics R add_subplot K depth leaf_paths set_aspect show gradient_cmap imshow Aleaf range concatenate streamplot set_xlim rot_contour_plt sqrt rot_vector_field figure array set_ylim normal power sqrt zeros range zeros power range size power shape meshgrid zeros range list _generate_data randint pi create_balanced_binary_tree flatten TroSLDS uniform repeat tqdm eye append zeros array range int ones reshape size matmul flatten pgdrawvpar randint empty array range len ones reshape size flatten pgdrawvpar randint empty range len T compute_ss_mniw hstack power sample_mniw diag T multivariate_normal multiply size hstack inv diag matmul power sqrt vstack zeros ravel range T multiply inv sqrt einsum size eye inv kron T sample_mniw compute_ss_mniw det sum exp ones size inv compute_leaf_log_prob_vectorized ravel multinomial range max log len normal T diag size inv solve flatten cholesky eye zeros expand_dims ravel array range normal T diag size inv solve flatten cholesky eye zeros expand_dims ravel array range len randn rand exp optimize_tree ones multiply solve trace append expand_dims range size hstack int T print repeat zeros numpy array exp size ravel multinomial append zeros compute_leaf_log_prob argmax max range len randn add_subplot create_balanced_binary_tree show ones set_xlabel append top_to_bottom range plot size hstack initialize_discrete nan int T print PCA isnan set_ylabel figure zeros len exp size flatten meshgrid zeros compute_leaf_log_prob sum max range exp size solve flatten meshgrid zeros compute_leaf_log_prob sum max range T exp size flatten shape meshgrid zeros compute_leaf_log_prob sum max range exp size solve flatten shape meshgrid zeros compute_leaf_log_prob sum max range LinearSegmentedColormap linspace zip append len size inv solve T rvs reshape shape T ravel range hyper_planes hstack vstack range _internal_dynamics range hstack vstack leaf_dynamics exp zeros size exp zeros range int matmul int flatten zeros sigmoid_vectorized range log int arange ones size isnan log2 repeat nan ceil zeros range append astype mul transpose matmul sigmoid sum range int list backward size step zero_grad Adam compute_residual tqdm create_batches trace item append double range T hstack argmax exp ones astype ravel flatten multinomial zeros compute_leaf_log_prob sum max range deepcopy list tqdm sample_leaf_dynamics append sample_internal_dynamics range len size gaussian shape convolve1d zeros sum range | # tree_structured_rslds Tree-structured recurrent switching linear dynamical systems (TrSLDS) are an extension of recurrent switching linear dynamical systems (rSLDS) from [Linderman et al., 2017](http://proceedings.mlr.press/v54/linderman17a/linderman17a.pdf). Similar to rSLDS, TrSLDS introduces a dependency between the continuous and discrete latent states which allows the probability distribtuion of the discrete states to depend on the continuous states; this depdency paritiions the space, where each partition has it's own linear dynamics. While rSLDS partitions the space using (sequential) stick-breaking, TrSLDS utilizes tree-structured stick-breaking to partition the space:  A priori, it is natural to expect that locally linear dynamics of nearby regions in the latent space are similar. Thus, in the context of tree-structured stick breaking, we impose that partitions that share a common parent should have similar dynamics. We explicitly model this by enforcing a hierarchical prior on the dynamics that respects the tree structure which allows for a multi-scale view of the system. The model is efficenitly learned through Gibbs sampling. Complete details of the algorithm are given in the following paper: ```` | 1,651 |
catta202000/CMRNet | ['visual localization', 'autonomous driving'] | ['CMRNet++: Map and Camera Agnostic Monocular Visual Localization in LiDAR Maps'] | losses.py models/CMRNet/CMRNet.py models/CMRNet/__init__.py DatasetVisibilityKitti.py models/CMRNet/correlation_package/setup.py setup.py models/CMRNet/correlation_package/correlation.py camera_model.py quaternion_distances.py utils.py preprocess/kitti_maps.py main_visibility_CALIB.py evaluate_iterative_single_CALIB.py CameraModel get_calib_kitti DatasetVisibilityKittiSingle main config _init_fn L1Loss GeometricLoss ProposedLoss DistancePoints3D config test _init_fn main train quatmultiply quatinv quaternion_distance overlay_imgs rotate_points_torch to_rotation_matrix rotate_back quaternion_from_matrix quat2mat rotate_points invert_pose quatmultiply rotate_forward merge_inputs tvector2mat mat2xyzrpy CMRNet conv predict_flow deconv Correlation CorrelationFunction print seed manual_seed zeros_like quaternion_from_matrix quat2mat DataLoader unsqueeze inverse quaternion_distance numpy rotate_forward CMRNet device tensor save cuda open seed writer show Vector rotate_back len Quaternion waitKey imshow pad load_state_dict tvector2mat append to range overlay_imgs plot close CameraModel eval stack startswith manual_seed item long enumerate load int visibility2 isinstance print writerow depth_image clone tqdm project_pytorch zeros mm dataset_class split backward model zero_grad loss_fn step pi eval quaternion_distance device loss_fn tensor range L1Loss model SGD MultiStepLR exists list exp resize_4x4 Adam to_matrix sum GeometricLoss ProposedLoss format param_groups test mkdir join time remove DistancePoints3D log_scalar Translation train Tensor ndarray zeros isinstance ndarray isinstance clone copy Tensor quatmultiply quatinv invert_safe resize_4x4 Translation copy t to_matrix tensor mm clone quat2mat t inverse tvector2mat mm Tensor isinstance Tensor isinstance invert_safe resize_4x4 Translation decompose to_matrix append zeros sqrt zeros norm eye asin atan2 mm quat2mat tvector2mat clone jet max_pool2d expand_dims numpy clip | [![CC BY-NC-SA 4.0][cc-by-sa-shield]][cc-by-sa] ## CMRNet: Camera to LiDAR-Map Registration (IEEE ITSC 2019) ### License This work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License][cc-by-sa]. [![CC BY-SA 4.0][cc-by-sa-image]][cc-by-sa] ### News ##### Check out our new paper "CMRNet++: Map and Camera Agnostic Monocular Visual Localization in LiDAR Maps": * [PDF](https://arxiv.org/abs/2004.13795) * [Demo](http://rl.uni-freiburg.de/research/vloc-in-lidar) * [Video](https://www.youtube.com/watch?v=EUCloC6flr4) | 1,652 |
cavalli1234/AdaLAM | ['outlier detection', 'visual localization'] | ['AdaLAM: Revisiting Handcrafted Outlier Detection', 'Handcrafted Outlier Detection Revisited'] | adalam/ransac.py adalam/adalam.py adalam/__init__.py examples/example.py examples/match_colmap_database_example.py setup.py adalam/core.py adalam/utils.py AdalamFilter adalam_core extract_local_patterns extract_neighborhood_sets select_seeds ransac stable_sort_residuals sample_padded_inliers confidence_based_inlier_selection group_sum_and_cumsum dist_matrix orientation_diff arange_sequence piecewise_arange random_samples_indices batch_2x2_invQ batch_2x2_det batch_2x2_ellipse batch_2x2_inv draw_first_k_couples batch_2x2_Q show_matches extract_keypoints dist_matrix orientation_diff abs unsqueeze sum argsort dtype type where max dist_matrix extract_neighborhood_sets select_seeds ransac min extract_local_patterns pi sqrt stack float numpy prod arange min argsort float max log cumsum cat arange_sequence cumsum unique_consecutive stable_sort_residuals group_sum_and_cumsum repeat_interleave repeat long float max zeros item norm transpose squeeze repeat_interleave sample_padded_inliers unsqueeze draw_first_k_couples batch_2x2_ellipse batch_2x2_inv eye confidence_based_inlier_selection cat expand item t view unique_consecutive expand device item bool empty_like norm clamp sqrt stack unsqueeze int concatenate sqrt stack tensor float rand long SIFT_create IMREAD_COLOR imread array detectAndCompute uint8 line zip resize_horizontal ones waitKey imshow resize | # AdaLAM [AdaLAM: Revisiting Handcrafted Outlier Detection](https://arxiv.org/abs/2006.04250) <img src="media/teaser.jpg" width="1000"/> Local feature matching is a critical component of many computer vision pipelines, including among others Structure-from-Motion, SLAM, and Visual Localization. However, due to limitations in the descriptors, raw matches are often contaminated by a majority of outliers. Filtering outliers is a vital step in any sparse vision pipeline which is based on local feature matching. AdaLAM is a fully handcrafted realtime outlier filter integrating several best practices into a single efficient and effective framework. It detects inliers by searching for significant local affine patterns in image correspondences. AdaLAM proved to be very competitive with recent deep learning methods, taking the second place for the [Image Matching Challenge](https://vision.uvic.ca/image-matching-challenge/) at CVPR 2020 for the 8000 keypoints category. [Here](https://youtu.be/UQ4uJX7UDB8?t=17139) is our invited talk about AdaLAM and the challenge submission. Check our [paper](https://arxiv.org/abs/2006.04250) for details about AdaLAM. In this repository we provide a full pytorch implementation of AdaLAM. We suggest running AdaLAM on a CUDA device for best performance, but CPU execution is possible as well. We also provide an example script to run a COLMAP reconstruction using AdaLAM for matching. The main aim of this repository is to provide a strong classical baseline that can be used easily for comparison purposes. | 1,653 |
cbbjames/Variational-Dropout---ResNet- | ['sparse learning'] | ['Variational Dropout Sparsifies Deep Neural Networks'] | ResNet/lasagne/layers/pool.py ResNet/lasagne/tests/test_regularization.py ResNet/lasagne/layers/conv.py ResNet/lasagne/layers/local.py ResNet/lasagne/tests/layers/test_conv.py ResNet/lasagne/tests/layers/test_helper.py ResNet/lasagne/layers/cuda_convnet.py ResNet/lasagne/layers/helper.py ResNet/lasagne/layers/noise.py ResNet/lasagne/tests/layers/test_dense.py ResNet/lasagne/layers/recurrent.py ResNet/lasagne/tests/layers/test_noise.py ResNet/lasagne/regularization.py ResNet/lasagne/tests/layers/test_local.py ResNet/load_for_flops.py experiments/vgglike/vgglike-ard.py ResNet/lasagne/tests/layers/test_embedding.py ResNet/lasagne/layers/dnn.py ResNet/lasagne/layers/merge.py ResNet/lasagne/tests/layers/test_pool.py ResNet/lasagne/layers/__init__.py experiments/vgglike/vgglike-wot.py RunExperiments.py ResNet/lasagne/tests/layers/test_normalization.py ResNet/lasagne/tests/layers/test_recurrent.py ResNet/lasagne/tests/layers/test_special.py ResNet/lasagne/layers/dense.py ResNet/lasagne/tests/test_theano_extensions.py ResNet/lasagne/tests/layers/test_input.py ResNet/lasagne/init.py experiments/lenet/lenet5-ard.py ResNet/lasagne/layers/normalization.py ResNet/lasagne/tests/test_updates.py ResNet/lasagne/tests/test_utils.py ResNet/read_resnet.py ResNet/lasagne/updates.py ResNet/lasagne/random.py experiments/utils.py ResNet/lasagne/layers/base.py ResNet/lasagne/tests/test_nonlinearities.py ResNet/lasagne/nonlinearities.py ResNet/lasagne/layers/corrmm.py ResNet/lasagne/utils.py data/downloader.py ResNet/lasagne/tests/test_objectives.py ResNet/lasagne/layers/special.py experiments/lenet/lenet300-100-ard.py ResNet/lasagne/__init__.py experiments/lenet/lenet5-wot.py ResNet/lasagne/conftest.py ResNet/lasagne/tests/test_examples.py ResNet/lasagne/theano_extensions/conv.py ResNet/lasagne/layers/input.py ResNet/lasagne/layers/shape.py ResNet/lasagne/objectives.py ResNet/lasagne/tests/layers/conftest.py ResNet/lasagne/tests/test_init.py ResNet/lasagne/tests/conftest.py ResNet/lasagne/tests/layers/test_merge.py data/reader.py ResNet/lasagne/tests/layers/test_shape.py theano_gpu.py ResNet/lasagne/layers/embedding.py ResNet/lasagne/theano_extensions/padding.py ResNet/lasagne/tests/layers/test_base.py download_mnist download_cifar10 download_cifar100 ZCA load load_cifar10_random load_mnist load_mnist_random load_cifar100 load_cifar10 run_experiment get_logging_print build_params_from_init experiment_info save_net net_lenet5 net_lenet5 net_lenet5 net_vgglike conv_bn_rectify net_vgglike conv_bn_rectify pytest_ignore_collect GlorotNormal Sparse Initializer He HeNormal GlorotUniform Normal Constant Orthogonal HeUniform Uniform Glorot tanh softplus SELU linear sigmoid elu softmax ScaledTanH rectify LeakyRectify categorical_crossentropy aggregate squared_error multiclass_hinge_loss categorical_accuracy binary_hinge_loss binary_accuracy align_targets binary_crossentropy set_rng get_rng apply_penalty regularize_network_params regularize_layer_params l1 l2 regularize_layer_params_weighted apply_nesterov_momentum norm_constraint adagrad nesterov_momentum total_norm_constraint momentum sgd apply_momentum rmsprop adam adamax adadelta get_or_compute_grads shared_empty one_hot as_theano_expression floatX compute_norms as_tuple unique inspect_kwargs create_param unroll_scan collect_shared_vars MergeLayer Layer Conv3DLayer conv_output_length Conv2DLayer TransposedConv3DLayer conv_input_length BaseConvLayer DilatedConv2DLayer TransposedConv2DLayer Conv1DLayer Conv2DMMLayer Conv2DCCLayer MaxPool2DCCLayer ShuffleBC01ToC01BLayer ShuffleC01BToBC01Layer NINLayer_c01b DenseLayer NINLayer BatchNormDNNLayer MaxPool2DDNNLayer Pool2DDNNLayer SpatialPyramidPoolingDNNLayer Conv3DDNNLayer MaxPool3DDNNLayer batch_norm_dnn Conv2DDNNLayer Pool3DDNNLayer EmbeddingLayer get_output_shape get_output get_all_params set_all_param_values get_all_param_values count_params get_all_layers InputLayer LocallyConnected2DLayer autocrop_array_shapes ConcatLayer ElemwiseMergeLayer autocrop ElemwiseSumLayer dropout_locations DropoutLayer dropout_channels GaussianNoiseLayer BatchNormLayer LocalResponseNormalization2DLayer batch_norm SpatialPyramidPoolingLayer GlobalPoolLayer Pool3DLayer FeaturePoolLayer pool_3d MaxPool3DLayer Upscale3DLayer pool_output_length Pool2DLayer MaxPool2DLayer Pool1DLayer pool_2d Upscale2DLayer Upscale1DLayer FeatureWTALayer pool_2d_nxn_regions MaxPool1DLayer GRULayer LSTMLayer Gate RecurrentLayer CustomRecurrentLayer FlattenLayer SliceLayer PadLayer DimshuffleLayer ReshapeLayer rrelu TransformerLayer InverseLayer prelu NonlinearityLayer _transform_thin_plate_spline ParametricRectifierLayer _U_func_numpy _meshgrid ScaleLayer TPSTransformerLayer _linspace standardize ExpressionLayer _interpolate BiasLayer _get_transformed_points_tps _initialize_tps RandomizedRectifierLayer _transform_affine pytest_addoption pytest_runtest_setup test_example _example_modules example test_specified_rng test_glorot_1d_not_supported test_he_uniform_c01b_4d_only test_constant test_he_normal_c01b test_glorot_uniform test_glorot_uniform_c01b_4d_only test_shape test_initializer_sample test_he_1d_not_supported test_he_uniform test_he_normal_receptive_field test_sparse_1d_not_supported test_glorot_uniform_gain test_he_normal_c01b_4d_only test_glorot_normal_receptive_field test_glorot_uniform_receptive_field test_he_uniform_c01b test_orthogonal_gain test_he_uniform_receptive_field test_glorot_normal test_glorot_normal_c01b test_uniform_mean_std test_normal test_uniform_range_as_number test_uniform_range_as_range test_orthogonal_1d_not_supported test_glorot_normal_gain test_orthogonal test_sparse test_orthogonal_multi test_glorot_uniform_c01b test_glorot_normal_c01b_4d_only test_he_uniform_gain test_he_normal_gain test_he_normal TestNonlinearities test_aggregate_sum test_binary_hinge_loss test_aggregate_weighted_normalized_sum test_binary_crossentropy test_aggregate_weighted_mean test_squared_error test_aggregate_mean test_aggregate_invalid test_categorical_crossentropy_onehot test_categorial_accuracy_invalid test_aggregate_weighted_sum test_multiclass_hinge_loss_invalid test_categorical_crossentropy test_categorical_accuracy_top_k test_binary_accuracy test_categorical_accuracy test_binary_hinge_loss_sigmoid_predictions test_squared_error_preserve_dtype test_binary_hinge_loss_not_binary_targets test_multiclass_hinge_loss TestRegularizationPenalties TestRegularizationHelpers test_conv_nones test_pad test_conv_pad test_conv test_conv_stride conv1d test_conv_invalid_border_mode test_pad_width_per_border test_pad_width_per_axis test_get_or_compute_grads test_norm_constraint TestUpdateFunctions test_total_norm_constraint test_norm_constraint_dim6_raises test_norm_constraint_norm_axes test_compute_norms_ndim6_raises test_create_param_numpy_bad_shape_raises_error test_create_param_numpy_generic_returns_same test_create_param_bad_callable_raises test_create_param_shared_returns_same test_as_tuple_fails test_inspect_kwargs test_compute_norms test_nonpositive_dims_raises_value_error test_create_param_broadcast_pattern test_create_param_number_returns_same test_create_param_shared_bad_ndim_raises_error test_one_hot test_create_param_callable_returns_shared test_create_param_callable_returns_shared_bad_ndim_raises_error test_create_param_bad_spec_raises test_collect_shared_vars test_shared_empty test_create_param_callable_returns_return_value test_create_param_callable_returns_theano_expr test_as_theano_expression_fails test_compute_norms_axes test_compute_norms_ndim1 test_create_param_accepts_iterable_shape test_compute_norms_type_raises test_create_param_retain_ndarray_dtype test_create_param_callable_returns_wrong_type test_unroll_scan test_create_param_numpy_returns_shared dummy_input_layer TestLayer TestMergeLayer transp_conv2d_test_sets TestShuffleLayers TestConv2DMMLayer dilated_conv2d_test_sets TestDilatedConv2DLayer convNd_test_sets DummyInputLayer TestConv2DCCLayer TestTransposedConv2DLayer conv3d_test_sets dilated_convNd transposed_convNd TestConv1DLayer TestBaseConvLayer convNd test_conv_input_length TestConv2DDNNLayer dilate TestConv3DLayerImplementations TestTransposedConv3DLayer conv2d_test_sets conv1d_test_sets transp_conv3d_test_sets test_conv_output_length TestConv2DLayerImplementations TestNINLayer TestDenseLayer TestNINLayer_c01b test_embedding_1D_input test_embedding_2D_input TestGetOutput_MergeLayer TestGetOutputShape_Layer TestGetOutputShape_InputLayer TestSetAllParamValues TestGetAllLayers TestGetOutput_Layer TestGetAllParamValues TestCountParams TestGetOutput_InputLayer TestGetOutputShape_MergeLayer TestGetAllParams TestInputLayer DummyInputLayer TestLocallyConnected2DLayer channelwise_locally_connected2d locally_connected2d locally_connected2d_test_sets TestElemwiseSumLayer TestAutocrop TestElemwiseMergeLayerMaximum TestElemwiseMergeLayerMul TestConcatLayer TestDropoutLayer TestGaussianNoiseLayer test_dropout_convenience_functions ground_truth_normalizer test_batch_norm_macro ground_truth_normalize_row TestBatchNormLayer TestLocalResponseNormalization2DLayer TestUpscale2DLayer TestMaxPool1DLayer TestMaxPool3DNNLayer max_pool_2d_ignoreborder TestMaxPool2DNNLayer max_pool_1d np_pool_fixed_output_size TestSpatialPyramidPoolingLayer upscale_1d_dilate TestFeaturePoolLayer TestPool3DLayer upscale_3d_dilate upscale_3d_shape upscale_1d np_spatial_pool_kaiming TestMaxPool2DCCLayer upscale_2d_dilate spatial_pool max_pool_3d_ignoreborder upscale_2d upscale_3d TestUpscale1DLayer TestGlobalPoolLayer upscale_2d_shape TestUpscale3DLayer TestFeatureWTALayer max_pool_1d_ignoreborder upscale_1d_shape TestSpatialPyramidPoolingDNNLayer TestMaxPool2DLayer max_pool_2d test_recurrent_nparams test_recurrent_grad_clipping test_lstm_return_final test_gru_unroll_scan_fwd test_lstm_unroll_scan_fwd test_custom_recurrent_init_shape_error test_recurrent_return_shape test_lstm_nparams_peepholes test_lstm_hid_init_layer_eval test_lstm_precompute test_recurrent_nparams_hid_init_layer test_custom_recurrent_non_unique_inputs test_lstm_nparams_no_peepholes test_lstm_grad_clipping test_recurrent_incoming_tuple test_gru_return_final test_recurrent_hid_init_layer_eval test_lstm_grad test_gru_bck test_lstm_passthrough test_lstm_hid_init_mask test_gru_hid_init_layer_eval test_gru_hid_init_mask test_gru_hid_init_layer test_custom_recurrent_arbitrary_shape test_recurrent_name test_gru_variable_input_size test_lstm_variable_input_size test_recurrent_precompute test_lstm_bck test_lstm_nparams_hid_init_layer test_recurrent_unroll_scan_bck test_gru_unroll_scan_bck test_gru_passthrough test_unroll_none_input_error test_CustomRecurrentLayer_child_kwargs test_recurrent_nparams_learn_init test_lstm_hid_init_layer test_recurrent_hid_init_layer test_recurrent_hid_init_mask test_gru_grad test_lstm_return_shape test_recurrent_variable_input_size test_gradient_steps_error test_recurrent_grad test_recurrent_return_final test_lstm_unroll_scan_bck test_gru_precompute test_lstm_nparams_learn_init test_gru_return_shape test_gru_nparams_hid_init_layer test_custom_recurrent_arbitrary_depth test_gru_grad_clipping test_recurrent_bck test_gru_nparams_learn_init_true test_gru_nparams_learn_init_false test_recurrent_unroll_scan_fwd test_slice_layer TestReshapeLayer TestPadLayer TestFlattenLayer TestDimshuffleLayer TestScaleLayer TestNonlinearityLayer TestTransformLayer TestRandomizedRectifierLayer TestInverseLayer test_standardize TestTPSTransformLayer TestBiasLayer TestExpressionLayer TestParametricRectifierLayer conv1d_sd conv1d_md conv1d_unstrided conv1d_mc0 conv1d_sc conv1d_mc1 pad format print call mkdir split call mkdir split call mkdir split download_mnist load_mnist_labels load_mnist_images mean seed len choice ZCA join download_cifar10 load_CIFAR10 copy apply ZCA join copy apply load_CIFAR_batch seed len choice gmtime strftime load format replace set_all_param_values print net_configuration get_functions get_logging_print mkdir arch experiment_info train save_net test_net join print get_all_param_values mkdir save load list zeros_like print name shape append range len InputLayer DenseVarDropOutARD MaxPool2DLayer Conv2DVarDropOutARD ConvLayer DenseLayer BatchNormLayer int NonlinearityLayer Conv2DVarDropOutARD int BatchNormLayer MaxPool2DLayer DenseVarDropOutARD NonlinearityLayer InputLayer conv_bn_rectify ConvLayer DropoutLayer DenseLayer dimshuffle align_targets align_targets log align_targets reshape max to_one_hot ge align_targets argsort shape_padaxis argmax any isinstance OrderedDict zip get_or_compute_grads list get_value OrderedDict shape shared keys zeros sgd list get_value OrderedDict shape shared keys zeros sgd get_value OrderedDict shape sqrt zip shared zeros get_or_compute_grads constant get_value OrderedDict shape sqrt zip shared zeros get_or_compute_grads constant get_value OrderedDict shape sqrt zip shared zeros get_or_compute_grads constant floatX get_value OrderedDict sqrt shape zip shared zeros get_or_compute_grads constant floatX get_value maximum OrderedDict shape zip shared abs zeros get_or_compute_grads sum clip dtype tuple sqr ndim sqrt type range sum dtype sqrt type clip tuple floatX Variable isinstance Variable isinstance max cast append add set tuple ndarray isinstance Variable tuple abs ndim sqrt abs_ sum range asarray ndarray isinstance Variable tuple spec any shared callable list TensorVariable isinstance fn stack append range len isinstance BatchNormDNNLayer getattr identity NonlinearityLayer update appendleft extendleft hasattr popleft input_layers input_layer set add reversed deque append update get_output_for list join isinstance as_theano_expression get_close_matches warn set dict append get_all_layers keys update list isinstance get_output_shape_for dict get_all_layers keys get_all_layers from_iterable get_all_params get_all_params get_all_params set_value zip list slice min ndim as_tensor_variable zip append enumerate len append list zip len tuple getattr range len BatchNormLayer NonlinearityLayer getattr identity max dimshuffle astype pooling_op mean append float max range BiasLayer remove floatX ScaleLayer _meshgrid dimshuffle _interpolate reshape dot shape flatten cast minimum mod arange dimshuffle floatX reshape shape repeat floor cast sum clip cast floatX ones_like dimshuffle concatenate ones reshape dot _meshgrid T dimshuffle _interpolate reshape _get_transformed_points_tps batched_dot dot shape flatten cast tile switch dimshuffle concatenate batched_dot isnan tile sum log vstack linspace log ones transpose shape meshgrid sum prod range _U_func_numpy floatX concatenate astype sqrt tile T inv as_tensor_variable zeros getattr identity getattr identity addoption skip glob join insert addfinalizer main import_module getattr __subclasses__ len sample set_rng get_rng RandomState sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sample sqrt sample reshape vectors floatX astype log matrices binary_crossentropy categorical_crossentropy astype floatX matrices categorical_crossentropy ivector uint8 floatX astype matrix vectors floatX squared_error astype matrices matrix matrix matrix matrix matrix matrix vector ivector floatX astype maximum binary_hinge_loss vector ivector floatX astype maximum binary_hinge_loss vector ivector floatX astype maximum binary_hinge_loss log ivector floatX reshape multiclass_hinge_loss astype zeros matrix max rectify vector ivector floatX astype binary_accuracy ivector floatX categorical_accuracy astype imatrix matrix argmax ivector floatX categorical_accuracy astype imatrix any matrix append convolve floatX ones tensor3 uniform eval conv getattr conv1d floatX ones tensor3 uniform eval conv getattr conv1d floatX ones tensor3 uniform eval conv getattr pad conv1d conv getattr tensor3 conv getattr tensor3 floatX ones tuple eval pad tensor4 floatX ones tuple eval pad tensor4 floatX ones tuple eval pad tensor4 shared scalar get_or_compute_grads norm_constraint function floatX astype apply_update shared norm_constraint function floatX astype apply_update shared shared astype floatX list norm function arange reshape f2 total_norm_constraint flatten assert_array_almost_equal f1 matrix scalar shared_empty randint eval zeros shared astype compute_norms floatX shared astype compute_norms floatX shared astype compute_norms floatX astype floatX empty create_param array array create_param create_param create_param int_ shared array create_param shared array Mock array assert_called_with create_param Mock assert_called_with create_param shared array shared Mock array shared Mock array create_param empty create_param Mock array create_param astype tuple unroll_scan function scalar Mock output_shape shape input_var InputLayer tuple as_tuple ndim pad any zeros sum range zeros tuple tuple as_tuple ndim pad dilate dilate as_tuple ndim random convNd shared random transposed_convNd array shared random transposed_convNd array random dilated_convNd get_output function f astype imatrix InputLayer assert_array_almost_equal EmbeddingLayer array ivector get_output function f astype InputLayer assert_array_almost_equal EmbeddingLayer array shape range zeros shape range zeros channelwise_locally_connected2d random locally_connected2d zeros range ground_truth_normalize_row shape min shape zeros max range object Mock batch_norm list rollaxis set shape array intersection append union range len shape pad zeros max range len zeros range upscale_1d_shape shape zeros upscale_1d_shape shape swapaxes max_pool_1d max_pool_1d_ignoreborder swapaxes max_pool_1d_ignoreborder swapaxes zeros upscale_2d_shape range shape zeros upscale_2d_shape shape zeros upscale_3d_shape range shape zeros upscale_3d_shape shape append tuple max_pool_2d_ignoreborder reshape int shape floor ceil zeros float pool_op range np_pool_fixed_output_size reshape mean append max get_output RecurrentLayer astype eval tensor4 InputLayer get_output RecurrentLayer get_all_params grad mean InputLayer InputLayer RecurrentLayer InputLayer RecurrentLayer get_output RecurrentLayer tensor3 InputLayer matrix DenseLayer InputLayer RecurrentLayer get_output RecurrentLayer tensor3 InputLayer matrix items list get_output set_value RecurrentLayer ones get_value tensor3 dict eval tile matrix InputLayer RecurrentLayer InputLayer RecurrentLayer get_output function Conv2DLayer shape InputLayer CustomRecurrentLayer get_output function Conv2DLayer shape InputLayer CustomRecurrentLayer InputLayer CustomRecurrentLayer Conv2DLayer ConcatLayer InputLayer Conv2DLayer InputLayer get_output tensor3 RecurrentLayer seed get_output RecurrentLayer astype tensor3 eval assert_almost_equal InputLayer get_output RecurrentLayer astype tensor3 eval InputLayer seed get_output RecurrentLayer astype eval assert_almost_equal InputLayer seed get_output RecurrentLayer astype tensor3 eval assert_almost_equal InputLayer seed RecurrentLayer ones astype eval assert_almost_equal InputLayer seed RecurrentLayer astype eval InputLayer LSTMLayer get_output astype eval tensor4 InputLayer LSTMLayer get_output get_all_params grad mean InputLayer InputLayer LSTMLayer InputLayer LSTMLayer InputLayer LSTMLayer LSTMLayer get_output tensor3 InputLayer matrix DenseLayer InputLayer LSTMLayer LSTMLayer get_output tensor3 InputLayer matrix items list LSTMLayer get_output set_value ones get_value tensor3 dict eval tile matrix InputLayer InputLayer LSTMLayer tensor3 get_output seed LSTMLayer get_output astype tensor3 eval assert_almost_equal InputLayer seed LSTMLayer ones astype eval assert_almost_equal InputLayer LSTMLayer get_output astype tensor3 eval InputLayer seed LSTMLayer get_output astype eval assert_almost_equal InputLayer seed LSTMLayer get_output astype tensor3 eval assert_almost_equal InputLayer LSTMLayer get_output floatX Gate astype eval Constant assert_almost_equal InputLayer seed LSTMLayer astype eval InputLayer GRULayer get_output astype eval tensor4 InputLayer GRULayer get_output get_all_params grad mean InputLayer GRULayer InputLayer GRULayer InputLayer GRULayer get_output tensor3 matrix InputLayer DenseLayer InputLayer GRULayer GRULayer list items get_output set_value ones get_value tensor3 dict eval tile matrix InputLayer GRULayer get_output tensor3 matrix InputLayer GRULayer InputLayer get_output tensor3 seed GRULayer get_output astype tensor3 eval assert_almost_equal InputLayer GRULayer get_output astype tensor3 eval InputLayer seed GRULayer get_output astype eval assert_almost_equal InputLayer seed GRULayer get_output astype tensor3 eval assert_almost_equal InputLayer seed GRULayer ones astype eval assert_almost_equal InputLayer GRULayer get_output floatX Gate astype eval Constant assert_almost_equal InputLayer seed GRULayer astype eval InputLayer InputLayer InputLayer Mock get_output InputLayer matrix CustomRecurrentLayer call_args SliceLayer astype eval aeq InputLayer std floatX min astype mean standardize eval InputLayer max conv2d dimshuffle conv2d dimshuffle isinstance conv2d dimshuffle isinstance reshape set_subtensor asarray dimshuffle reshape min stack append zeros range tensordot asarray set_subtensor dimshuffle reshape zeros range tensordot list isinstance slice ones ndim shape zeros enumerate | # Variational Dropout Sparsifies Deep Neural Networks This repo contains the code for the ICML17 paper, [Variational Dropout Sparsifies Deep Neural Networks](https://arxiv.org/abs/1701.05369). *Extension on ResNet* *Fixed the out-dated dependency* ## MNIST Experiments The table containes the comparison of different sparsity-inducing techniques (Pruning (Han et al., 2015b;a), DNS (Guo et al., 2016), SWS (Ullrich et al., 2017)) on LeNet architectures. VD method provides the highest level of sparsity with a similar accuracy | Network | Method | Error | Sparsity per Layer | Compression | | -------------: | -------- | ----- | ------------------- | :--------------: | | | Original | 1.64 | | 1 | | 1,654 |
cchangyou/Santa | ['stochastic optimization'] | ['Bridging the Gap between Stochastic Gradient MCMC and Stochastic Optimization'] | caffe/python/caffe/classifier.py caffe/python/caffe/test/test_net.py rnn_music/eval_music.py rnn_music/data/rnn_results/nott/plot_results_nott.py caffe/tools/extra/resize_and_crop_images.py caffe/examples/pycaffe/caffenet.py rnn_music/eval_music_santa.py caffe/src/caffe/test/test_data/generate_sample_data.py rnn_music/model/gru_layers.py caffe/python/detect.py rnn_music/data/rnn_results/jsb/plot_results_jsb.py caffe/python/caffe/detector.py caffe/python/draw_net.py caffe/examples/finetune_flickr_style/assemble_data.py caffe/tools/extra/extract_seconds.py caffe/python/caffe/test/test_layer_type_list.py caffe/python/caffe/io.py rnn_music/model/optimizers.py caffe/python/caffe/__init__.py caffe/examples/pycaffe/layers/pyloss.py caffe/examples/web_demo/app.py caffe/python/classify.py rnn_music/model/utils.py caffe/python/caffe/draw.py rnn_music/data/rnn_results/piano/plot_results_piano.py rnn_music/model/gru_model.py caffe/scripts/download_model_binary.py caffe/python/caffe/test/test_python_layer_with_param_str.py caffe/tools/extra/parse_log.py caffe/python/caffe/net_spec.py rnn_music/data/rnn_results/muse/plot_results_muse.py caffe/examples/web_demo/exifutil.py caffe/python/caffe/test/test_python_layer.py caffe/python/caffe/test/test_solver.py caffe/scripts/cpp_lint.py caffe/scripts/copy_notebook.py caffe/python/caffe/test/test_io.py caffe/python/caffe/pycaffe.py caffe/python/caffe/test/test_net_spec.py download_image make_net max_pool caffenet conv_relu fc_relu EuclideanLossLayer start_tornado start_from_terminal embed_image_html classify_upload index allowed_file ImagenetClassifier classify_url open_oriented_im apply_orientation main main main parse_args Classifier Detector get_edge_label draw_net get_layer_label get_pydot_graph choose_color_by_layertype get_pooling_types_dict draw_net_to_file Transformer blobproto_to_array datum_to_array array_to_blobproto arraylist_to_blobprotovecor_str array_to_datum resize_image blobprotovector_str_to_arraylist load_image oversample Layers Function Parameters Top NetSpec assign_proto param_name_dict to_proto _Net_blobs _Net_forward_all _Net_set_input_arrays _Net_backward _Net_params _Net_forward _Net_outputs _Net_forward_backward_all _Net_blob_loss_weights _Net_batch _Net_inputs TestBlobProtoToArray TestLayerTypeList simple_net_file TestNet lenet TestNetSpec silent_net anon_lenet exception_net_file parameter_net_file SimpleLayer TestPythonLayer ParameterLayer python_net_file ExceptionLayer SimpleParamLayer TestLayerWithParam python_param_net_file TestSolver ParseNolintSuppressions CheckVlogArguments CheckSectionSpacing FindNextMultiLineCommentEnd ReplaceAll CheckForFunctionLengths _SetOutputFormat _IsTestFilename _VerboseLevel CheckBraces RemoveMultiLineComments ResetNolintSuppressions CheckForNonStandardConstructs _SetVerboseLevel PrintUsage _NestingState CheckIncludeLine CheckAccess _CppLintState Search CheckInvalidIncrement RemoveMultiLineCommentsFromRange CleansedLines CheckForBadCharacters UpdateIncludeState FindPreviousMatchingAngleBracket CheckEmptyBlockBody FindNextMultiLineCommentStart Match _NamespaceInfo CheckMakePairUsesDeduction CheckCheck IsBlankLine _SetFilters ProcessLine _FunctionState CheckPosixThreading GetLineWidth GetHeaderGuardCPPVariable IsCppString _IncludeState CheckSpacing _ClassInfo CheckForCopyright IsErrorSuppressedByNolint ProcessFileData CheckForMultilineCommentsAndStrings CloseExpression _PreprocessorInfo _OutputFormat CheckForIncludeWhatYouUse CheckSpacingForFunctionCall FindEndOfExpressionInLine FindNextMatchingAngleBracket _SetCountingStyle ProcessFile _IncludeError CleanseRawStrings CheckAltTokens CheckForNewlineAtEOF ParseArguments CheckForNonConstReference PrintCategories _Filters main FilesBelongToSameModule CheckCStyleCast FileInfo _BlockInfo CheckForHeaderGuard CheckCaffeDataLayerSetUp ReverseCloseExpression CleanseComments _DropCommonSuffixes _ClassifyInclude CheckStyle CheckCaffeAlternatives FindStartOfExpressionInLine _ShouldPrintError CheckComment Error _GetTextInside CheckLanguage CheckCaffeRandom GetPreviousNonBlankLine reporthook parse_readme_frontmatter model_checks_out valid_dirname get_start_time extract_seconds extract_datetime_from_line get_log_created_year write_csv parse_log fix_initial_nan_learning_rate save_csv_files main parse_args parse_line_for_net_output ResizeCropImagesMapper PILResizeCrop OpenCVResizeCrop unzip zipp calc_negLoglike train_model unzip zipp calc_negLoglike train_model adjustFigAspect adjustFigAspect adjustFigAspect adjustFigAspect decoder_layer param_init_decoder init_params init_tparams build_model Adam SGD RMSprop Santa_r Momentum Santa zipp dropout unzip uniform_weight ortho_weight normal_weight _p zero_bias numpy_floatX get_minibatches_idx imread urlretrieve Convolution InnerProduct Data SoftmaxWithLoss LRN Accuracy max_pool InnerProduct conv_relu fc_relu Dropout get read info load_image classify_image StringIO join replace info secure_filename save filename open_oriented_im classify_image fromarray replace astype save resize StringIO items list listen HTTPServer format print start WSGIContainer update start_tornado add_option OptionParser debug port parse_args ImagenetClassifier forward run hasattr _getexif astype float32 tile apply_orientation open transpose model_def endswith ArgumentParser save mean_file channel_swap output_file dirname expanduser parse_args input_file predict Classifier set_mode_cpu load time isdir print add_argument set_mode_gpu pretrained_model gpu len DataFrame Detector format to_hdf detect_selective_search mean set_index to_csv detect_windows read_csv add_argument ArgumentParser read NetParameter output_image_file rankdir Merge draw_net_to_file items list DESCRIPTOR batch_size str num_output get_pooling_types_dict add_edge get_edge_label list Dot get_layer_label values name choose_color_by_layertype Edge Node bottom append type layer add_node top data array diff shape BlobProto extend flat extend BlobProtoVector ParseFromString BlobProtoVector extend tostring shape Datum flat data len astype float32 tile zoom tuple resize fill empty array concatenate shape tile empty array LayerParameter list NetParameter _to_proto extend Counter OrderedDict values iteritems hasattr isinstance extend add getattr setattr items list layers index set outputs _forward len items list _backward layers inputs index set len items list asarray extend copy next _batch iter forward values len items list asarray backward extend next _batch zip_longest zip iter forward values len ascontiguousarray list concatenate iter num zeros next range values len NamedTemporaryFile str close write data Pooling pool1 conv2 pool2 ip1 relu1 SoftmaxWithLoss Convolution NetSpec DummyData ip2 ReLU InnerProduct label conv1 Pooling SoftmaxWithLoss Convolution DummyData ReLU InnerProduct data NetSpec DummyData Silence data2 error search add group clear compile compile compile SetOutputFormat SetCountingStyle SetFilters _Filters startswith IsErrorSuppressedByNolint _ShouldPrintError write IncrementErrorCount replace append Match group find startswith endswith range error FindNextMultiLineCommentEnd RemoveMultiLineCommentsFromRange FindNextMultiLineCommentStart rstrip find range len FindEndOfExpressionInLine range len FindStartOfExpressionInLine error min search I range len FileInfo RepositoryName sep sub ParseNolintSuppressions error startswith split GetHeaderGuardCPPVariable enumerate error enumerate error len error replace count error find error find error find error find error Search error match InnermostClass replace error escape Match Search error group Search Check error lines Count End group Begin NumLines Match raw_lines range Search error match group error Match group pop group append Search pop group append Search elided replace CheckSpacingForFunctionCall rfind error len group min CloseExpression NumLines sub find CheckComment Match range Search lines_without_raw_strings error group starting_linenum Match range Search error rfind len group ReverseCloseExpression Search Match CloseExpression find error Match CloseExpression find elided error strip group FindEndOfExpressionInLine find Match range CloseExpression len error Match finditer normalize isinstance GetLineWidth int InnermostClass CheckCheck error CheckAltTokens CheckBraces CheckSpacing CheckSectionSpacing CheckEmptyBlockBody CheckAccess GetHeaderGuardCPPVariable lines_without_raw_strings _DropCommonSuffixes RepositoryName match split CheckNextIncludeOrder CanonicalizeAlphabeticalOrder FileInfo error search group SetLastHeader match _ClassifyInclude Match pop end search set append values M rstrip replace CheckCStyleCast error _GetTextInside CheckIncludeLine search group lstrip startswith Match ResetSection Search split rfind error group ReverseCloseExpression lstrip findall Match range Search ReplaceAll error Match Search endswith replace setdefault group search CleanseComments open list FilesBelongToSameModule error search copy sub NumLines FullName keys range error search CheckPosixThreading ParseNolintSuppressions CheckVlogArguments CheckMakePairUsesDeduction CheckCaffeDataLayerSetUp CheckLanguage CheckInvalidIncrement CheckCaffeRandom CheckForNonConstReference check_fn Update CheckForNonStandardConstructs CheckStyle raw_lines CheckForMultilineCommentsAndStrings CheckCaffeAlternatives CheckForFunctionLengths CleansedLines _NestingState CheckForBadCharacters CheckForNewlineAtEOF _IncludeState RemoveMultiLineComments CheckForCopyright ResetNolintSuppressions CheckForHeaderGuard NumLines CheckCompletedBlocks CheckForIncludeWhatYouUse range ProcessLine _FunctionState Error rstrip endswith len write ProcessFileData _SetVerboseLevel range split write exit join write exit _VerboseLevel int getopt _SetOutputFormat set _SetVerboseLevel PrintCategories _SetFilters _OutputFormat PrintUsage _SetCountingStyle split getreader ParseArguments ResetErrorCounts stderr exit verbose_level PrintErrorCounts StreamReaderWriter ProcessFile getwriter int time write flush load join index int rfind datetime split getctime year strip extract_datetime_from_line get_start_time total_seconds strip write get_log_created_year close extract_datetime_from_line open float get_log_created_year compile fix_initial_nan_learning_rate search group OrderedDict append float join basename write_csv print excel parse_log save_csv_files output_dir logfile_path items list set_value OrderedDict items list get_value f_cost arange len function arange SGD Momentum f_grad_shared Adam RMSprop append f_update init_params range zipp format build_model shuffle info time init_tparams savez unzip calc_negLoglike scalar len Santa floatX astype get_size_inches min subplots_adjust uniform_weight zero_bias ortho_weight concatenate dot tanh dimshuffle scan OrderedDict uniform_weight zero_bias param_init_decoder OrderedDict shared list items function sigmoid dot matrix sum decoder_layer binary_crossentropy list function grad sqrt zip append ge sum values list function grad get_value sqrt zip append shared ge sum values list function grad get_value sqrt zip append shared ge sum values list function sqr grad get_value sqrt zip append shared ge sum numpy_floatX values list function ones grad get_value sqrt shape zip append shared ge sum values normal list RandomStreams function ones lt grad get_value sqrt shape zip append shared ge sum numpy_floatX values append range arange shuffle binomial shape svd randn uniform randn zeros | # Santa ## Code for the Santa algorithm for deep learning The Code incldues a MATLAB version for the FNN and CNN, a Python version for the RNN, and an implementation in Caffe for large-scale learning. The algorithm is proposed in the AISTATS 2016 paper "Bridging the Gap between Stochastic Gradient MCMC and Stochastic Optimization". Changyou Chen ([email protected]), 2.24.2016 ## License Please note that this code should be used at your own risk. There is no implied guarantee that it will not do anything stupid. Permission is granted to use and modify the code. ## Usage Please refer to README.pdf for instructions on how to use the code. ## Citing Santa Please cite our AISTATS paper in your publications if it helps your research: | 1,655 |
cdcnjupt/BCANet | ['semantic segmentation'] | ['BiCANet: Bi-directional Contextual Aggregating Network for Image Semantic Segmentation'] | run.py args.py database/reader.py database/helper_cityscapes.py predict.py model/bcanet_mg.py experiment_manager/utils.py demo_infer.py model/utils_mg.py database/helper.py main infer gpu_num prediction_image_create gpu_num main coloring_image_create predict get_model_id chunks train_and_eval gpu_num main numpy_crop_image image_scaling numpy_pad_image compute_confusion_matrix compute_iou compute_iou_each_class random_crop_and_pad_image_and_labels rotate_image_tensor decide_intersection image_mirroring labelid_to_trainid assureSingleInstanceName coloring trainid_to_labelid find_data_path read_labeled_image_list QueueBasedImageReader _read_sbd_image_label_list _read_ade20k_image_label_list _read_cityscapes_image_label_list ImageReader sorted_str_dict prepare_log_dir read_and_arrange_logs PSPNetMG pspnet_with_list conv2d_transpose fully_connected concat input_data conv_bias_relu get_transpose_weights resize_images conv2d_same cast bottleneck_residual_v2 batch_norm relu subsample dropout softmax bottleneck_residual global_avg_pool stride_arr max_pool avg_pool imwrite Saver run_once resize argmax GPUOptions Session run restore COLOR_BGR2RGB shape coloring test_image_size gpu_num PSPNetMG copy ConfigProto build_forward_ops zeros network cvtColor __dict__ print sorted_str_dict weights_ckpt infer visible_gpus imwrite initializer three_convs_beginning prediction_image_create compute_iou trainid_to_labelid compute_iou_each_class image_list Saver run_once resize train_like_in_caffe argmax GPUOptions Session run open str restore new_layer_names num_classes COLOR_BGR2RGB sorted_str_dict shape coloring test_image_size gpu_num range fine_tune_filename start_queue_runners __dict__ PSPNetMG momentum copy mkdir ConfigProto test_subset optimizer build_forward_ops join print compute_confusion_matrix write request_stop Coordinator ms mirror zeros weight_decay_mode network coloring_image_create cvtColor len predict list append max range len str __dict__ trainable_variables initializer get_model_id three_convs_beginning train_max_iter compute_iou image_list Saver save train_like_in_caffe argmax GPUOptions Session run open str restore new_layer_names num_classes name sorted_str_dict new_layers_names len placeholder run_for_eval weight_decay_rate test_image_size append gpu_num range database fine_tune_filename start_queue_runners prepare_log_dir snapshot __dict__ PSPNetMG close momentum weight_decay_rate2 ConfigProto optimizer enumerate build_forward_ops int remove flush join total_seconds print build_train_ops compute_confusion_matrix write float32 now lrn_rate request_stop Coordinator any zeros weight_decay_mode network split train_and_eval to_int32 boolean_mask logical_not round list transpose squeeze matmul shape gather_nd cast append less range sparse_to_dense stack tile minimum reshape float32 greater maximum logical_or dynamic_stitch int32 split resize_images to_int32 multiply squeeze float32 stack cast random_uniform resize_nearest_neighbor expand_dims less cond random_uniform pad_to_bounding_box random_crop concat shape cast set_shape less cond append range pad reshape at where print astype divide range mean float sum diag float sum astype diag shape reshape shape reshape shape zeros reshape array sorted print glob range len print split append open sorted print glob range len path_read_func sorted keys enumerate join mkdir str sorted glob readlines writelines append float open as_list print concat input_data max_pool stack cast int32 append array range len range len range len range len range len random_normal_initializer sqrt xavier_initializer range len as_list range len range len range len len range relu max_pool range conv2d_same len range conv2d_same relu len ceil zeros abs range get_shape value stack add_to_collection constant_initializer get_transpose_weights range len range len range len range len | cdcnjupt/BCANet | 1,656 |
cddlyf/GCANet | ['image dehazing', 'rain removal'] | ['Gated Context Aggregation Network for Image Dehazing and Deraining'] | utils.py GCANet.py test.py GCANet ShareSepConv ResidualBlock SmoothDilatedResidualBlock is_image_file edge_compute make_dataset is_image_file join sorted append walk fill_ abs size new sum | Gated Context Aggregation Network for Image Dehazing and Deraining =======  This is the implementation of our WACV 2019 paper *"Gated Context Aggregation Network for Image Dehazing and Deraining"* by [Dongdong Chen](<http://www.dongdongchen.bid/>), [Mingming He](<https://github.com/hmmlillian>), [Qingnan Fan](<https://fqnchina.github.io/>), *et al.* In this paper, we propose a new end-to-end gated context aggregation network GCANet for image dehazing, in which the smoothed dilated convolution is used to avoid the gridding artifacts and a gated subnetwork is applied to fuse the features of different levels. Experiments show that GCANet can obtain much better performance than all the previous state-of-the-art image dehazing methods both qualitatively and quantitatively  We further apply our proposed GCANet to the image deraining task, which also outperforms previous state-of-the-art image deraining methods and demonstrates its generality.  ## Getting Started This paper is implemented with Pytorch framework. | 1,657 |
cdevin/cpv | ['imitation learning'] | ['Compositional Plan Vectors'] | crafting/gridworld/policies/random_agent.py crafting/gridworld/algorithms/naive_model_experiment.py crafting/gridworld/algorithms/cpv_experiment.py crafting/gridworld/envs/grid_affordance.py crafting/gridworld/algorithms/task_embeddings_networks.py crafting/gridworld/algorithms/composite_models.py crafting/gridworld/envs/__init__.py crafting/gridworld/policies/task_embeddings_policy.py crafting/scripts/collect_composite_trajectories.py crafting/gridworld/algorithms/composite_dataset.py crafting/gridworld/policies/composite_delta_policy.py crafting/scripts/collect_reference_trajectories.py crafting/gridworld/algorithms/TE_experiment.py crafting/gridworld/policies/gridworld_policies.py crafting/gridworld/policies/composite_policy.py crafting/scripts/run_model_multitask_tensorboard.py crafting/gridworld/algorithms/tecnets_images_experiment.py crafting/gridworld/algorithms/models.py IRLDataset CompositeDataset ActionToTensor StateCompositeDataset StateActionToTensor MLP2 CompositeDotModelV3 TaskEmbeddingModel CNN2 NaiveModel save_model v3_loss_function accuracy test g_matching_loss process_data train worker_init_fn layer_init save_model v3_loss_function accuracy test process_data train worker_init_fn CNN MLP2 ImageTaskEmbeddingModel MLP CNN2 StateTaskEmbeddingModel save_model accuracy test process_data train worker_init_fn save_model v3_loss_function accuracy test g_matching_loss process_data train worker_init_fn HammerWorld categorical_sample placeholder_reward LearnedBCPolicy CompositePolicy eval_eatbread sign MakeBreadPolicy GoToObjectPolicy GoToCornerPolicy SimplePickupObjectPolicy eval_pickupsticks MoveOverPolicy ChopTreePolicy eval_gotocorner ChopRockPolicy MoveObjectPolicy eval_gotohouse PickupHammerPolicy eval_choptree eval_buildhouse BuildHousePolicy PickupAxePolicy BaseGridStatePolicy EatBreadPolicy eval_choprock Random PickupSticksPolicy DropObjectPolicy eval_pickuphammer eval_pickupaxe PickupObjectPolicy eval_makebread GoToHousePolicy RandomPolicy LearnedTECNetPolicy eval_counts get_counts_diff eval_counts get_counts_diff get_epoch process_path eval_counts process_path_list run_model get_counts_diff seed triplet_margin_loss to format P v3_loss_function backward print add_scalar step zero_grad get_goal_feat g_matching_loss process_data H item forward enumerate print eval format add_scalar save state_dict data kaiming_normal_ weight constant_ zero_grad control_loss model embedding_loss clock total_loss embed_task cumsum asarray MoveObjectPolicy MoveObjectPolicy MoveObjectPolicy list keys startswith list keys startswith list keys startswith list keys startswith deepcopy list index keys enumerate load join get_counts_diff detach list norm concatenate process_path keys state process_path N eval_counts render append range get_action_from_ref CompositePolicy deepcopy int pretty_render isinstance reshape action_space process_path_list reset get_action step get_counts_diff append isdigit | # Plan Arithmetic: Compositional Plan Vectors for Multi-Task Control [Project webpage](https://sites.google.com/berkeley.edu/compositionalplanvectors/home) This codebase has been tested with python 3.5 and 3.6. To install: clone the repository and run `pip install -r requirements.py` Add the repo to you pythonpath by running `export PYTHONPATH=[path/to/repo/]cpv/crafting:$PYTHONPATH' To generate training data for the crafting environment, run `cd [path/to/repo/]cpv/` `mkdir data` | 1,658 |
cdjhz/multigen | ['text generation'] | ['Language Generation with Multi-Hop Reasoning on Commonsense Knowledge Graph'] | preprocess/find_neighbours.py evaluation/cider/cider.py scripts/add_special_tokens.py evaluation/bleu/bleu_scorer.py evaluation/bleu/bleu.py evaluation/rouge/rouge.py evaluation/meteor/__init__.py evaluation/cider/__init__.py evaluation/meteor/meteor_nltk.py evaluation/meteor/meteor.py evaluation/eval.py scripts/data.py scripts/seq_generator.py evaluation/rouge/__init__.py evaluation/cider/cider_scorer.py evaluation/bleu/__init__.py preprocess/extract_cpnet.py preprocess/filter_triple.py preprocess/graph_construction.py scripts/optimization.py scripts/tokenization_gpt2.py evaluation/eval_story.py scripts/main.py preprocess/ground_concepts_simple.py scripts/dictionary.py scripts/modeling_gpt2.py find_all_keys read_gt eval read_hyp QGEvalCap read _get_ngrams evaluate get_ngram_counter read_reference distinct_ngrams _compute_bleu _distinct_n Bleu precook BleuScorer cook_test cook_refs Cider precook CiderScorer cook_test cook_refs Meteor Meteor my_lcs Rouge extract_english load_merge_relation del_pos filter_directed_triple bfs read_json save_json load_total_concepts load_resources get_edge find_neighbours_frequency load_cpnet process cosine_score_triple save_cpnet load_resources load_matcher lemmatize match_mentioned_concepts read_model_vocab match hard_ground grounding_sentences read_csv normalize_case MHDataset TruncatedDictionary Dictionary _get_ngrams set_seed evaluate build_generator str2list list2str set_log _compute_bleu save_generation generate JsonDumpHelper main train GPT2LMHeadModel Block GPT2DoubleHeadsModel load_tf_weights_in_gpt2 MLP MultiHopGen gelu GPT2PreTrainedModel GPT2Model Attention AdamW WarmupCosineSchedule WarmupCosineWithHardRestartsSchedule WarmupLinearSchedule WarmupConstantSchedule ConstantLRSchedule EnsembleModel SequenceGenerator reorder_encoder_out EnsembleModelWithAlignment SequenceGeneratorWithAlignment bytes_to_unicode get_pairs GPT2Tokenizer defaultdict extend append QGEvalCap enumerate append index update Counter print format get_ngram_counter tuple range Counter len _get_ngrams exp Counter zip float sum range len join list setdefault float sum keys range values len load read list format print read_reference close tqdm zip append open defaultdict tuple split range len get items precook list min append float sum max len list items precook max range len ConfigParser read ConfigParser read pop items list bfs len extend index set tqdm zip append max enumerate get append print add_edge print Graph edges read_gpickle has_edge update items list set dict get_edge zip append keys range values format print tqdm find_neighbours_frequency append len get list append set write_gpickle MultiDiGraph load_resources lemma_ add set lower nlp append tqdm enumerate hard_ground join replace add set nlp vocab read ConfigParser add Matcher match_mentioned_concepts list print loads append keys len upper lower seed manual_seed_all manual_seed setFormatter addHandler StreamHandler Formatter setLevel INFO FileHandler gradient_accumulation_steps model tuple clip_grad_norm_ zero_grad DataLoader DataParallel max_grad_norm output_dir save max evaluate_metrics initialize call logging_steps getattr master_params state_dict format size mean save_pretrained num_train_epochs info fp16 trange item per_gpu_train_batch_size max_steps enumerate int join n_gpu evaluate backward AdamW tqdm parameters WarmupLinearSchedule print_features step train_batch_size len tuple DataLoader output_dir tensor max dev_data_file eval_batch_size exp per_gpu_eval_batch_size len _compute_bleu getattr save_generation eval info test_data_file n_gpu train_data_file build_generator MHDataset print_features makedirs tuple extend tqdm eval DataLoader SequentialSampler enumerate Dictionary SequenceGenerator tokenizer encoder join format output_dir info from_pretrained do_eval resize_token_embeddings warning ArgumentParser device output_dir do_train evaluate_metrics set_seed set_device len device_count parse_args to format init_process_group set_log info fp16 vars train load join n_gpu evaluate model_name_or_path train_data_file add_argument barrier dumps MHDataset bool local_rank makedirs load_variable int format info zip squeeze fullmatch from_numpy getattr list_variables abspath append split index_select list items append list range ord add set | # Language Generation with Multi-hop Reasoning on Commonsense Knowledge Graph ## Introduction This is the pytorch implementation of our paper "*Language Generation with Multi-hop Reasoning on Commonsense Knowledge Graph*". The arxiv version of the paper could be found [here](https://arxiv.org/pdf/2009.11692.pdf). ## Requirements ``` python version >= 3 torch version >= 1.4.0 transformers == 2.8.0 nltk == 3.4.5 | 1,659 |
cdmh/deeplab-public-ver2 | ['semantic segmentation'] | ['DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs'] | python/caffe/io.py python/caffe/test/test_python_layer.py scripts/download_model_binary.py python/caffe/net_spec.py python/caffe/test/test_net.py tools/extra/resize_and_crop_images.py python/draw_net.py python/caffe/test/test_net_spec.py src/caffe/test/test_data/generate_sample_data.py python/caffe/draw.py python/caffe/pycaffe.py tools/extra/extract_seconds.py scripts/cpp_lint.py python/classify.py examples/web_demo/exifutil.py examples/pycaffe/layers/pyloss.py python/caffe/test/test_solver.py python/caffe/classifier.py examples/finetune_flickr_style/assemble_data.py python/caffe/test/test_io.py python/caffe/test/test_python_layer_with_param_str.py tools/extra/parse_log.py python/caffe/__init__.py python/caffe/test/test_layer_type_list.py examples/web_demo/app.py scripts/copy_notebook.py python/caffe/detector.py python/detect.py examples/pycaffe/caffenet.py tools/extra/summarize.py download_image make_net max_pool caffenet conv_relu fc_relu EuclideanLossLayer start_tornado start_from_terminal embed_image_html classify_upload index allowed_file ImagenetClassifier classify_url open_oriented_im apply_orientation main main main parse_args Classifier Detector get_edge_label draw_net get_layer_label get_pydot_graph choose_color_by_layertype get_pooling_types_dict draw_net_to_file Transformer blobproto_to_array datum_to_array array_to_blobproto arraylist_to_blobprotovecor_str array_to_datum resize_image blobprotovector_str_to_arraylist load_image oversample Layers Function Parameters Top NetSpec assign_proto param_name_dict to_proto _Net_blobs _Net_forward_all _Net_set_input_arrays _Net_backward _Net_params _Net_forward _Net_IdNameWrapper _Net_outputs _Net_forward_backward_all _Net_blob_loss_weights _Net_batch _Net_inputs TestBlobProtoToArray TestLayerTypeList simple_net_file TestNet lenet TestNetSpec silent_net anon_lenet exception_net_file parameter_net_file SimpleLayer TestPythonLayer ParameterLayer python_net_file ExceptionLayer SimpleParamLayer TestLayerWithParam python_param_net_file TestSolver ParseNolintSuppressions CheckVlogArguments CheckSectionSpacing FindNextMultiLineCommentEnd ReplaceAll CheckForFunctionLengths _SetOutputFormat _IsTestFilename _VerboseLevel CheckBraces RemoveMultiLineComments ResetNolintSuppressions CheckForNonStandardConstructs _SetVerboseLevel PrintUsage _NestingState CheckIncludeLine CheckAccess _CppLintState Search CheckInvalidIncrement RemoveMultiLineCommentsFromRange CleansedLines CheckForBadCharacters UpdateIncludeState FindPreviousMatchingAngleBracket CheckEmptyBlockBody FindNextMultiLineCommentStart Match _NamespaceInfo CheckMakePairUsesDeduction CheckCheck IsBlankLine _SetFilters ProcessLine _FunctionState CheckPosixThreading GetLineWidth GetHeaderGuardCPPVariable IsCppString _IncludeState CheckSpacing _ClassInfo CheckForCopyright IsErrorSuppressedByNolint ProcessFileData CheckForMultilineCommentsAndStrings CloseExpression _PreprocessorInfo _OutputFormat CheckForIncludeWhatYouUse CheckSpacingForFunctionCall FindEndOfExpressionInLine FindNextMatchingAngleBracket _SetCountingStyle ProcessFile _IncludeError CleanseRawStrings CheckAltTokens CheckForNewlineAtEOF ParseArguments CheckForNonConstReference PrintCategories _Filters main FilesBelongToSameModule CheckCStyleCast FileInfo _BlockInfo CheckForHeaderGuard CheckCaffeDataLayerSetUp ReverseCloseExpression CleanseComments _DropCommonSuffixes _ClassifyInclude CheckStyle CheckCaffeAlternatives FindStartOfExpressionInLine _ShouldPrintError CheckComment Error _GetTextInside CheckLanguage CheckCaffeRandom GetPreviousNonBlankLine reporthook parse_readme_frontmatter model_checks_out valid_dirname get_start_time extract_seconds extract_datetime_from_line get_log_created_year write_csv parse_log fix_initial_nan_learning_rate save_csv_files main parse_args parse_line_for_net_output ResizeCropImagesMapper PILResizeCrop OpenCVResizeCrop print_table printed_len summarize_net main read_net format_param imread urlretrieve Convolution InnerProduct Data SoftmaxWithLoss LRN Accuracy max_pool InnerProduct conv_relu fc_relu Dropout get read info load_image classify_image StringIO join replace info secure_filename save filename open_oriented_im classify_image fromarray replace astype save resize StringIO items list listen HTTPServer format print start WSGIContainer update start_tornado add_option OptionParser debug port parse_args ImagenetClassifier forward run hasattr _getexif astype float32 tile apply_orientation open transpose model_def endswith ArgumentParser save mean_file channel_swap output_file dirname expanduser parse_args input_file predict Classifier set_mode_cpu load time isdir print add_argument set_mode_gpu pretrained_model gpu len DataFrame Detector format to_hdf detect_selective_search mean set_index to_csv detect_windows read_csv add_argument ArgumentParser read NetParameter output_image_file rankdir Merge draw_net_to_file items list DESCRIPTOR batch_size str num_output get_pooling_types_dict add_edge get_edge_label list Dot get_layer_label values name choose_color_by_layertype Edge Node bottom append type layer add_node top data array diff shape BlobProto extend flat extend BlobProtoVector ParseFromString BlobProtoVector extend tostring shape Datum flat data len astype float32 tile zoom tuple resize fill empty array concatenate shape tile empty array LayerParameter list NetParameter _to_proto extend Counter OrderedDict values iteritems hasattr isinstance extend add getattr setattr items list layers index set outputs _forward len items list _backward layers inputs index set len items list asarray extend copy next _batch iter forward values len items list asarray backward extend copy next _batch zip_longest zip iter forward values len ascontiguousarray list concatenate iter zeros next range values len NamedTemporaryFile str close write data Pooling pool1 conv2 pool2 ip1 relu1 SoftmaxWithLoss Convolution NetSpec DummyData ip2 ReLU InnerProduct label conv1 Pooling SoftmaxWithLoss Convolution DummyData ReLU InnerProduct data NetSpec DummyData Silence data2 error search add group clear compile compile compile SetOutputFormat SetCountingStyle SetFilters _Filters startswith IsErrorSuppressedByNolint _ShouldPrintError write IncrementErrorCount replace append Match group find startswith endswith range error FindNextMultiLineCommentEnd RemoveMultiLineCommentsFromRange FindNextMultiLineCommentStart rstrip find range len FindEndOfExpressionInLine range len FindStartOfExpressionInLine error min search I range len FileInfo RepositoryName sep sub ParseNolintSuppressions error startswith split GetHeaderGuardCPPVariable enumerate error enumerate error len error replace count error find error find error find error find error Search error match InnermostClass replace error escape Match Search error group Search Check error lines Count End group Begin NumLines Match raw_lines range Search error match group error Match group pop group append Search pop group append Search elided replace CheckSpacingForFunctionCall rfind error len group min CloseExpression NumLines sub find CheckComment Match range Search lines_without_raw_strings error group starting_linenum Match range Search error rfind len group ReverseCloseExpression Search Match CloseExpression find error Match CloseExpression find elided error strip group FindEndOfExpressionInLine find Match range CloseExpression len error Match finditer normalize isinstance GetLineWidth int InnermostClass CheckCheck error CheckAltTokens CheckBraces CheckSpacing CheckSectionSpacing CheckEmptyBlockBody CheckAccess GetHeaderGuardCPPVariable lines_without_raw_strings _DropCommonSuffixes RepositoryName match split CheckNextIncludeOrder CanonicalizeAlphabeticalOrder FileInfo error search group SetLastHeader match _ClassifyInclude Match pop end search set append values M rstrip replace CheckCStyleCast error _GetTextInside CheckIncludeLine search group lstrip startswith Match ResetSection Search split rfind error group ReverseCloseExpression lstrip findall Match range Search ReplaceAll error Match Search endswith replace setdefault group search CleanseComments open list FilesBelongToSameModule error search copy sub NumLines FullName keys range error search CheckPosixThreading ParseNolintSuppressions CheckVlogArguments CheckMakePairUsesDeduction CheckCaffeDataLayerSetUp CheckLanguage CheckInvalidIncrement CheckCaffeRandom CheckForNonConstReference check_fn Update CheckForNonStandardConstructs CheckStyle raw_lines CheckForMultilineCommentsAndStrings CheckCaffeAlternatives CheckForFunctionLengths CleansedLines _NestingState CheckForBadCharacters CheckForNewlineAtEOF _IncludeState RemoveMultiLineComments CheckForCopyright ResetNolintSuppressions CheckForHeaderGuard NumLines CheckCompletedBlocks CheckForIncludeWhatYouUse range ProcessLine _FunctionState Error rstrip endswith len write ProcessFileData _SetVerboseLevel range split write exit join write exit _VerboseLevel int getopt _SetOutputFormat set _SetVerboseLevel PrintCategories _SetFilters _OutputFormat PrintUsage _SetCountingStyle split getreader ParseArguments ResetErrorCounts stderr exit verbose_level PrintErrorCounts StreamReaderWriter ProcessFile getwriter int time write flush load join index int rfind datetime split getctime year strip extract_datetime_from_line get_start_time total_seconds strip write get_log_created_year close extract_datetime_from_line open float get_log_created_year compile fix_initial_nan_learning_rate search group OrderedDict append float join basename write_csv print excel parse_log save_csv_files output_dir logfile_path NetParameter decay_mult format name lr_mult append print zip len get join str format convolution_param list setdefault param kernel_size map set top bottom append type module layer enumerate print_table filename summarize_net read_net | ## DeepLab v2 ### Introduction DeepLab is a state-of-art deep learning system for semantic image segmentation built on top of [Caffe](http://caffe.berkeleyvision.org). It combines (1) *atrous convolution* to explicitly control the resolution at which feature responses are computed within Deep Convolutional Neural Networks, (2) *atrous spatial pyramid pooling* to robustly segment objects at multiple scales with filters at multiple sampling rates and effective fields-of-views, and (3) densely connected conditional random fields (CRF) as post processing. This distribution provides a publicly available implementation for the key model ingredients reported in our latest [arXiv paper](http://arxiv.org/abs/1606.00915). This version also supports the experiments (DeepLab v1) in our ICLR'15. You only need to modify the old prototxt files. For example, our proposed atrous convolution is called dilated convolution in CAFFE framework, and you need to change the convolution parameter "hole" to "dilation" (the usage is exactly the same). For the experiments in ICCV'15, there are some differences between our argmax and softmax_loss layers and Caffe's. Please refer to [DeepLabv1](https://bitbucket.org/deeplab/deeplab-public/) for details. Please consult and consider citing the following papers: @article{CP2016Deeplab, title={DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs}, author={Liang-Chieh Chen and George Papandreou and Iasonas Kokkinos and Kevin Murphy and Alan L Yuille}, | 1,660 |
cdulhanty/syde672 | ['multiple object tracking'] | ['Simple Online and Realtime Tracking'] | testing-bed.py sort.py sort-lstm.py sort-nonlinear-kf.py LSTMTracker iou convert_lstm_to_bbox Sort convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox convert_bboxs_to_lstm parse_args KalmanBoxTracker iou Sort convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox parse_args KalmanBoxTracker iou Sort convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox parse_args minimum maximum float sqrt array linear_assignment iou concatenate reshape append zeros empty enumerate add_argument ArgumentParser | SORT ===== A simple online and realtime tracking algorithm for 2D multiple object tracking in video sequences. See an example [video here](https://motchallenge.net/movies/ETH-Linthescher-SORT.mp4). By Alex Bewley ### Introduction SORT is a barebones implementation of a visual multiple object tracking framework based on rudimentary data association and state estimation techniques. It is designed for online tracking applications where only past and current frames are available and the method produces object identities on the fly. While this minimalistic tracker doesn't handle occlusion or re-entering objects its purpose is to serve as a baseline and testbed for the development of future trackers. SORT was initially described in an [arXiv tech report](http://arxiv.org/abs/1602.00763). At the time of the initial publication, SORT was ranked the best *open source* multiple object tracker on the [MOT benchmark](https://motchallenge.net/results/2D_MOT_2015/). This code has been tested on Mac OSX 10.10, and Ubuntu 14.04, with Python 2.7 (anaconda). **Note:** A significant proportion of SORT's accuracy is attributed to the detections. | 1,661 |
ceciliaresearch/MixedExample | ['data augmentation', 'image augmentation'] | ['Improved Mixed-Example Data Augmentation'] | train.py resnet_model.py mixed_example.py random_rows first_example random_row_interval random_2x2 random_square random_elems random_pixels noisy_mixup vh_bcplus vh_mixup random_cols random_column_interval vert_concat should_zero_mean mixed_example_data_augmentation mixup mixed_concat horiz_concat bcplus preactivation_block conv2d_fixed_padding batch_norm_relu resnet18 fixed_padding input_fn get_num_classes parse_record record_dataset preprocess_image2 cifar_model_fn main preprocess_image1 random_uniform pow sqrt moments random_uniform as_list constant concat float32 cast random_uniform as_list constant concat float32 cast random_uniform as_list constant concat float32 cast random_uniform as_list int to_float concat reduce_sum random_uniform expand_dims round vert_concat horiz_concat vert_concat horiz_concat as_list py_func as_list concat to_float random_uniform as_list concat to_float random_uniform as_list to_float reduce_mean as_list to_float reduce_mean as_list to_float reduce_mean as_list to_float reduce_mean as_list minimum maximum random_uniform random_normal batch_normalization relu pad fixed_padding conv2d_fixed_padding batch_norm_relu dense preactivation_block transpose identity average_pooling2d flatten conv2d_fixed_padding enumerate print join exit uint8 decode_raw one_hot get_num_classes reshape transpose float32 cast int32 constant resize_image_with_crop_or_pad mixed_example_method float32 reduce_mean cast should_zero_mean random_crop random_flip_left_right partial mixed_example_data_augmentation cache record_dataset shuffle map make_one_shot_iterator get_next repeat prefetch batch get_or_create_global_step batch_size get_num_classes reshape MomentumOptimizer get_collection identity accuracy weight_decay UPDATE_OPS add_n resnet18 argmax piecewise_constant scalar softmax_cross_entropy train_epochs evaluate print Estimator LoggingTensorHook model_dir epochs_per_eval train range exists | # Improved Mixed-Example Data Augmentation This repository provides the code for our paper, *Improved Mixed-Example Data Augmentation*. Code has been tested with TensorFlow version 1.12. ## Usage First, make sure CIFAR-10 or CIFAR-100 has been downloaded and extracted to `cifar10_data/cifar-10-batches-bin` or `cifar100_data/cifar-100-binary`. After that, basic usage is as follows: ``` python train.py --mixed_example_method=vh_mixup --model_dir=cifar10_models/vh_mixup --dataset=cifar10 --weight_decay=1e-4 ``` ## Notes | 1,662 |
cem8301/EmotionDetector | ['facial expression recognition'] | ['Deep Facial Expression Recognition: A Survey'] | saveLightCsv.py model_categorical_light.py testModel.py testModel_forSpecific.py createAndRun str compile Sequential fit add Dense MaxPooling2D save summary Conv2D Flatten Dropout | # EmotionDetector Case Study in Recognition of Emotion from Images Carolyn Mason 4/18/2019 CSCI E-89 Deep Learning Problem: It can take a lot of time to sort through and choose images to share with friends and family. It can also be hard to come back to an album years later and find a specific sets of pictures. Deep learning tools can help speed up this process and pinpoint images of a specific style that you are searching for. This tool is an emotion detector, allowing the user to pick the top ‘X’ images from their photo album. The user can choose from angry, happy, sad, and neutral. Data Sets: Data from Kaggle: https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data | 1,663 |
cf020031308/mad-learning | ['link prediction'] | ['Memory-Associated Differential Learning'] | mad.py logger.py cifar_mnist.py ogbl-ddi.py citations.py weekday.py karate.py MAD gpu batch cpu ip gpu MAD Logger MADGraph sample main gpu MADGraph MAD gpu gen_data MLP list DataLoader range list DataLoader range data runs model batch_size LinkPropPredDataset get_edge_split zero_grad print_statistics xavier_uniform_ ArgumentParser seed list MADGraph Adam epochs from_numpy shape parse_args range eval_steps Evaluator mean manual_seed sample keys backward print add_argument sigmoid randint train step gpu split weekday randperm timedelta append date range len | cf020031308/mad-learning | 1,664 |
cfotache/pytorch_objectdetecttrack | ['multiple object tracking'] | ['Simple Online and Realtime Tracking'] | utils/utils.py utils/datasets.py object_tracker.py utils/parse_config.py models.py sort.py YOLOLayer create_modules Darknet EmptyLayer detect_image KalmanBoxTracker iou Sort convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox parse_args ImageFolder ListDataset parse_data_config parse_model_config compute_ap build_targets bbox_iou_numpy to_categorical weights_init_normal load_classes bbox_iou non_max_suppression pop int YOLOLayer Sequential ZeroPad2d MaxPool2d add_module Conv2d ModuleList EmptyLayer Upsample append BatchNorm2d LeakyReLU sum enumerate unsqueeze_ Variable Compose min type float round minimum maximum float sqrt linear_assignment iou concatenate reshape append zeros empty enumerate add_argument ArgumentParser rstrip strip open startswith append split dict strip split open data normal_ __name__ constant_ concatenate size maximum sum range clamp min max minimum eps expand_dims maximum data sort new squeeze size shape unsqueeze cuda unique bbox_iou append max is_cuda cat enumerate int fill_ FloatTensor ones concatenate size range unsqueeze bbox_iou zeros argmax log | # PyTorch Object Detection and Tracking Object detection in images, and tracking across video frames Full story at: https://towardsdatascience.com/object-detection-and-tracking-in-pytorch-b3cf1a696a98 References: 1. YOLOv3: https://pjreddie.com/darknet/yolo/ 2. Erik Lindernoren's YOLO implementation: https://github.com/eriklindernoren/PyTorch-YOLOv3 3. YOLO paper: https://pjreddie.com/media/files/papers/YOLOv3.pdf 4. SORT paper: https://arxiv.org/pdf/1602.00763.pdf 5. Alex Bewley's SORT implementation: https://github.com/abewley/sort | 1,665 |
cg563/low-frequency-adversarial | ['speech recognition', 'denoising'] | ['Low Frequency Adversarial Perturbation'] | utils.py run_dba_simple.py boundary_attack_simple.py defenses.py boundary_attack adjust_step generate_candidate jpeg_numpy identity jpeg_torch bit_reduction bit_reduction_torch sample_gaussian_torch get_preds invert_normalization sample_gaussian_tf apply_normalization rand cuda view fill_ ones squeeze adjust_step expand_as range generate_candidate get_preds size mean float long transformation int norm print sort clone pow repeat cpu zeros norm mul sample_gaussian_torch clamp size div pow expand_as sum cuda size mean sum cuda range size clone range size clone range data int max Softmax Variable cpu size min Normalize ceil float forward cuda range cat apply_normalization int randn size idct from_numpy zeros numpy pad transpose random_normal idct | This repository contains code for the UAI 2019 paper: Chuan Guo, Jared S. Frank, Kilian Q. Weinberger. Low Frequency Adversarial Perturbation. https://arxiv.org/abs/1809.08758 Our code uses PyTorch (pytorch >= 0.4.1, torchvision >= 0.2.1) with CUDA 9.0 and Python 3.5. Both RGB-BA (original boundary attack) and LF-BA (low frequency boundary attack) are implemented. Before running the code, make sure that the output directory exists (default ./save). Notable options: --defense: Type of transformation defense to evaluate against [none/jpeg/bit] --dct_ratio: Frequency ratio r. Recommend using 1/32 with Hyperband to select from {1/4, 1/8, 1/16, 1/32} To run RGB-BA: ``` | 1,666 |
cgpotts/dynasent | ['sentiment analysis'] | ['DynaSent: A Dynamic Benchmark for Sentiment Analysis'] | test_dataset.py dynasent_models.py dynasent_utils.py DynaSentModel get_dist_of_majority_dists get_label_rating_relationship get_global_worker_dist load_dataset jitter get_adversarial_rate get_label_distribution get_worker_agreement prompt_cmp_plot _format_dist get_fleiss_kappa get_label_model_relationship sample_examples _extra_boxplot_styling vocab_diversity_experiments plot_global_worker_dist plot_worker_agreement estimate_human_precision_recall_f1 sample_short_examples test_no_repeated_sentences test_no_real_mturk_ids test_gold_label_inference test_no_round2_assess_set_repeated_prompts _is_our_anonymized_mturk_id dataset test_no_round2_self_rating test_unique_annotators test_gold_vs_model_assess test_unique_ids test_expected_dataset_size test_expected_sst_dev_size test_no_sentence_overlap test_gold_vs_rating_round1_assess gold_label value_counts Series concat sum fillna DataFrame sum sum get_label_model_relationship rename DataFrame sum append sorted Series list values set_xlabel tight_layout hist savefig set_ylabel DataFrame reset_index sort_values apply sample DataFrame reset_index apply sorted zeros enumerate seed T len shuffle mean precision_recall_fscore_support DataFrame array range append enumerate append items list DataFrame _extra_boxplot_styling ax get_worker_agreement concat lines set_xlabel tight_layout scatter set_ylabel savefig boxplot jitter enumerate values len ax reset_index set_xlabel lines set_ylim tight_layout apply enumerate scatter set_ylabel savefig boxplot jitter _extra_boxplot_styling values len DataFrame values seed list ax set_xlabel apply scatter savefig append jitter range lines tight_layout boxplot _extra_boxplot_styling enumerate items T set_ylabel to_dict len title grid setp suptitle Counter Counter sorted list values list values sum len append defaultdict items list | # DynaSent: Dynamic Sentiment Analysis Dataset DynaSent is an English-language benchmark task for ternary (positive/negative/neutral) sentiment analysis. ## Contents * [Citation](#Citation) * [Dataset files](#dataset-files) * [Quick start](#quick-start) * [Data format](#data-format) * [Models](#models) * [Other files](#other-files) * [License](#license) | 1,667 |
cgsaxner/UB_Segmentation | ['semantic segmentation'] | ['DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs'] | tf_records.py metrics.py networks.py upsampling.py make_tfrecords_dataset.py ResNet_training.py FCN_training.py FCN_testing.py ResNet_testing.py dsc_coeff tnr iou_coeff directed_hausdorff tpr hd_distance FCN upsampled_ResNet _int64_feature write_to_tfrecords _bytes_feature read_and_decode bilinear_upsampling_weights multiply reduce_mean cast reduce_sum ones multiply min dot sqrt append max range max argwhere directed_hausdorff to_float to_float join list imresize print TFRecordWriter write SerializeToString close tostring Example zip append array walk open int read TFRecordReader string_input_producer decode_raw uint8 print reshape grayscale_to_rgb Example ParseFromString stack tf_record_iterator parse_single_example zeros abs range | # Automatic urinary bladder segmentation in CT images using deep learning A framework for urinary bladder segmentation in CT images using deep learning. Contains code to train and test two different deep neural network architectures for semantic segmentation using training and testing data obtained from combined PET/CT scans. ## Requirements To use the framework, you need: 1. [Python](https://www.python.org/download/releases/3.5/) 3.5 with the packages specified in the [requirements.txt](https://github.com/cgsaxner/UB_Segmentation/blob/master/requirements.txt) file 2. [TensorFlow](https://www.tensorflow.org/versions/r1.3/) 1.3 3. [TensorFlow-Slim](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/slim) library ## Data Our networks were trained and tested on the publically available [RIDER Lung PET CT Dataset](https://wiki.cancerimagingarchive.net/display/Public/RIDER+Lung+PET-CT). | 1,668 |
cgtuebingen/Flex-Convolution | ['semantic segmentation'] | ['Flex-Convolution (Million-Scale Point-Cloud Learning Beyond Grid-Worlds)'] | user_ops/test_flex_pooling.py user_ops/test_flex_convolution.py user_ops/misc.py user_ops/__init__.py basic_mnist_3d.py user_ops/profile_flexconv.py layers.py user_ops/test_knn_bruteforce.py example.py user_ops/test_flex_convolution_transpose.py user_ops/test_all.py get_data Model Digit2Cloud knn_bruteforce flex_convolution_transpose _remove_dim KnnBruteforce FlexPooling FlexConvolution FlexConvolutionTranspose flex_convolution flex_pooling VerboseTestCase FakePointCloud FlexConvTest FlexConvTest FlexPoolTest KnnBruteforceTest python_bruteforce _FlexPoolGrad flex_convolution_transpose load_op _FlexDeconvGrad flex_convolution _FlexConvGrad flex_pooling PrefetchDataZMQ BatchData Digit2Cloud Mnist KnnBruteforce FlexPooling FlexConvolution FlexConvolutionTranspose append T pdist squareform join load_op_library print dirname isfile append convert_to_tensor _flex_conv_grad convert_to_tensor _flex_pool_grad convert_to_tensor _flex_deconv_grad | # Flex-Convolution (Million-Scale Point-Cloud Learning Beyond Grid-Worlds) Fabian Groh, Patrick Wieschollek, Hendrik P.A. Lensch  Abstract ------------------- Traditional convolution layers are specifically designed to exploit the natural data representation of images -- a fixed and regular grid. However, unstructured data like 3D point clouds containing irregular neighborhoods constantly breaks the grid-based data assumption. Therefore applying best-practices and design choices from 2D-image learning methods towards processing point clouds are not readily possible. In this work, we introduce a natural generalization flex-convolution of the conventional convolution layer along with an efficient GPU implementation. We demonstrate competitive performance on rather small benchmark sets using fewer parameters and lower memory consumption and obtain significant improvements on a million-scale real-world dataset. Ours is the first which allows to efficiently process 7 million points concurrently. The following figure shows the *raw* network semantic segmentation prediction on a real-world example: <p align="center"> <img src=".github/flexconv.jpg" width="100%"> </p> This repository contains the source code of our FlexConv Layer from our 2018 ACCV paper "Flex-Convolution (Million-Scale Point-Cloud Learning Beyond Grid-Worlds)". <p align="center"> <a href="https://www.youtube.com/watch?v=5ftWmuQXU_s"><img src="./.github/youtube.jpg" width="50%"></a> </p> | 1,669 |
chandanbiswas08/infectracer | ['information retrieval'] | ['Approximate Nearest Neighbour Search on Privacy-aware Encoding of User Locations to Identify Susceptible Infections in Simulated Epidemics'] | build_tree.py tragectory_data_gen.py retrieve_susceptibles.py gpsutils_trajectory.py build_index.py rearrange_user_nn_file.py main main superbit_hyperplanes loadUserMap get_gt loadSecureUserMap save_variables convertToCartesian get_cartesian load_data get_quantized_vec loadusers load_variables rearrange_nn evaluateRecall gram_schmidt evaluateRecall_checkin executeQueries main rand_walk get_user_nn find_nn create_nn_gt create_tragectory_data decode getopt createIndex save_variables load_variables run open superbit_hyperplanes str exit strftime saveIndex format addDataPointBatch close splitlines init int time print loadtxt write now load_data dump fit cos sin append get_cartesian asarray append dict get_cartesian append dict get_cartesian append seed normal norm print exit dot zeros range norm asarray ceil dot append range len norm ceil dot append range len readlines close len open range split str dump print close write open load str print close write open readlines close len write open range split append norm sum any int set append range len int set append range len list process_time evaluateRecall print write close evaluateRecall_checkin flatten knnQuery open kneighbors len get_gt process_time executeQueries exists list seed len range shuffle sample float loadIndex load randint write range str rand_walk close randint range open str len write close rearrange_nn unique find_nn array range open str readline close append open | # Approximate Nearest Neighbour Search on Privacy-aware Encoding of User Locations to Identify Susceptible Infections in Simulated Epidemics In the present national emergency situation of coronavirus pandemic governments of all countries are trying to prevent massive propagation of that virus. To get a success in preventing propagation of the Covid-19 virus many governments have decided to keep the whole country locked down. According to experts, prevention of the spread of the disease can be achieved by quarantining all Covid-19 positive patients, and all those persons who came in contact or closer to these patients within last 15-20 days. Very often it happens that a person who came in close contact with an infected patient hides this information from local administration to avoid quarantine. In this situation, the key problem is finding out who those people are. This repository describes a system that reports all possible cases of proximities of a person with another infected person. We believe that with the availabity of GPS location data of a large number of users, the system can very quickly help finding suspectible people in very quick time (which in the real-life could help in the initiative of imposing quarantine on them and prevent further spread of the disease). ## INFECTRACER A tool to quickly locate a set of susceptible persons given a global database of user check-ins and a set of infected people. ### Extract the data If you want to generate your own data (using a different simulation approach then read the Appendix section). Else to conduct experiments on the provided dataset, simply execute ```bash gunzip data/* wc -l data/* | 1,670 |
chaneeh/SeqGAN_experiment | ['text generation'] | ['SeqGAN: Sequence Generative Adversarial Nets with Policy Gradient'] | alpha_target_lstm.py dataloader.py alpha_sequence.py alpha_rollout.py alpha_discriminator.py alpha_generator.py get_conv_shape highway linear conv2d deconv2d Discriminator int_shape resize_nearest_neighbor upscale Generator ROLLOUT generate_samples_by_rollout_for_dis generate_samples_by_lstm_for_dis generate_samples_by_rollout target_loss main pre_train_epoch generate_samples_by_lstm TARGET_LSTM Gen_Data_loader Dis_dataloader as_list as_list int_shape get_conv_shape int range extend generate generate_prob range extend int get_rollout_samples range extend get_rollout_samples range extend next_batch num_batch append pretrain_loss reset_pointer range run pretrain_step num_batch append next_batch reset_pointer range recovered_reward_for_policy get_rollout_samples Dis_dataloader k_update num_batch Gen_Data_loader Saver create_batches target_loss TARGET_LSTM generate_samples_by_lstm Session ROLLOUT run seed open str Generator array Discriminator pre_train_epoch range format generate_samples_by_rollout_for_dis load_train_data FileWriter close update_params generate_samples_by_lstm_for_dis generate_samples_by_rollout ConfigProto load join int print Variable g_updates write global_variables_initializer next_batch reset_pointer makedirs | # SeqGAN_experiment reference paper: https://arxiv.org/pdf/1609.05473.pdf original code from LantaoYu | 1,671 |
chang-li/MergeDTS | ['information retrieval'] | ['MergeDTS: A Method for Effective Large-Scale Online Ranker Evaluation'] | individual_run.py demo.py dueling_bandits/merge_rucb.py dueling_bandits/self_sparring.py dueling_bandits/sparring_ts.py dueling_bandits/sparring.py dueling_bandits/sparring_exp3.py dueling_bandits/setup.py dueling_bandits/abstract_duel.py dueling_bandits/__init__.py dueling_bandits/rmed.py dueling_bandits/rex3.py dueling_bandits/merge_dts.py dueling_bandits/double_thompson_sampling.py dueling_bandits/multidueling_bandits.py dueling_bandits/relative_thompson_sampling.py init_bandits run_bandits save_results init_bandits run_bandits save_results AbstractDuel my_argmax DoubleThompsonSampling FastBeta MergeDTS my_argmax my_argmin ArmTree my_argmax MergeRUCB my_argmin ArmTree MultiDuelingBandit my_argmax my_argmax RelativeThompsonSampling FastBeta my_argmax Rex3 KLBernoulli my_argmax my_argmin RMED1 SelfSparring my_argmax my_argmax Sparring my_argmax SparringEXP3 my_argmax SparringTS str makedirs close iterations save open permutation save_results cumsum rand iterations save argmax str list default_timer sum range RandomState mkdir scale info float update_scores get_arms zeros len seed | # MergeDTS Li, Chang, Ilya Markov, Maarten de Rijke, and Masrour Zoghi. "Merge Double Thompson Sampling for Large Scale Online Ranker Evaluation." arXiv preprint arXiv:1812.04412 (2018). | 1,672 |
changhuixu/LSTM-sentiment-analysis | ['stochastic optimization'] | ['Adam: A Method for Stochastic Optimization'] | imdbReviews.py imdb.py imdb_bidirectional_lstm.py load_data extract_words build_dict load_data main grab_data seed load endswith close shuffle array zip append max open join rstrip replace words strip translate lower sub maketrans split append len list extract_words chdir getcwd print glob len dict sum keys enumerate values split extract_words chdir getcwd glob split enumerate len remove_unk join dump print build_dict close open grab_data len | # LSTM-sentiment-analysis Due to computationly intensive of LSTM method, we only use two LSTM layes in our classifcation model. These two LSTM layes are bidirectional, which include a forwads LSTM and a backwards LSTM. Feature extraction was done by reading all training reviews and tokenizing all english words, as well as removing stop words using `nltk` package. Training in LSTM RNN contains two steps. First, run the neural network going forward. This sets the cell states. Then, you go backwards computing derivatives. This uses the cell states (what the network knows at a given point in time) to figure out how to change the network's weights. When LSTM updates cell states, we choose to use the default `Adam` optimizer (http://arxiv.org/abs/1412.6980v8), which is a method for Stochastic Optimization. The optimizer minimizes the loss function, which here is the mean square error between expected output and acutal output. input matrix shape is (number of samples x maxlen) `number_of_samples` here is 25000 reviews. All reviews are transform into sequences of word vector. `maxlen` is the max length of each sequence. i.e., if a review has more than `maxlen` words, then this review will be truncated. However, if a review has less than `maxlen` words, then the sequence will pad 0's to make it a regular shape. `max_features` is the dictionary size. The dictionary was created before data feed into LSTM RNN. Dictionary keys are purified words, dictionary values are the indicies, which is from 2 to 90000. Such that, the most frequent word has lowest index value. For those rarely occurred words, their indicies is large. We can use `max_features` to filter out uncommon words. First, keeping the `max_features = 20000`, we tested the effect of `maxlen`, which varied from 25 to 200. | 1,673 |
changyi7231/MEF | ['density estimation'] | ['Generative Flows with Matrix Exponential'] | optim/adam.py models/main.py models/flows.py models/nets.py optim/adamax.py models/utils.py Block ActNorm Conv1x1 CouplingLayer Conv2d Norm ConvBlock get_model test get_dataset get_save_dir compute_loss save sample main train get_optimizer get_init_data Flow Model Sequential postprocess expm unsplit2d preprocess squeeze2d series unsqueeze2d split2d Adam Adamax MultiStepLR DataParallel DataLoader device get_optimizer step_size get_dataset test_epoch lr_decay load_state_dict get_init_data to format sample_epoch test get_save_dir sample train load join print swap get_model model LambdaLR zero_grad compute_loss save bits log str epochs load_state_dict append to rand_like range resume_epoch format test eval preprocess item load join time backward print swap dimension step format print dimension eval log join format makedirs eval to save_image join replace dataset realpath dirname save_dir makedirs hidden_channels levels Model num_flows flow_type num_blocks image_size conv_type join ImageFolder dataset_dir CIFAR10 arange shuffle choice init_batch_size append len Adamax Adam sum join makedirs size view contiguous size view contiguous div mul floor div mul floor int size matmul log2 eye ceil max range size matmul eye | # MEF A PyTorch implementation of Generative Flows with Matrix Exponential. | 1,674 |
chanil1218/DCUnet.pytorch | ['speech enhancement'] | ['Phase-aware Speech Enhancement with Deep Complex U-Net'] | train.py models/layers/istft.py models/layers/complexnn.py utils.py se_dataset.py models/unet.py AudioDataset load_data load_data_list main wSDRLoss load_checkpoint set_logger RunningAverage save_checkpoint Params save_dict_to_json pad2d_as padded_cat Decoder Encoder Unet complex_rayleigh_init ComplexBatchNorm RealConvWrapper ComplexConvWrapper CLeakyReLU ISTFT print listdir append tqdm load list float32 tqdm shape range len bsum mSDRLoss zero_grad model_dir DataLoader unsqueeze save Params cuda write_wav squeeze Adam set_printoptions range AudioDataset state_dict size num_epochs net enumerate join ExponentialLR backward print wSDRLoss tqdm parameters step istft setFormatter getLogger addHandler StreamHandler Formatter setLevel INFO FileHandler join format print copyfile mkdir save load load_state_dict cat pad2d_as rayleigh to tuple cos copy_ shape sin uniform_ float | chanil1218/DCUnet.pytorch | 1,675 |
chaofengc/Face-Sketch | ['style transfer'] | ['Face Sketch Synthesis with Style Transfer using Pyramid Column Feature'] | style_generate.py utils/img_process.py utils/content_model.py train_content_net.py utils/compare_patch.py utils/evaluator.py utils/vgg16_gray.py utils/loss.py evaluate.py generate_result.py sketch_generate.py pred_acc PCA_recognition load_dataset build_feat_function generate_target_style save_train_feat train compare_patch ContentNet Evaluator cal_DOF generate_train get_region_mask deprocess_image preprocess_image abs_loss gram_matrix content_loss total_variation_loss region_loss style_loss VGG16Gray join BORDER_CONSTANT int sorted copyMakeBorder astype shape startswith append imread array walk append argmin sum array print reshape mean shape load_dataset transform enumerate fit VGG16Gray get_out_var function gradients concatenate get_region_mask variable placeholder append zeros range len VGG16Gray generate_train savez astype get_features function get_region_mask variable get_features compare_patch max transpose argmin placeholder conv2d shape expand_dims imread sum range astype square enumerate VGG16Gray reshape dot repeat unravel_index len join concatenate gen_position_map fit Adam load_weights ModelCheckpoint compile ContentNet f_conv set_value cumsum astype append zeros sum GaussianBlur COLOR_RGB2GRAY cvtColor imread transpose resize squeeze astype resize list reversed repeat zeros range cal_DOF join sorted COLOR_BGR2GRAY resize imread listdir array cvtColor square abs dot transpose batch_flatten gram_matrix gram_matrix sum | # Face Sketch Synthesis with Style Transfer using Pyramid Column Feature :warning: **Because Theano is no longer supported, this project cannot run on GPU with latest drivers. You may refer to our latest work about face sketch here: https://github.com/chaofengc/Face-Sketch-Wild.** **[Face Sketch Synthesis with Style Transfer using Pyramid Column Feature, WACV2018](https://cfchen.com/papers/WACV2018_face_sketch_pcf.pdf)** [Chaofeng Chen\*](https://cfchen.com/), [Xiao Tan\*](http://www.xtan.org/), [Kwan-Yee K. Wong](http://i.cs.hku.hk/~kykwong/). (\* equal contribution) This paper addresses the problem of face sketch synthesis. Here is an example <p align="center"> <img src="./test/1.png"> <img src="./result/content/1.png"> <img src="./result/sketch/1.png"> </p> | 1,676 |
chaofengc/Face-Sketch-Wild | ['patch matching'] | ['Semi-Supervised Learning for Face Sketch Synthesis in the Wild'] | train.py utils/logger.py utils/utils.py utils/img_process.py utils/metric.py utils/search_dataset.py test.py utils/face_sketch_data.py data_process/face_rectify.py models/networks.py models/vgg19.py face2sketch_wild.py utils/loss.py models/components.py cmd_option train test rectify_img similarityTransform detect_fiducial_points align_img ConvLayer UpsampleConvLayer ResidualBlock NormLayer DNet SketchNet vgg19 VGG FaceDataset ToTensor Rescale ColorJitter read_img_var subtract_mean_batch save_var_img read_sketch_var Logger total_variation MRFLoss feature_mrf_loss_func feature_mse_loss_func avg_score SSIM FSIM find_photo_sketch_batch select_random_batch get_real_sketch_batch tensorToVar mkdirs extract_patches to_device add_argument ArgumentParser vgg19 zeros_like draw_loss_curve find_photo_sketch_batch mse_crit zero_grad MultiStepLR DNet DataLoader DataParallel Logger save cuda train_data max open seed list compress get_real_sketch_batch meanshift len step Adam epochs MSELoss Dnet feature_mrf_loss_func iterLogUpdate load_state_dict expand_as ceil flayers range state_dict manual_seed_all ones_like subtract_mean_batch format glob size Compose close Gnet resume lr manual_seed total_variation FaceDataset enumerate load join int time backward print write now parameters save_weight_path cpu SketchNet vgg19_weight DataParallel cuda test_dir avg_score read_img_var mkdirs save_var_img load_state_dict format Gnet eval listdir test_gt_dir load join result_dir print test_weight_path SketchNet get_frontal_face_detector predictor shape_predictor append range array detector enumerate estimateRigidTransform tolist cos pi sin append array warpAffine detect_fiducial_points similarityTransform imread array warpAffine detect_fiducial_points similarityTransform imread array load VGG parameters load_state_dict is_available cuda convert resize convert resize transpose convert save resize numpy array view vgg_model sum vgg_model MRFLoss zip get eval array put compare_ssim uint8 astype sorted format FSIM print convert SSIM lower bilateralFilter append MatlabSession listdir array append choice array enumerate load data topk view Variable size type_as unsqueeze append sum array range enumerate append choice array enumerate isinstance makedirs is_available is_available unfold transpose view | # Face Sketch Synthesis in the Wild PyTorch implementation for face sketch synthesis in the wild through semi-supervised learning. Here is an example:  [**Semi-Supervised Learning for Face Sketch Synthesis in the Wild.**](https://arxiv.org/abs/1812.04929) [Chaofeng Chen](https://chaofengc.github.io), [Wei Liu](http://www.visionlab.cs.hku.hk/people.html), [Xiao Tan](http://www.xtan.org/), [Kwan-Yee K. Wong](http://i.cs.hku.hk/~kykwong/). # Getting Started ## Prerequisite - Pytorch 0.3 - torchvision 0.2 - opencv-python | 1,677 |
chaojingduan/Neural-Projection | ['denoising'] | ['3D Point Cloud Denoising via Deep Neural Network based Local Surface Estimation'] | utils/show3d_balls.py pointnet/dataset.py utils/train.py wmp.py pointnet/model.py utils/show_seg.py utils/train_classification.py utils/show_cls.py utils/train_segmentation.py tpe write_xyz wmp pc_weight_epsilon mse chamfer_dist snr PointCloudDataset get_segmentation_classes ShapeNetDataset gen_modelnet_id ModelNetDataset feature_transform_regularizer STN3d PointNetDenseCls PointNetCls PointNetfeat STNkd onmouse showpoints eval snr chamfer_dist mse reshape write cycle zip type open norm log10 mean_squared_error T sum tile min count_nonzero T exp print csr_matrix mean shape sqrt tile sum T asarray todense zeros_like transpose eig tile zeros sum array range deepcopy log10 zeros range len append join sorted listdir unique bmm norm transpose mean cuda is_cuda float imwrite waitKey exit mean imshow render zeros require max batchSize subplots model chamfer_dist snr cuda view transpose savefig quiver range mse zeros enumerate print tqdm npoints numpy len | chaojingduan/Neural-Projection | 1,678 |
chaosallen/IPNV2_pytorch | ['semantic segmentation'] | ['IPN-V2 and OCTA-500: Methodology and Dataset for Retinal Image Segmentation'] | data_process/readData.py options/train_options.py IPN V2_test.py IPN V2_train.py data_process/BatchDataReader.py options/base_options.py IPN V2+_test.py IPN V2+_train.py utils.py options/test_options.py model.py test_net train_net test_net train_net Up IPN_V2 UNet_3Plus PLM DoubleConv OutConv2d Double3DConv Down skip UNet IPN InConv3d OutConv3d check_dir_exist cal_Dice cal_acc BatchDatset BatchDatset_post read_dataset read_dataset_post BaseOptions TestOptions TrainOptions dataroot saveroot val_ids squeeze natsorted from_numpy to imsave test_ids astype data_size eval softmax listdir net load join feature_dir uint8 print zeros numpy batch_size channels zero_grad SGD BatchDatset_post saveroot read_dataset_post max_iteration_post Adam RMSprop read_batch_feature to CrossEntropyLoss range data_size lr net join criterion backward print save_interval_post parameters zeros train step block_size save train_ids modality_filename imread range imresize enumerate array read_dataset block_size max_iteration dataroot val_ids read_batch_random_train train_ids save_interval modality_filename BatchDatset in_channels join print mkdir exists split shape range shape range update join natsorted listdir range len update join listdir natsorted | # IPNV2_pytorch This is an pytorch implementation of "IPN-V2 and OCTA-500: Methodology and Database for Retinal Image Segmentation". # Dataset The dataset OCTA500 is available at: https://ieee-dataport.org/open-access/octa-500. Use this dataset, you need to preprocess the downloaded labels. Two operations are required: 1)Rotate 90 degrees:To align with 3D data. 2)Change the gray value of the label image to:0-background,1-FAZ,(2-RV,if you need). # Related Papers: -Mingchao Li, Yerui Chen, Zexuan Ji, Keren Xie, Songtao Yuan, Qiang Chen, and Shuo Li.“Image projection network: 3D to 2D image segmentation in OCTA images,” IEEE Trans. Med. Imaging, vol. 39, no. 11 pp. 3343-3354, 2020. -Mingchao Li, Yuhan Zhang, Zexuan Ji, Keren Xie, Songtao Yuan, Qinghuai Liu and Qiang Chen. "IPN-V2 and OCTA-500: Methodology and Dataset for Retinal Image Segmentation," arXiv:2012.07261. | 1,679 |
charlenekok/Unity-Technologies-Machine-Learning | ['unity'] | ['Unity: A General Platform for Intelligent Agents'] | ml-agents/mlagents/envs/communicator_objects/environment_parameters_proto_pb2.py ml-agents/tests/trainers/test_trainer_controller.py ml-agents/mlagents/trainers/buffer.py ml-agents/mlagents/envs/communicator_objects/unity_rl_initialization_input_pb2.py ml-agents/mlagents/envs/communicator_objects/brain_parameters_proto_pb2.py ml-agents/tests/envs/test_envs.py ml-agents/mlagents/envs/communicator_objects/__init__.py ml-agents/mlagents/envs/rpc_communicator.py ml-agents/mlagents/trainers/ppo/__init__.py gym-unity/gym_unity/envs/__init__.py ml-agents/mlagents/envs/communicator_objects/agent_action_proto_pb2.py ml-agents/mlagents/trainers/learn.py gym-unity/gym_unity/envs/unity_env.py ml-agents/mlagents/trainers/bc/trainer.py ml-agents/mlagents/trainers/policy.py ml-agents/mlagents/envs/communicator_objects/unity_rl_initialization_output_pb2.py ml-agents/tests/trainers/test_curriculum.py ml-agents/mlagents/trainers/meta_curriculum.py ml-agents/mlagents/trainers/curriculum.py ml-agents/mlagents/trainers/ppo/models.py ml-agents/mlagents/envs/communicator_objects/space_type_proto_pb2.py ml-agents/mlagents/envs/communicator_objects/unity_output_pb2.py ml-agents/mlagents/envs/communicator_objects/unity_input_pb2.py gym-unity/gym_unity/__init__.py ml-agents/mlagents/trainers/ppo/policy.py ml-agents/mlagents/envs/communicator_objects/engine_configuration_proto_pb2.py ml-agents/mlagents/envs/communicator_objects/brain_type_proto_pb2.py ml-agents/mlagents/envs/socket_communicator.py gym-unity/setup.py ml-agents/mlagents/trainers/trainer_controller.py ml-agents/mlagents/envs/communicator_objects/agent_info_proto_pb2.py ml-agents/mlagents/envs/communicator_objects/unity_to_external_pb2_grpc.py ml-agents/tests/trainers/test_ppo.py ml-agents/mlagents/envs/brain.py ml-agents/mlagents/trainers/bc/policy.py ml-agents/tests/trainers/test_bc.py ml-agents/tests/mock_communicator.py ml-agents/mlagents/envs/communicator_objects/unity_message_pb2.py ml-agents/mlagents/trainers/models.py ml-agents/mlagents/trainers/__init__.py ml-agents/mlagents/envs/communicator_objects/resolution_proto_pb2.py ml-agents/mlagents/envs/communicator_objects/unity_to_external_pb2.py ml-agents/mlagents/envs/communicator_objects/unity_rl_input_pb2.py ml-agents/tests/trainers/test_buffer.py ml-agents/mlagents/trainers/trainer.py ml-agents/mlagents/envs/communicator.py ml-agents/setup.py ml-agents/mlagents/envs/communicator_objects/unity_rl_output_pb2.py ml-agents/mlagents/envs/__init__.py ml-agents/mlagents/trainers/bc/__init__.py gym-unity/tests/test_gym.py ml-agents/mlagents/envs/exception.py ml-agents/mlagents/envs/environment.py ml-agents/mlagents/trainers/bc/models.py ml-agents/mlagents/envs/communicator_objects/command_proto_pb2.py ml-agents/mlagents/trainers/exception.py ml-agents/tests/trainers/test_meta_curriculum.py ml-agents/mlagents/trainers/ppo/trainer.py ml-agents/mlagents/envs/communicator_objects/header_pb2.py UnityGymException UnityEnv test_gym_wrapper test_multi_agent BrainInfo BrainParameters Communicator UnityEnvironment UnityException UnityTimeOutException UnityEnvironmentException UnityActionException RpcCommunicator UnityToExternalServicerImplementation SocketCommunicator UnityToExternalServicer UnityToExternalStub add_UnityToExternalServicer_to_server BufferException Buffer Curriculum CurriculumError MetaCurriculumError TrainerError main run_training MetaCurriculum LearningModel Policy UnityPolicyException UnityTrainerException Trainer TrainerController BehavioralCloningModel BCPolicy BehavioralCloningTrainer PPOModel PPOPolicy PPOTrainer get_gae discount_rewards MockCommunicator test_initialization test_reset test_close test_step test_handles_bad_filename test_dc_bc_model test_cc_bc_model test_visual_cc_bc_model test_bc_policy_evaluate dummy_config test_visual_dc_bc_model assert_array test_buffer location default_reset_parameters test_init_curriculum_bad_curriculum_raises_error test_init_curriculum_happy_path test_increment_lesson test_get_config test_init_meta_curriculum_happy_path test_increment_lessons_with_reward_buff_sizes default_reset_parameters MetaCurriculumTest test_increment_lessons measure_vals reward_buff_sizes test_set_all_curriculums_to_lesson_num test_get_config test_set_lesson_nums test_init_meta_curriculum_bad_curriculum_folder_raises_error more_reset_parameters test_rl_functions test_ppo_model_dc_vector_curio test_ppo_model_dc_vector_rnn test_ppo_model_cc_vector_rnn test_ppo_policy_evaluate test_ppo_model_cc_visual dummy_config test_ppo_model_dc_vector test_ppo_model_dc_visual test_ppo_model_cc_visual_curio test_ppo_model_dc_visual_curio test_ppo_model_cc_vector_curio test_ppo_model_cc_vector test_initialization test_initialize_trainers dummy_bc_config dummy_bad_config dummy_config dummy_start test_load_config sample step MockCommunicator UnityEnv step MockCommunicator UnityEnv method_handlers_generic_handler add_generic_rpc_handlers start_learning int str TrainerController int Process getLogger print start info append randint docopt range list zeros_like size reversed range asarray tolist discount_rewards UnityEnvironment close MockCommunicator UnityEnvironment close MockCommunicator reset str local_done print agents step close reset MockCommunicator UnityEnvironment len UnityEnvironment close MockCommunicator reset_default_graph close reset_default_graph reset_default_graph reset_default_graph reset_default_graph flatten list range len get_batch Buffer assert_array append_update_buffer make_mini_batch append reset_agent array range Curriculum Curriculum Curriculum MetaCurriculum assert_has_calls MetaCurriculumTest increment_lessons assert_called_with MetaCurriculumTest increment_lessons assert_called_with assert_not_called MetaCurriculumTest set_all_curriculums_to_lesson_num MetaCurriculumTest dict update MetaCurriculumTest reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph reset_default_graph assert_array_almost_equal array discount_rewards TrainerController | <img src="docs/images/unity-wide.png" align="middle" width="3000"/> <img src="docs/images/image-banner.png" align="middle" width="3000"/> # Unity ML-Agents Toolkit (Beta) **The Unity Machine Learning Agents Toolkit** (ML-Agents) is an open-source Unity plugin that enables games and simulations to serve as environments for training intelligent agents. Agents can be trained using reinforcement learning, imitation learning, neuroevolution, or other machine learning methods through a simple-to-use Python API. We also provide implementations (based on TensorFlow) of state-of-the-art algorithms to enable game developers and hobbyists to easily train intelligent agents for 2D, 3D and VR/AR games. These trained agents can be | 1,680 |
charleschen1015/SemanticParsing | ['semantic parsing', 'time series'] | ['Context-Dependent Semantic Parsing over Temporally Structured Data'] | SPAAC-MLE/main.py SPAAC-MLE/nn.py SeqGenAtt2In/dataset.py SPAAC-RL/misc.py data/artificial/utils.py SPAAC-RL/base_model.py SPAAC-MLE/dataset.py SeqGenAtt2In/nn.py SPAAC-MLE/base_model.py SPAAC-RL/config.py SeqGen/config.py SPAAC-MLE/vocabulary.py SPAAC-RL/nn.py SPAAC-RL/model.py data/artificial/generate.py SeqGenAtt2In/model.py SeqGen/dataset.py SeqGen/vocabulary.py SPAAC-MLE/model.py SPAAC-RL/dataset.py SeqGen/nn.py SeqGenAtt2In/base_model.py SPAAC-RL/main.py SeqGen/model.py SPAAC-RL/vocabulary.py SeqGen/misc.py SeqGenAtt2In/vocabulary.py SPAAC-MLE/config.py SeqGenAtt2In/main.py SeqGen/main.py SeqGenAtt2In/misc.py SPAAC-MLE/misc.py SeqGenAtt2In/config.py SeqGen/base_model.py prepare_tex_file parse_template expand_type BaseModel Config prepare_data read_tex_v2 read_tex DataSet main TopN LogicData Model NN Vocabulary BaseModel Config prepare_data read_tex_v2 read_tex DataSet main TopN LogicData Model NN Vocabulary BaseModel Config prepare_data read_tex_v2 read_tex DataSet main TopN LogicData Model NN Vocabulary BaseModel Config prepare_data read_tex_v2 read_tex DataSet main TopN LogicData Model NN Vocabulary lstrip rstrip partition str rstrip format partition expand_type strip lstrip start eval startswith stop append randint range len eval_dir batch_size save train_file process_sentence max_input_length temp_eval_file test_dir len eval_file array append train_dir temp_train_file Vocabulary DataSet item phase zeros join print test_file max_output_length temp_test_file vocab1_size Config beam_size phase | ## Context-Dependent Semantic Parsing over Temporally Structured Data This repository contains the datasets and code associated with the paper: Charles Chen, and Razvan Bunescu. **_Context-Dependent Semantic Parsing over Temporally Structured Data._** In NAACL 2019 (Oral Presentation) [[Preprint](https://arxiv.org/abs/1905.00245)] [[CameraReady](https://www.aclweb.org/anthology/N19-1360)] # Citation If you use our code in your research, please use the following BibTeX entry: ``` @inproceedings{chen-bunescu-2019-context, title={Context-Dependent Semantic Parsing over Temporally Structured Data}, author={Chen, Charles and Bunescu, Razvan}, | 1,681 |
charwing10/isbi2019miccan | ['mri reconstruction'] | ['MRI Reconstruction via Cascaded Channel-wise Attention Network'] | networks.py utils.py generatekdata.py main.py loss.py gaussiansample Percetual validate KdataDataset AverageMeter save_checkpoint main train outconv MICCANlong Cascade_Block CSE_Block up double_conv UNet down UNetCSE DC_layer MICCAN inconv fspecial_gauss sigtoimage create_window get_rmse gaussian _ssim get_psnr roll SSIM get_ssim int asarray arange tolist delete shuffle choice argwhere unique cdf sum range append len copyfile join save model zero_grad roll floor cri len to update format size gaussiansample avg item int backward print AverageMeter step add_scalar eval AverageMeter validate MultiStepLR DataLoader DataParallel save_checkpoint device savepath seed str Percetual Adam MSELoss load_state_dict nblock append parse_args to MICCAN blocktype range SummaryWriter format epoch KdataDataset gpuid manual_seed is_available join MICCANlong add_scalar print min parameters train step makedirs size abs narrow mean sqrt abs mean exp Tensor Variable contiguous unsqueeze pow conv2d create_window size type_as get_device cuda is_cuda sqrt unsqueeze | # isbi2019miccan ### *MRI Reconstruction via Cascaded Channel-wise Attention Network* *Qiaoying Huang, Dong Yang, Pengxiang Wu, Hui Qu, Jingru Yi, Dimitris Metaxas* [Paper](https://arxiv.org/abs/1810.08229) is accepted by The IEEE International Symposium on Biomedical Imaging (ISBI) 2019 ### Prerequisites python 3.7 Pytorch 1.3 ### Quick start Training: run main function with toy dataset ``` | 1,682 |
chauthehan/CRAFT | ['scene text detection'] | ['Character Region Awareness for Text Detection'] | detect.py test_func.py tools.py load_torch_weights build_vgg_backbone build_efficientnet_backbone Detector make_vgg_block invert_input UpsampleLike upconv build_keras_model compute_input map_to_rgb getBoxes gaussian_2d read combine_line fix_line download_and_verify get_rotated_box warpBox get_rotated_width_height flatten drawAnnotations drawBoxes pad adjust_boxes read_and_fit get_default_cache_dir resize_image augment sha256sum fit astype array array copy threshold zeros_like roll max connectedComponentsWithStats argmin MORPH_RECT shape append minAreaRect range astype copy sqrt dilate int getStructuringElement boxPoints min array Model make_vgg_block build_efficientnet_backbone build_vgg_backbone endswith upconv Model load_weights Input load_torch_weights load list layers isinstance set get_layer Conv2D BatchNormalization set_weights T exp arange reshape min meshgrid max clip len asarray hasattr ndarray isinstance bytearray url imdecode IMREAD_UNCHANGED imread cdist min astype get_rotated_width_height getPerspectiveTransform warpPerspective get_rotated_box join boxPoints astype roll minAreaRect array sorted subplots zip set_yticks drawBoxes imshow set_xticks annotate append array enumerate len append polylines copy augmenter to_deterministic zeros shape max zeros list map resize fit memoryview bytearray sha256 join basename urlretrieve print path get_default_cache_dir makedirs arctan MultiPoint array argsort array | # CRAFT Text detection Hiểu về craft: paper: https://arxiv.org/pdf/1904.01941.pdf # Về dữ liệu: - Synthetic image với nhãn cấp độ ký tự. Chúng ta sẽ tạo heat map để biểu diễn ground truth label là region score (tỉ lệ 1 pixel có là tâm của một ký tự không) và affinity score (Tỷ lệ một ảnh là tâm của 2 ký tự liền kề). Có 3 bước để tạo heatmap: 1) Chuẩn bị 2-dimensional isotropic Gausian map; 2) Tính toán ma trận perspective transform giữa Gaussian map và mỗi box ký tự; 3) Dùng ma trận tìm được để chuyển Gaussian map về hình dạng của box ký tự. Đối với affinity score, ta sẽ vẽ các đường chéo nối các đỉnh đối diện nhau của box ký tự, tạo ra 2 tam giác upper và lower. Và một affinity box sẽ được tạo ra có đỉnh là là tâm của 4 cái tam giác của 2 box ký tự liền kề.  - Weakly-Supervised learning: không giống như synthetic datasets, ảnh thực chỉ có nhãn ở cấp độ từ. Mục tiêu của ta là tạo character box từ mỗi word box này. Khi có một ảnh thực, mô hình tạm thời (đang được train) sẽ dự đoán character region score của các từ đã được cắt ra để tạo ra character-level bouding boxes. Để thể hiện độ tin cậy về dự đoán của mô hình tạm thời, giá trị của confidence map ở mỗi word box sẽ được tính dựa trên tỷ lệ của số lượng ký tự phát hiện được và số lượng ký tự thực tế, điều này sẽ được dùng để tính loss và cập nhật trọng số. Các bước thực hiện: đầu tiên là cắt các word box ra, sau đó dùng model tạm thời để dự đoán region score (heat map), tiếp theo ta sẽ dùng thuật toán watershed để tách các ký tự ra để tạo ra character bounding box. Cuối cùng, tạo độ của các character box sẽ được chuyển lại về tạo độ trong ảnh thực. Pseudo-ground truths cho region score và affinity scỏe sẽ được tạo ra giống như ở bước trên.  Với phương pháp weakly-supervised learning, chúng ta phải train với các pseudo-GTs không hoàn hoản, tức là các nhãn bị sai, điều này dễ dẫn đến đầu ra character regions bị mờ. Để giải quyết điều này, chúng ta sẽ đo đạc chất lượng của pseudo-GTs sử dụng độ dài của mỗi từ ( vì mỗi từ sẽ có nhãn nên ta có thể biết được số ký tự trong từ đó). Với R(w) và l(w) là bounding box region và độ dài của từ của mẫu w. lc(w) là tổng số lượng character được dự đoán, thì độ tự tin Sconf(w) đưuọc tính dựa theo công thức: | 1,683 |
chauthehan/CRNN_OCR_CMND | ['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'] | train.py count_char.py test/test.py pyimagesearch/callbacks.py pyimagesearch/datasets.py create_dic.py prediction.py pyimagesearch/ranked.py build_dataset.py pyimagesearch/ppc.py pyimagesearch/hdf5datasetwriter.py pyimagesearch/preprocessing.py pyimagesearch/fcheadnet.py pyimagesearch/nn.py create_model.py pyimagesearch/io.py config/config.py rotate_bound encode_utf8_string ctc_lambda_func CRNN rotate_bound decode_label fastdecode EpochCheckpoint TrainingMonitor SimpleDatasetLoader FCHeadNet HDF5DatasetWriter HDF5DatasetWriter HDF5DatasetGenerator ShallowNet ResNet LeNet AlexNet FCHeadNet MiniVGGNet MiniGoogleNet ImageToArrayPreprocessor CropPreprocessor MeanPreprocessor PatchPreprocessor ImageToArrayPreprocessor SimplePreprocessor AspectAwarePreprocessor rank5_accuracy rotate_bound encode_utf8_string getRotationMatrix2D int abs range len enumerate enumerate zip | # CRNN_OCR_CMND CRNN là một mạng kết hợp giữa CNN và RNN để xử lý những ảnh chứa các thông tin dạng chuỗi như là chữ viết. Nó chủ yếu được sử dụng cho công nghệ OCR và có các điểm mạnh sau: 1. End-to-end learning 2. Độ dài của nhãn là ngẫu nhiên 3. Không cần các kỹ thuật phát hiện và cắt từng ký tự một Bạn có thể sử dụng CRNN dể OCR, đọc biển số xe, nhận dạng text,.. Phụ thuộc vào dữ liệu của bạn. Tôi sử dụng một phiên bản được chỉnh sửa nhẹ so với bản gốc trong paper https://arxiv.org/abs/1507.05717 khi thêm vào 3 lớp convolutional và đầu vào sẽ là 300 *32 Sử dụng: File dic.txt chứa danh sách các chữ cái tiếng việt, tạo ra từ create_dic.py Command: "python create_dic.py" | 1,684 |
cheind/rgbd-correction | ['gaussian processes'] | ['Spatio-thermal depth correction of RGB-D sensors based on Gaussian Processes in real-time'] | sensor_correction/apps/correct_depth.py sensor_correction/gp_cpu.py sensor_correction/utils.py sensor_correction/apps/create_pandas.py sensor_correction/apps/compare_cpu_gpu.py sensor_correction/apps/depth_from_pattern.py sensor_correction/apps/plot_corrected_depth.py sensor_correction/apps/plot_gp_params_influence.py sensor_correction/apps/preprocess_depth.py sensor_correction/gp_gpu.py sensor_correction/apps/plot_statistics.py sensor_correction/apps/train.py sensor_correction/apps/convert.py sensor_correction/__init__.py sensor_correction/apps/plot_depth_vs_temperature.py GPRegressorStandalone GPRegressor GPRegressorGPU sensor_unproject create_batches mask_outliers crop size camera_rays model_points crop select_data ones shape zeros arange split percentile ravel zeros range dot zeros inv range append empty sensor_unproject concatenate | # Dense RGB-D depth correction in the spatio-thermal domain This repository contains code and data accompanying our work on spatio-thermal depth correction of RGB-D sensors based on Gaussian Processes in real-time.  ## Documentation We provide presentation slides of the ICMV 2017 conference event - [PDF Slides 16:9](etc/rgbd-correction-slides-169.pdf) - [PDF Slides 4:3](etc/rgbd-correction-slides-43.pdf) Our presentation was awarded the prize for ***best oral presentation of the conference***. ## Capture setup Our capture setup consists of a RGB-D sensor looking towards a known planar object. The sensor is coupled with an electronic linear axis to adjust distance. We captured data at distances [40cm, 90cm, 10cm steps] in the temperate range of [25°C, 35°C, 1°C steps]. At each temperature/distance tuple we grabbed 50 images from both RGB and IR (aligned with RGB) sensors. We then created an artificial depth map for all RGB images utilizing the known calibration target in sight. | 1,685 |
chelvanai/Oneshot-Face-Identify | ['multiple object tracking', 'face detection'] | ['Simple Online and Realtime Tracking', 'FaceBoxes: A CPU Real-time Face Detector with High Accuracy'] | App.py face_compare/face_compare.py video_stream.py face_detect/face_detector.py ipcam gen upload video_feed KalmanBoxTracker iou convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox VideoCamera FaceMatch FaceDetector save filename get_frame print VideoCamera minimum maximum float sqrt linear_assignment iou concatenate reshape append zeros empty enumerate | # Oneshot-Face-Identify This project is designed for one shot face identify people in video. ## Face Detection - Face detection model used https://arxiv.org/pdf/1708.05234.pdf - Face identify [one shot learnig] model used https://www.cs.toronto.edu/~ranzato/publications/taigman_cvpr14.pdf - Multi object tracking using SORT algorithm https://arxiv.org/pdf/1602.00763.pdf ## Run - python App.py for [web view] - before run you should download the face compare weight file from the txt file in the folder | 1,686 |
cheng6076/scanner | ['semantic parsing'] | ['Learning Structured Natural Language Representations for Semantic Parsing'] | semantic_parser/kb_simple/post_process.py semantic_parser/model.py semantic_parser/util.py semantic_parser/tables/attention.py semantic_parser/kb_simple/train_ranker.py generic_tree_generator/post_process.py generic_tree_generator/sexp.py semantic_parser/kb_simple/test_ranker.py semantic_parser/tables/tinydb/__init__.py semantic_parser/kb_simple/generate_train_graph_spade.py semantic_parser/kb_simple/layers.py semantic_parser/tables/derivation.py semantic_parser/tables/pre_process.py semantic_parser/kb_simple/executor.py semantic_parser/tables/tinydb/storages.py semantic_parser/pre_process.py semantic_parser/tables/sexp.py semantic_parser/kb_simple/small_kb.py semantic_parser/tables/model.py semantic_parser/derivation.py semantic_parser/kb_simple/generate_train_graph.py semantic_parser/tables/tinydb/executor.py semantic_parser/tables/main.py semantic_parser/kb_simple/misc.py semantic_parser/kb_simple/sempre_evaluation_lib.py semantic_parser/post_process.py semantic_parser/kb_simple/session.py semantic_parser/main.py semantic_parser/tables/db.py semantic_parser/kb_simple/tree.py generic_tree_generator/main.py semantic_parser/tables/layers.py semantic_parser/tables/tree.py semantic_parser/tables/tinydb/middlewares.py semantic_parser/kb_simple/ranker.py semantic_parser/tables/util.py semantic_parser/tables/tinydb/database.py generic_tree_generator/pre_process.py semantic_parser/tables/tinydb/operations.py semantic_parser/kb_simple/sexp.py semantic_parser/kb_simple/pre_process.py semantic_parser/tables/tinydb/utils.py semantic_parser/kb_simple/util.py semantic_parser/tree.py semantic_parser/kb_simple/derivation.py semantic_parser/tables/tinydb/queries.py generic_tree_generator/tree.py generic_tree_generator/layers.py semantic_parser/sexp.py semantic_parser/kb_simple/attention.py semantic_parser/layers.py semantic_parser/kb_simple/loader_ranker.py semantic_parser/attention.py generic_tree_generator/model.py semantic_parser/kb_simple/main.py semantic_parser/kb_simple/model.py semantic_parser/tables/post_process.py NonLinear InitialEmbedding sample RNNSequencePredictor SequencePredictor average BiRNNSequencePredictor BiAttention FFSequencePredictor pick FFAttention BiRNNSequencePredictor_shared Linear train_and_test LSTMParser recover test format_output recover_span recover_level_order recover_pre_order recover_post_order iter_data Vocab load_data recover parse bstrip decode_operand is_int parse_operands is_string convert is_float is_list tokenize parse_list Node Tree test BiAttention threshold_sample attention_output hard_sample hard_select FFAttention_Bernoulli FFAttention soft_average Derivation_b Derivation NonLinear InitialEmbedding RNNSequencePredictor SequencePredictor BiRNNSequencePredictor FFSequencePredictor BiRNNSequencePredictor_shared Linear train_and_test LSTMParser format_output recover recover_bottom_up recover_top_down iter_data Vocab load_data recover parse bstrip decode_operand is_int parse_operands is_string convert is_float is_list tokenize parse_list Node Tree test get_general_nt_action BiAttention threshold_sample attention_output hard_sample hard_select FFAttention_Bernoulli FFAttention soft_average Derivation tokenize KBExecutor convert_graph extract_rel extract_ent graph2lf convert_graph extract_rel extract_ent graph2lf NonLinear InitialEmbedding RNNSequencePredictor SequencePredictor BiRNNSequencePredictor FFSequencePredictor BiRNNSequencePredictor_shared Linear iter_lf_train iter_lf_test load_lf_test load_lf_train is_list is_string LSTMParser recover recover_top_down format_output recover_bottom_up test_postprocess iter_data lf2transitions test_load_sentence load_graph graph2lf extract_rel Vocab load_data get_gold_graph_lf test_load_graph iter_graph compute_oracle_graph extract_ent LogLinear getResults computeF1 write_file_by_result test_ranker train_ranker find_executable_all training_with_denonation find_executable_by_result find_executable write_file write_file_all recover parse bstrip decode_operand is_int parse_operands is_string convert is_float is_list tokenize parse_list ToyKnowledgeBase add_relation test_kb build_simple_kb Node Tree test get_act get_valid_actions_td get_ter_ent get_valid_actions_bu get_general_nt_action get_and get_count get_nt_rel get_aggregation get_ter_rel BiAttention threshold_sample attention_output hard_sample hard_select FFAttention_Bernoulli FFAttention soft_average Derivation NonLinear InitialEmbedding RNNSequencePredictor SequencePredictor BiRNNSequencePredictor FFSequencePredictor BiRNNSequencePredictor_shared Linear train_and_test LSTMParser format_output recover recover_bottom_up recover_top_down iter_data Vocab load_data recover parse bstrip decode_operand is_int parse_operands is_string convert is_float is_list tokenize parse_list Node Tree test get_filter get_operator get_column get_display get_act get_valid_actions_bu get_general_nt_action get_ter get_size get_count get_aggregation get_valid_actions_td get_all DBTable StorageProxy Element Table TinyDB TableExecutor tokenize is_list is_string Middleware CachingMiddleware decrement delete increment Query QueryImpl is_sequence where touch JSONStorage Storage MemoryStorage catch_warning with_metaclass FrozenDict LRUCache freeze npvalue sum list exp save_model model nlayers format_output model_dir exists open str iter_data ter_dim load_model data_dir lstm_dim word_dim nt_dim LSTMParser range update recover format parse close float backward print result_dir order write load_data train epochs attention embedding_file len pop append pop insert pop range append len pop join append print format_output recover_span recover_level_order recover_pre_order recover_post_order join defaultdict print feed_all Vocab shuffle list range len str split rstrip enumerate is_string convert tokenize parse_list pop parse_operands extend append pop decode_operand parse_list is_float is_int construct_from_sexp Tree span list exp npvalue zeros sum len list exp npvalue append sum enumerate len soft_average hard_select hard_sample beam_search train_selection beam_size test_selection pop pop join append append items list replace format append print join open join join list range len list range len print format_output recover_bottom_up print join defaultdict Vocab print join defaultdict print join get_oracle construct_from_sexp Tree shuffle list range len print iter_data load_data print load_graph iter_graph float len float format_output recover enumerate execute recover execute format_output append enumerate recover execute set format_output append enumerate dump write dump write dump write save_model model nlayers build_simple_kb model_dir beam_search iter_graph exists open str ter_dim load_model find_executable_all data_dir lstm_dim word_dim nt_dim LSTMParser range update lf2transitions format parse load_graph close choice train_selection float write_file_all beam_size backward print result_dir order KBExecutor test_selection train epochs attention embedding_file len save_model model data_dir WordNetLemmatizer word_dim LogLinear range update format load_lf_train float iter_lf_train backward print stopwords_file train epochs embedding_file len join load_lf_test load_model result_dir print data_dir close iter_lf_test WordNetLemmatizer test getResults word_dim LogLinear ranker_model_dir open write_file embedding_file stopwords_file feed print ToyKnowledgeBase join get_oracle endswith get_operator get_operator startswith count dirname makedirs isinstance | cheng6076/scanner | 1,687 |
chengaf/DALAUP | ['active learning'] | ['Deep Active Learning for Anchor User Prediction'] | nets.py util.py feature_extract.py model.py extract feature_ex read_edge_pair aup NETA SiameseNetwork NETB Classifier tes_vec calculate_metric init_weights SiameseNetworkDataset val_classifier pop tuple map add set items list sorted concatenate nodes tqdm array pagerank len add_edges_from Graph feature_ex read_edge_pair data_path save_file save restart_probability represent_dim model cos zero_grad gpu_id DataLoader unsqueeze numpy classifier device N val_classifier netb total_anchor seed list StepLR squeeze MSELoss load_state_dict append to range cat state_dict feature_A update tes_vec is_classification detach CrossEntropyLoss feature_B train_ratio choice set init_weights CosineEmbeddingLoss SiameseNetworkDataset lr mse eval lr_step long load int norm Adadelta backward print neta lr_prob represent_epoch parameters classification_epoch cel cpu Tensor train step stop_P len xavier_normal_ normal_ fill_ named_parameters int list calculate_metric set unsqueeze item cosine_similarity len int list calculate_metric set gpu_id eval unsqueeze classifier_net softmax item N to cat len | # DALAUP If you find this method helpful for your research, please cite this paper: ```latex @inproceedings{cheng2019deep, author = {Anfeng Cheng and Chuan Zhou and Hong Yang and Jia Wu and Lei Li and Jianlong Tan and | 1,688 |
chenh1001/Basketball-ML-Unity | ['unity'] | ['Unity: A General Platform for Intelligent Agents'] | ml-agents-envs/mlagents_envs/communicator_objects/capabilities_pb2.py ml-agents/mlagents/trainers/components/reward_signals/curiosity/model.py ml-agents-envs/mlagents_envs/communicator_objects/command_pb2.py ml-agents/mlagents/trainers/cli_utils.py ml-agents/mlagents/trainers/run_experiment.py ml-agents-envs/mlagents_envs/mock_communicator.py ml-agents/mlagents/trainers/policy/__init__.py ml-agents-envs/mlagents_envs/communicator_objects/unity_to_external_pb2.py ml-agents-envs/mlagents_envs/communicator.py gym-unity/gym_unity/envs/__init__.py ml-agents-envs/mlagents_envs/communicator_objects/brain_parameters_pb2.py ml-agents/mlagents/trainers/learn.py ml-agents/mlagents/trainers/tests/test_sampler_class.py ml-agents/mlagents/trainers/meta_curriculum.py ml-agents/mlagents/trainers/tests/test_barracuda_converter.py ml-agents-envs/mlagents_envs/side_channel/raw_bytes_channel.py ml-agents/mlagents/trainers/trainer/trainer.py gym-unity/gym_unity/__init__.py ml-agents-envs/mlagents_envs/side_channel/__init__.py utils/validate_meta_files.py ml-agents/mlagents/trainers/trainer_controller.py ml-agents/mlagents/trainers/components/bc/model.py ml-agents/mlagents/trainers/tests/test_curriculum.py ml-agents/mlagents/trainers/action_info.py ml-agents/mlagents/trainers/tests/test_ppo.py ml-agents/mlagents/tf_utils/__init__.py ml-agents/mlagents/trainers/components/reward_signals/__init__.py ml-agents-envs/setup.py ml-agents-envs/mlagents_envs/side_channel/engine_configuration_channel.py ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_output_pb2.py ml-agents/mlagents/trainers/tests/mock_brain.py ml-agents/mlagents/trainers/tests/test_bcmodule.py ml-agents/mlagents/trainers/tests/test_trainer_controller.py ml-agents-envs/mlagents_envs/side_channel/incoming_message.py ml-agents/mlagents/trainers/components/reward_signals/reward_signal_factory.py ml-agents-envs/mlagents_envs/rpc_utils.py ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_output_pb2.py ml-agents/setup.py ml-agents/tests/yamato/setup_venv.py ml-agents/mlagents/trainers/barracuda.py ml-agents/mlagents/trainers/optimizer/tf_optimizer.py utils/run_markdown_link_check.py ml-agents/mlagents/trainers/env_manager.py ml-agents/mlagents/trainers/ppo/trainer.py ml-agents/mlagents/trainers/policy/policy.py ml-agents-envs/mlagents_envs/communicator_objects/agent_action_pb2.py ml-agents/mlagents/model_serialization.py ml-agents-envs/mlagents_envs/tests/test_rpc_communicator.py ml-agents-envs/mlagents_envs/tests/test_envs.py ml-agents/mlagents/trainers/brain.py utils/validate_inits.py ml-agents-envs/mlagents_envs/side_channel/float_properties_channel.py ml-agents/mlagents/trainers/tests/test_meta_curriculum.py ml-agents/mlagents/trainers/components/reward_signals/curiosity/signal.py ml-agents/mlagents/trainers/simple_env_manager.py ml-agents-envs/mlagents_envs/side_channel/outgoing_message.py ml-agents-envs/mlagents_envs/exception.py ml-agents/mlagents/trainers/curriculum.py ml-agents/mlagents/trainers/tests/test_policy.py ml-agents/mlagents/trainers/trainer/__init__.py ml-agents-envs/mlagents_envs/communicator_objects/unity_message_pb2.py ml-agents/mlagents/trainers/tests/test_learn.py ml-agents/mlagents/trainers/policy/nn_policy.py ml-agents/tests/yamato/scripts/run_gym.py ml-agents-envs/mlagents_envs/communicator_objects/agent_info_pb2.py ml-agents/mlagents/trainers/tests/test_demo_loader.py ml-agents-envs/mlagents_envs/communicator_objects/observation_pb2.py utils/validate_versions.py ml-agents-envs/mlagents_envs/tests/test_rpc_utils.py ml-agents/mlagents/trainers/models.py ml-agents-envs/mlagents_envs/tests/test_timers.py ml-agents/mlagents/trainers/__init__.py ml-agents-envs/mlagents_envs/communicator_objects/custom_reset_parameters_pb2.py ml-agents-envs/mlagents_envs/communicator_objects/agent_info_action_pair_pb2.py ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_input_pb2.py ml-agents/mlagents/trainers/tests/test_nn_policy.py ml-agents-envs/mlagents_envs/timers.py ml-agents/tests/yamato/check_coverage_percent.py ml-agents/mlagents/trainers/tests/test_simple_rl.py ml-agents/mlagents/trainers/exception.py ml-agents/mlagents/trainers/tests/test_distributions.py gym-unity/gym_unity/tests/test_gym.py utils/make_readme_table.py ml-agents/mlagents/tf_utils/tf.py ml-agents/mlagents/trainers/tests/test_ghost.py ml-agents/mlagents/trainers/buffer.py ml-agents-envs/mlagents_envs/side_channel/side_channel.py ml-agents-envs/mlagents_envs/side_channel/environment_parameters_channel.py ml-agents/mlagents/trainers/tests/test_subprocess_env_manager.py ml-agents/mlagents/trainers/subprocess_env_manager.py ml-agents/mlagents/trainers/tensorflow_to_barracuda.py ml-agents/mlagents/trainers/agent_processor.py ml-agents-envs/mlagents_envs/communicator_objects/engine_configuration_pb2.py ml-agents/mlagents/trainers/tests/test_rl_trainer.py ml-agents-envs/mlagents_envs/rpc_communicator.py ml-agents-envs/mlagents_envs/communicator_objects/demonstration_meta_pb2.py ml-agents-envs/mlagents_envs/__init__.py gym-unity/setup.py ml-agents/mlagents/trainers/behavior_id_utils.py ml-agents/mlagents/trainers/sac/network.py ml-agents/mlagents/trainers/distributions.py ml-agents/mlagents/trainers/policy/tf_policy.py ml-agents/mlagents/trainers/optimizer/__init__.py ml-agents/mlagents/trainers/tests/simple_test_envs.py ml-agents/mlagents/trainers/tests/__init__.py ml-agents-envs/mlagents_envs/communicator_objects/unity_output_pb2.py ml-agents-envs/mlagents_envs/communicator_objects/space_type_pb2.py ml-agents/mlagents/trainers/trainer_util.py ml-agents/mlagents/trainers/tests/test_trainer_util.py ml-agents-envs/mlagents_envs/logging_util.py ml-agents/mlagents/trainers/components/reward_signals/extrinsic/signal.py ml-agents/mlagents/trainers/sac/trainer.py ml-agents/mlagents/trainers/sampler_class.py ml-agents/tests/yamato/training_int_tests.py ml-agents/mlagents/trainers/tests/test_sac.py ml-agents/mlagents/trainers/trajectory.py ml-agents/mlagents/trainers/ppo/optimizer.py ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_input_pb2.py ml-agents-envs/mlagents_envs/base_env.py ml-agents-envs/mlagents_envs/communicator_objects/header_pb2.py ml-agents/mlagents/trainers/tests/test_stats.py ml-agents/mlagents/trainers/components/reward_signals/gail/model.py ml-agents/mlagents/trainers/tests/test_reward_signals.py ml-agents-envs/mlagents_envs/side_channel/stats_side_channel.py ml-agents/mlagents/trainers/components/reward_signals/gail/signal.py ml-agents-envs/mlagents_envs/tests/test_side_channel.py ml-agents/mlagents/trainers/ghost/controller.py ml-agents/mlagents/trainers/sac/optimizer.py ml-agents/tests/yamato/standalone_build_tests.py ml-agents-envs/mlagents_envs/environment.py ml-agents/mlagents/trainers/demo_loader.py ml-agents/mlagents/trainers/ghost/trainer.py ml-agents/tests/yamato/editmode_tests.py ml-agents/mlagents/trainers/components/bc/module.py ml-agents-envs/mlagents_envs/communicator_objects/unity_input_pb2.py ml-agents/mlagents/trainers/tests/test_buffer.py ml-agents/mlagents/trainers/trainer/rl_trainer.py ml-agents/mlagents/trainers/tests/test_agent_processor.py ml-agents-envs/mlagents_envs/communicator_objects/unity_to_external_pb2_grpc.py ml-agents/mlagents/trainers/brain_conversion_utils.py ml-agents/tests/yamato/yamato_utils.py ml-agents/tests/yamato/scripts/run_llapi.py ml-agents/mlagents/trainers/stats.py ml-agents/mlagents/trainers/tests/test_trajectory.py ml-agents/mlagents/trainers/optimizer/optimizer.py VerifyVersionCommand UnityGymException ActionFlattener UnityToGymWrapper create_mock_vector_steps test_gym_wrapper create_mock_group_spec test_branched_flatten setup_mock_unityenvironment test_gym_wrapper_visual VerifyVersionCommand _get_frozen_graph_node_names export_policy_model _make_onnx_node_for_constant _make_frozen_graph _get_output_node_names _get_input_node_names convert_frozen_to_onnx _enforce_onnx_conversion SerializationSettings _process_graph set_warnings_enabled generate_session_config ActionInfo AgentManager AgentProcessor AgentManagerQueue BarracudaWriter fuse print_known_operations compress Build sort lstm write fuse_batchnorm_weights trim mean gru Model summary Struct parse_args to_json rnn BehaviorIdentifiers create_name_behavior_id BrainParameters CameraResolution get_global_agent_id behavior_spec_to_brain_parameters BufferException AgentBuffer StoreConfigFile DetectDefault DetectDefaultStoreTrue Curriculum make_demo_buffer write_demo get_demo_files load_demonstration write_delimited demo_to_buffer OutputDistribution DiscreteOutputDistribution MultiCategoricalDistribution GaussianDistribution EnvManager EnvironmentStep SamplerException TrainerConfigError CurriculumError TrainerError MetaCurriculumError CurriculumLoadingError UnityTrainerException CurriculumConfigError RunOptions write_timing_tree create_sampler_manager create_environment_factory parse_command_line write_run_options run_training try_create_meta_curriculum run_cli main _create_parser get_version_string MetaCurriculum EncoderType NormalizerTensors ModelUtils LearningRateSchedule main parse_command_line MultiRangeUniformSampler UniformSampler SamplerFactory SamplerManager GaussianSampler Sampler SimpleEnvManager StatsWriter StatsSummary ConsoleWriter StatsReporter GaugeWriter TensorboardWriter StatsPropertyType CSVWriter worker EnvironmentResponse EnvironmentRequest UnityEnvWorker StepResponse SubprocessEnvManager EnvironmentCommand get_layer_shape pool_to_HW flatten sqr_diff process_layer process_model get_layer_rank slow_but_stable_topological_sort get_attr basic_lstm ModelBuilderContext order_by get_epsilon get_tensor_dtype replace_strings_in_list debug embody by_op get_tensor_dims strided_slice remove_duplicates_from_list axis_to_barracuda by_name locate_actual_output_node convert strides_to_HW get_tensor_data very_slow_but_stable_topological_sort gru TrainerController handle_existing_directories initialize_trainer _load_config assemble_curriculum_config TrainerFactory load_config AgentExperience Trajectory SplitObservations BCModel BCModule create_reward_signal RewardSignal CuriosityModel CuriosityRewardSignal ExtrinsicRewardSignal GAILModel GAILRewardSignal GhostController GhostTrainer Optimizer TFOptimizer NNPolicy Policy TFPolicy UnityPolicyException PPOOptimizer PPOTrainer get_gae discount_rewards SACPolicyNetwork SACTargetNetwork SACNetwork SACOptimizer SACTrainer create_mock_pushblock_brain create_steps_from_brainparams simulate_rollout make_brain_parameters setup_mock_brain make_fake_trajectory create_mock_banana_brain create_mock_steps create_mock_brainparams create_mock_3dball_brain RecordEnvironment clamp SimpleEnvironment MemoryEnvironment test_end_episode test_agent_deletion test_agent_manager_queue test_agentprocessor test_agent_manager test_agent_manager_stats create_mock_brain create_mock_policy test_barracuda_converter test_policy_conversion dummy_config test_bcmodule_rnn_update test_bcmodule_update test_bcmodule_constant_lr_update ppo_dummy_config test_bcmodule_dc_visual_update create_bc_module test_bcmodule_defaults test_bcmodule_rnn_dc_update test_buffer_sample construct_fake_buffer test_num_experiences assert_array fakerandint test_buffer test_buffer_truncate test_curriculum_load_invalid_json default_reset_parameters test_load_bad_curriculum_file_raises_error test_curriculum_load_missing_file test_get_parameters test_init_curriculum_happy_path test_increment_lesson test_curriculum_load_good test_unsupported_version_raises_error test_load_demo test_demo_mismatch test_edge_cases test_load_demo_dir test_multicategorical_distribution test_tanh_distribution dummy_config test_gaussian_distribution test_load_and_set dummy_config test_publish_queue test_process_trajectory basic_options test_run_training test_yaml_args test_sampler_configs test_bad_env_path test_commandline_args test_env_args test_increment_lessons_with_reward_buff_sizes test_increment_lessons measure_vals reward_buff_sizes test_set_all_curriculums_to_lesson_num test_get_config test_set_lesson_nums test_simple_metacurriculum test_curriculum_config test_min_visual_size test_load_save create_policy_mock test_normalization dummy_config test_policy_evaluate _compare_two_policies basic_mock_brain test_take_action_returns_action_info_when_available basic_params test_take_action_returns_nones_on_missing_values test_take_action_returns_empty_with_no_agents FakePolicy test_trainer_increment_step test_trainer_update_policy test_ppo_optimizer_update test_ppo_optimizer_update_curiosity test_process_trajectory test_rl_functions test_add_get_policy test_bad_config _create_fake_trajectory _create_ppo_optimizer_ops_mock dummy_config test_ppo_optimizer_update_gail test_ppo_get_value_estimates test_gail_dc_visual sac_dummy_config reward_signal_update reward_signal_eval test_extrinsic test_curiosity_cc test_gail_rnn test_gail_cc ppo_dummy_config test_curiosity_dc curiosity_dummy_config test_curiosity_visual test_curiosity_rnn create_optimizer_mock gail_dummy_config FakeTrainer create_rl_trainer dummy_config test_rl_trainer create_mock_brain test_advance test_clear_update_buffer test_sac_update_reward_signals test_add_get_policy test_bad_config create_sac_optimizer_mock test_sac_optimizer_update dummy_config test_advance test_sac_save_load_buffer test_empty_samplers sampler_config_1 check_value_in_intervals incorrect_uniform_sampler test_incorrect_sampler test_sampler_config_1 sampler_config_2 incorrect_sampler_config test_incorrect_uniform_sampler test_sampler_config_2 test_simple_ghost_fails test_gail test_visual_advanced_sac _check_environment_trains test_visual_sac test_2d_ppo generate_config test_simple_sac default_reward_processor test_simple_ghost test_simple_asymm_ghost test_gail_visual_ppo test_simple_ppo test_gail_visual_sac test_recurrent_ppo DebugWriter test_recurrent_sac test_simple_asymm_ghost_fails test_visual_advanced_ppo test_visual_ppo test_2d_sac simple_record test_tensorboard_writer test_stat_reporter_add_summary_write test_tensorboard_writer_clear test_gauge_stat_writer_sanitize ConsoleWriterTest test_csv_writer test_stat_reporter_property MockEnvWorker mock_env_factory SubprocessEnvManagerTest test_subprocess_env_raises_errors create_worker_mock test_subprocess_env_endtoend test_initialization_seed test_start_learning_trains_until_max_steps_then_saves basic_trainer_controller trainer_controller_with_take_step_mocks test_advance_adds_experiences_to_trainer_and_trains trainer_controller_with_start_learning_mocks test_start_learning_trains_forever_if_no_train_model test_initialize_ppo_trainer test_handles_no_default_section test_assemble_curriculum_config test_load_config_invalid_yaml test_initialize_invalid_trainer_raises_exception dummy_bad_config dummy_config test_load_config_missing_file test_load_config_valid_yaml test_existing_directories test_initialize_trainer_parameters_override_defaults test_raise_if_no_config_for_brain dummy_config_with_override test_trajectory_to_agentbuffer test_split_obs np_zeros_no_float64 np_array_no_float64 _check_no_float64 np_ones_no_float64 RLTrainer Trainer main check_coverage main clean_previous_results TestResults parse_results main main main run_training override_config_file init_venv get_unity_executable_path override_legacy_config_file get_base_path run_standalone_build checkout_csharp_version undo_git_checkout get_base_output_path test_closing test_run_environment test_closing test_run_environment VerifyVersionCommand ActionType TerminalStep DecisionSteps BehaviorSpec TerminalSteps BaseEnv DecisionStep Communicator UnityEnvironment UnityCommunicatorStoppedException UnityObservationException UnityWorkerInUseException UnityException UnityCommunicationException UnityTimeOutException UnitySideChannelException UnityEnvironmentException UnityActionException get_logger set_log_level MockCommunicator RpcCommunicator UnityToExternalServicerImplementation _generate_split_indices process_pixels behavior_spec_from_proto _raise_on_nan_and_inf observation_to_np_array steps_from_proto _process_vector_observation _process_visual_observation _get_thread_timer TimerNode merge_gauges hierarchical_timer add_metadata get_timer_tree get_timer_root reset_timers get_timer_stack_for_thread set_gauge timed GaugeNode TimerStack UnityToExternalProtoServicer add_UnityToExternalProtoServicer_to_server UnityToExternalProtoStub EngineConfigurationChannel EngineConfig EnvironmentParametersChannel FloatPropertiesChannel IncomingMessage OutgoingMessage RawBytesChannel SideChannel StatsAggregationMethod StatsSideChannel test_initialization test_reset test_returncode_to_signal_name test_log_file_path_is_set test_close test_step test_port_defaults test_handles_bad_filename test_check_communication_compatibility test_rpc_communicator_checks_port_on_create test_rpc_communicator_create_multiple_workers test_rpc_communicator_close test_batched_step_result_from_proto_raises_on_nan test_process_pixels test_process_visual_observation_bad_shape test_agent_behavior_spec_from_proto proto_from_steps_and_action test_batched_step_result_from_proto test_action_masking_continuous test_action_masking_discrete_1 generate_list_agent_proto generate_uncompressed_proto_obs test_batched_step_result_from_proto_raises_on_infinite generate_compressed_proto_obs test_vector_observation proto_from_steps test_action_masking_discrete generate_compressed_data test_action_masking_discrete_2 test_process_pixels_gray test_process_visual_observation test_raw_bytes test_int_channel test_message_float_list IntChannel test_message_bool test_message_string test_float_properties test_message_int32 test_message_float32 test_timers decorated_func table_line ReleaseInfo validate_packages main NonTrivialPEP420PackageFinder main set_academy_version_string _escape_non_none extract_version_string check_versions set_package_version set_version MagicMock create_mock_vector_steps UnityToGymWrapper sample create_mock_group_spec setup_mock_unityenvironment step MagicMock create_mock_vector_steps UnityToGymWrapper create_mock_group_spec setup_mock_unityenvironment MagicMock create_mock_vector_steps UnityToGymWrapper sample create_mock_group_spec setup_mock_unityenvironment step tuple CONTINUOUS range DISCRETE list array range convert_to_barracuda convert convert_to_onnx _make_frozen_graph _enforce_onnx_conversion convert_frozen_to_onnx info model_path items list tf_optimize make_model node _make_onnx_node_for_constant extend _get_output_node_names _get_input_node_names info append brain_name optimize_graph TensorProto _get_frozen_graph_node_names add _get_frozen_graph_node_names name add node set brain_name info set_verbosity ConfigProto 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 layers isinstance print tensors inputs zip to_json globals Build array_equal pool reduce Build tanh mad tanh mul Build concat add sigmoid sub mad _ tanh mul Build concat add sigmoid mad print sorted keys is_action_discrete sum resequence_and_append obs from_observations steps_from_proto vector_actions AgentBuffer append reset_agent vector_observations array visual_observations enumerate make_demo_buffer camera_resolutions load_demonstration behavior_spec_to_brain_parameters zip enumerate isdir isfile get_demo_files write SerializeToString _EncodeVarint len add_argument_group add_argument ArgumentParser parse_args start_learning join join pop SamplerManager MetaCurriculum set_all_curricula_to_lesson_num validate_environment_path set_warnings_enabled warning __version__ DEBUG seed load_model _asdict set_log_level debug run_training add_timer_metadata INFO get_version_string train_model API_VERSION print dumps cpu randint parse_command_line run_cli add_argument ArgumentParser RunOptions experiment_config_path load_config get_timer_root reset_timers put _send_response StepResponse env_factory list _generate_all_results set_log_level get_and_reset_stats set_actions StatsSideChannel action set_configuration EngineConfigurationChannel external_brains payload set_float_parameter STEP EnvironmentParametersChannel items EnvironmentResponse EXTERNAL_BRAINS reset RESET step endswith len print HasField hasattr get_attr isinstance 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 Build mul sub insert Build tolist append range len locate_actual_output_node name find_tensor_by_name split locate_actual_output_node name lstm find_tensor_by_name find_forget_bias split get_layer_shape id Struct tensor get_layer_rank layer_ranks hasattr name patch_data rank input_shapes out_shapes input get_attr append replace_strings_in_list tensors embody astype op inputs zip enumerate print float32 patch_data_fn model_tensors map_ignored_layer_to_its_input co_argcount len items list hasattr get_tensors name print process_layer eval slow_but_stable_topological_sort ModelBuilderContext sort assign_ids pop range insert len layers verbose Struct process_model open print_known_operations fuse compress node GraphDef Model dims_to_barracuda_shape insert get_tensor_dims inputs MessageToJson ParseFromString cleanup_layers read memories print sort write trim summary print_supported_ops update join min_lesson_length format SACTrainer GhostTrainer copy warning PPOTrainer items list isdir get check_config rcls list zeros_like size reversed range append discount_rewards Mock CameraResolution arange ones BehaviorSpec append array range ones AgentExperience append zeros sum range len vector_action_space_size pop number_visual_observations to_agentbuffer make_fake_trajectory vector_observation_space_size create_mock_brainparams create_mock_brainparams create_mock_brainparams create_mock_brainparams create_mock_brainparams zeros Mock Mock ActionInfo publish_trajectory_queue range create_mock_steps AgentProcessor empty create_mock_policy add_experiences Mock assert_has_calls ActionInfo publish_trajectory_queue range call create_mock_steps append AgentProcessor empty create_mock_policy add_experiences Mock assert_has_calls ActionInfo end_episode publish_trajectory_queue range call create_mock_steps append AgentProcessor empty create_mock_policy add_experiences AgentManager create_mock_policy Mock get_nowait AgentManagerQueue put Mock assert_any_call remove record_environment_stats AgentManager add_writer StatsReporter write_stats join remove _get_candidate_names convert _get_default_tempdir dirname abspath isfile next join export_policy_model sess save_model graph create_policy_mock SerializationSettings model_path reset_default_graph brain_name initialize_or_load dirname abspath NNPolicy create_bc_module ppo_dummy_config create_mock_3dball_brain update items list ppo_dummy_config create_bc_module create_mock_3dball_brain update items list ppo_dummy_config current_lr create_bc_module create_mock_3dball_brain update items list ppo_dummy_config create_bc_module create_mock_3dball_brain update items list ppo_dummy_config create_mock_banana_brain create_bc_module update items list ppo_dummy_config create_mock_banana_brain create_bc_module flatten list range len append range AgentBuffer resequence_and_append get_batch construct_fake_buffer assert_array make_mini_batch AgentBuffer reset_agent array resequence_and_append sample_mini_batch construct_fake_buffer AgentBuffer resequence_and_append construct_fake_buffer AgentBuffer resequence_and_append list construct_fake_buffer AgentBuffer truncate values Curriculum Curriculum Curriculum dumps StringIO StringIO load_demonstration demo_to_buffer dirname abspath load_demonstration demo_to_buffer dirname abspath dirname abspath dirname abspath mock_open BytesIO DemonstrationMetaProto write_delimited create_tf_graph brain_name setup_mock_brain load_weights init_load_weights zip assert_array_equal get_weights PPOTrainer create_policy GhostController GhostTrainer PPOTrainer subscribe_trajectory_queue advance put make_fake_trajectory BrainParameters from_name_behavior_id AgentManagerQueue add_policy brain_name create_policy GhostController GhostTrainer PPOTrainer simulate_rollout get_nowait advance _swap_snapshots setup_mock_brain publish_policy_queue BrainParameters from_name_behavior_id AgentManagerQueue add_policy brain_name create_policy clear safe_load MagicMock parse_command_line clear parse_command_line parse_command_line parse_command_line MetaCurriculum increment_lessons Mock MetaCurriculum assert_called_with increment_lessons assert_not_called MetaCurriculum assert_called_with MetaCurriculum set_all_curricula_to_lesson_num MetaCurriculum SimpleEnvironment safe_load loads MetaCurriculum _check_environment_trains setup_mock_brain NNPolicy join save_model initialize_or_load create_policy_mock _compare_two_policies list create_steps_from_brainparams evaluate brain agent_id assert_array_equal list create_steps_from_brainparams evaluate brain agent_id create_policy_mock reset_default_graph NNPolicy update_normalization to_agentbuffer make_fake_trajectory BrainParameters zeros range run MagicMock basic_mock_brain basic_params BehaviorSpec get_action empty FakePolicy MagicMock basic_mock_brain DecisionSteps basic_params get_action array FakePolicy MagicMock basic_mock_brain ActionInfo DecisionSteps basic_params get_action array FakePolicy setup_mock_brain PPOOptimizer NNPolicy make_fake_trajectory update brain simulate_rollout _create_ppo_optimizer_ops_mock reset_default_graph update brain simulate_rollout _create_ppo_optimizer_ops_mock reset_default_graph update brain simulate_rollout _create_ppo_optimizer_ops_mock reset_default_graph items list get_trajectory_value_estimates to_agentbuffer _create_fake_trajectory _create_ppo_optimizer_ops_mock next_obs reset_default_graph assert_array_almost_equal array discount_rewards Mock brain_name _increment_step BrainParameters assert_called_with add_policy PPOTrainer _update_policy simulate_rollout brain_name setup_mock_brain add_policy PPOTrainer create_policy list values Mock brain_name make_brain_parameters add_policy PPOTrainer make_brain_parameters update NNPolicy setup_mock_brain PPOOptimizer SACOptimizer simulate_rollout evaluate_batch brain brain simulate_rollout prepare_update _execute_model update_dict make_mini_batch policy update create_optimizer_mock reward_signal_eval reward_signal_update update create_optimizer_mock reward_signal_eval reward_signal_update update create_optimizer_mock reward_signal_eval reward_signal_update create_optimizer_mock reward_signal_eval reward_signal_update create_optimizer_mock reward_signal_eval reward_signal_update create_optimizer_mock reward_signal_eval reward_signal_update create_optimizer_mock reward_signal_eval reward_signal_update create_optimizer_mock reward_signal_eval reward_signal_update set_is_policy_updating FakeTrainer dummy_config create_mock_brain end_episode list create_rl_trainer values items list construct_fake_buffer create_rl_trainer _clear_update_buffer create_rl_trainer set_is_policy_updating subscribe_trajectory_queue advance put make_fake_trajectory publish_policy_queue AgentManagerQueue get_nowait range setup_mock_brain SACOptimizer NNPolicy update brain simulate_rollout create_sac_optimizer_mock reset_default_graph brain simulate_rollout create_sac_optimizer_mock update_reward_signals reset_default_graph str SACTrainer save_model brain simulate_rollout num_experiences setup_mock_brain add_policy brain_name create_policy SACTrainer list SACTrainer values make_brain_parameters add_policy brain_name create_policy SamplerManager sample_all sampler_config_1 sampler_config_2 SamplerManager SamplerManager sample_all incorrect_uniform_sampler incorrect_sampler_config update safe_load print SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config MemoryEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config MemoryEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains generate_config SimpleEnvironment _check_environment_trains simple_record generate_config SimpleEnvironment _check_environment_trains simple_record generate_config SimpleEnvironment _check_environment_trains simple_record generate_config clear assert_called_once_with Mock get_stats_summaries add_stat add_writer StatsReporter float range write_stats clear Mock add_property add_writer StatsReporter assert_called_once_with sleep TensorboardWriter StatsSummary write_stats generate_config close SubprocessEnvManager simple_env_factory _check_environment_trains default_config default_config close SubprocessEnvManager GhostController MagicMock GhostController TrainerController MagicMock assert_called_with MagicMock start_learning assert_called_once MagicMock assert_not_called start_learning assert_called_once MagicMock MagicMock assert_called_once MagicMock advance add assert_not_called BrainParametersMock BrainParametersMock TrainerFactory BrainParameters brain_name generate TrainerFactory BrainParameters _load_config StringIO _load_config assemble_curriculum_config mkdir join handle_existing_directories append from_observations range ones items list to_agentbuffer add set make_fake_trajectory extract_stack filename get __old_np_array _check_no_float64 get _check_no_float64 __old_np_zeros get __old_np_ones _check_no_float64 join format print exit walk float check_coverage join remove mkdir rmdir exists documentElement getAttribute parse join clean_previous_results parse_results get_unity_executable_path print exit returncode get_base_path copy2 init_venv add_argument ArgumentParser parse_args split strip run_standalone_build int time join init_venv override_config_file print exit override_legacy_config_file get_base_path rename run_standalone_build run checkout_csharp_version exists get_base_output_path python run_training csharp exists join move get_unity_executable_path print makedirs dirname get_base_output_path run check_call check_call check_call update list values update list values check_call str format UnityToGymWrapper print step reset sample UnityEnvironment range reset UnityEnvironment close UnityToGymWrapper randn is_action_continuous column_stack action_size get_behavior_spec set_actions get_steps EngineConfigurationChannel set_configuration_parameters discrete_action_branches is_action_discrete any len add setLevel getLogger basicConfig setLevel tuple vector_action_size mean reshape array data compressed_data reshape process_pixels shape array mean isnan array _raise_on_nan_and_inf sum is_action_discrete _generate_split_indices ones discrete_action_branches len astype _raise_on_nan_and_inf any cast split append _process_vector_observation bool _process_visual_observation array observation_shapes enumerate range len get_ident TimerStack perf_counter push items list merge reset method_handlers_generic_handler add_generic_rpc_handlers UnityEnvironment close MockCommunicator UnityEnvironment MockCommunicator UnityEnvironment MockCommunicator index executable_args get_steps obs get_behavior_spec close reset MockCommunicator zip UnityEnvironment observation_shapes len get_steps obs zip ones step get_behavior_spec close MockCommunicator set_actions zeros UnityEnvironment observation_shapes len UnityEnvironment close MockCommunicator close RpcCommunicator close RpcCommunicator close RpcCommunicator list extend ObservationProto AgentInfoProto append prod range len fromarray uint8 BytesIO astype save ObservationProto generate_compressed_data extend shape ObservationProto shape tolist extend obs concatenate action_mask agent_id ObservationProto AgentInfoProto append generate_uncompressed_proto_obs proto_from_steps generate_compressed_data process_pixels rand generate_compressed_data process_pixels rand _process_vector_observation generate_list_agent_proto enumerate generate_compressed_proto_obs rand extend AgentInfoProto _process_visual_observation generate_uncompressed_proto_obs generate_compressed_proto_obs rand AgentInfoProto extend list sort CONTINUOUS agent_id BehaviorSpec steps_from_proto generate_list_agent_proto range BehaviorSpec steps_from_proto DISCRETE generate_list_agent_proto action_mask BehaviorSpec steps_from_proto DISCRETE generate_list_agent_proto action_mask BehaviorSpec steps_from_proto DISCRETE generate_list_agent_proto action_mask CONTINUOUS BehaviorSpec steps_from_proto generate_list_agent_proto action_mask BrainParametersProto behavior_spec_from_proto extend CONTINUOUS generate_list_agent_proto BehaviorSpec CONTINUOUS generate_list_agent_proto BehaviorSpec _parse_side_channel_message _generate_side_channel_data send_int IntChannel FloatPropertiesChannel _parse_side_channel_message _generate_side_channel_data get_property set_property uuid4 _parse_side_channel_message _generate_side_channel_data RawBytesChannel encode send_raw_data get_and_clear_received_messages len buffer read_bool append write_bool IncomingMessage range OutgoingMessage buffer write_int32 read_int32 IncomingMessage OutgoingMessage IncomingMessage write_float32 buffer read_float32 OutgoingMessage read_string write_string buffer IncomingMessage OutgoingMessage IncomingMessage buffer OutgoingMessage read_float32_list write_float32_list set_gauge TimerStack print find_packages find validate_packages replace endswith add set walk join print extract_version_string set values join format set_academy_version_string print set_package_version enumerate split | <img src="docs/images/image-banner.png" align="middle" width="3000"/> # Unity ML-Agents Toolkit [](https://github.com/Unity-Technologies/ml-agents/tree/release_1_docs/docs/) [](LICENSE) ([latest release](https://github.com/Unity-Technologies/ml-agents/releases/tag/latest_release)) ([all releases](https://github.com/Unity-Technologies/ml-agents/releases)) **The Unity Machine Learning Agents Toolkit** (ML-Agents) is an open-source project that enables games and simulations to serve as environments for training intelligent agents. Agents can be trained using reinforcement learning, imitation learning, neuroevolution, or other machine learning methods through a | 1,689 |
chenhongge/RobustTrees | ['adversarial defense', 'adversarial attack'] | ['Robust Decision Trees Against Adversarial Examples'] | tests/python/test_basic_models.py demo/guide-python/custom_objective.py python-package/xgboost/rabit.py tests/python-gpu/test_large_sizes.py jvm-packages/create_jni.py demo/guide-python/predict_first_ntree.py demo/guide-python/sklearn_examples.py tests/python-gpu/test_gpu_linear.py demo/gpu_acceleration/cover_type.py tests/python/test_shap.py demo/guide-python/predict_leaf_indices.py demo/regression/mknfold.py python-package/xgboost/libpath.py tests/python/test_training_continuation.py python-package/xgboost/callback.py demo/guide-python/sklearn_evals_result.py tests/python/test_early_stopping.py tests/python/test_with_sklearn.py tests/python/test_eval_metrics.py demo/kaggle-higgs/higgs-numpy.py tests/distributed/test_issue3402.py tests/python/test_linear.py demo/guide-python/cross_validation.py tests/python/test_monotone_constraints.py tests/python/test_basic.py doc/conf.py tests/benchmark/benchmark_linear.py tests/benchmark/benchmark_tree.py demo/guide-python/generalized_linear_model.py tests/python-gpu/test_monotonic_constraints.py demo/guide-python/basic_walkthrough.py python-package/xgboost/core.py python-package/xgboost/training.py python-package/xgboost/__init__.py demo/kaggle-higgs/higgs-pred.py tests/python/test_updaters.py demo/kaggle-higgs/higgs-cv.py tests/python/testing.py tests/python-gpu/test_gpu_updaters.py tests/python/regression_test_utilities.py xgbKantchelianAttack.py demo/multiclass_classification/train.py python-package/setup.py demo/guide-python/external_memory.py tests/python/test_openmp.py tests/python/test_dt.py demo/binary_classification/mapfeat.py demo/regression/mapfeat.py demo/guide-python/sklearn_parallel.py tests/python-gpu/test_gpu_prediction.py demo/guide-python/boost_from_prediction.py demo/yearpredMSD/csv2libsvm.py tests/distributed/test_basic.py demo/binary_classification/mknfold.py tests/python/test_sparse_dmatrix.py tests/python/test_with_pandas.py python-package/xgboost/plotting.py tests/python/test_plotting.py demo/rank/trans_data.py demo/kaggle-higgs/speedtest.py python-package/xgboost/compat.py tests/python/test_tree_regularization.py doc/sphinx_util.py demo/guide-python/gamma_regression.py demo/guide-python/evals_result.py python-package/xgboost/sklearn.py python-package/setup_pip.py node_wrapper sigmoid xgbMultiClassKantchelianAttack main xgbKantchelianAttack xgboost_wrapper write_nmap loadfmap evalerror logregobj fpreproc evalerror logregobj fpreproc save_data generate_doxygen_xml setup run_doxygen cd cp maybe_makedirs normpath run BinaryDistribution reset_learning_rate record_evaluation print_evaluation _fmt_metric early_stop _get_callback_context py_str EarlyStopException _maybe_dt_data _maybe_pandas_label ctypes2buffer from_cstr_to_pystr _load_lib _log_callback XGBoostError _maybe_dt_array c_array Booster c_str _check_call ctypes2numpy DMatrix from_pystr_to_cstr _get_log_callback_func _maybe_pandas_data XGBoostLibraryNotFound find_lib_path to_graphviz plot_tree _parse_node _parse_edge plot_importance allreduce tracker_print get_world_size version_number get_processor_name finalize _init_rabit init get_rank broadcast _objective_decorator XGBClassifier XGBModel XGBRegressor mknfold train aggcv cv _train_internal CVPack run_benchmark run_benchmark get_cancer get_digits parameter_combinations train_dataset get_boston assert_results_non_increasing get_sparse_weights get_sparse Dataset run_suite non_increasing _skip_if_no_dt _skip_if_no_sklearn _skip_if_no_matplotlib _skip_if_no_pandas TestBasic captured_output TestModels TestDataTable TestEarlyStopping TestEvalMetrics assert_classification_result is_float assert_regression_result TestLinear xgb_get_weights is_increasing is_correctly_constrained is_decreasing TestMonotoneConstraints TestOMP TestPlotting TestSHAP test_sparse_dmatrix_csc test_sparse_dmatrix_csr TestTrainingContinuation TestTreeRegularization TestUpdaters TestPandas test_save_load_model test_boston_housing_regression test_classification_with_custom_objective test_split_value_histograms test_parameter_tuning test_multiclass_classification test_validation_weights_xgbmodel test_binary_classification test_sklearn_nfolds_cv test_kwargs test_sklearn_n_jobs TemporaryDirectory test_regression_with_custom_objective test_sklearn_api_gblinear test_validation_weights_xgbclassifier test_sklearn_api test_feature_importances test_kwargs_error test_sklearn_clone test_sklearn_plotting test_sklearn_random_state TestGPULinear TestGPUPredict TestGPU assert_gpu_results TestGPU eprint TestMonotonicConstraints non_decreasing assert_constraint non_increasing arange load_svmlight_file Booster xgbKantchelianAttack xgbMultiClassKantchelianAttack abs max seed load_model attack predict format hstack astype shuffle xgboost_wrapper enumerate time toarray print len int strip split open len write range len sum float get_label exp get_label get_label get_weight set_weight str join write len call write run_doxygen add_stylesheet chdir getcwd print normpath print normpath makedirs print check_call print format copy normpath join isabs clear isinstance str decode value append range print format py_str CFUNCTYPE c_char_p LoadLibrary dirname pathsep find_lib_path _get_log_callback_func c_char_p zeros from_buffer bytearray format columns isinstance astype dtypes dtypes isinstance astype names tuple astype join dirname abspath append expanduser get_score sorted list subplots arange isinstance set_title set_yticklabels barh text set_yticks set_xlim set_xlabel grid set_ylabel zip set_ylim len node match group match edge groups update get_booster isdigit isinstance _parse_node copy Digraph _parse_edge enumerate split BytesIO subplots seek to_graphviz write axis imshow imread pipe c_int RabitInit len RabitFinalize RabitGetRank RabitGetWorldSize str RabitTrackerPrint RabitIsDistributed write c_str flush RabitGetProcessorName byref create_string_buffer c_ulong value sizeof len dumps byref c_void_p loads cast c_ulong get_rank raw c_char_p RabitBroadcast data_as size copy c_void_p RabitAllreduce func_ptr CFUNCTYPE ravel RabitVersionNumber join join decode Booster load_rabit_checkpoint eval_set list cb CallbackEnv save_rabit_checkpoint get_rank range update get_dump best_iteration save_raw float attr pop items int isinstance dict len isinstance reset_learning_rate warn append record_evaluation print_evaluation early_stop seed items list permutation arange array_split slice num_row fpreproc copy XGBStratifiedKFold split append range CVPack len decode sorted list items extend append float array split pop update from_dict cb mknfold isinstance CallbackEnv aggcv dict append early_stop print_evaluation range update str time print train literal_eval iterations params updater DMatrix tree_method load_boston load_digits load_breast_cancer csr_matrix array RandomState make_regression array RandomState make_regression int str y remove print X name hstack metric glob copy use_external_memory savetxt scale train DMatrix max objective append sorted product enumerate append train_dataset float y ElasticNet scale DMatrix X predict fit ones reshape linspace DMatrix range predict column_stack train rand predict DMatrix train rand predict DMatrix load_digits len KFold _skip_if_no_sklearn float sum predict fit load_iris KFold _skip_if_no_sklearn check_pred predict fit load_digits Series feature_importances_ _skip_if_no_sklearn assert_almost_equal DataFrame array fit fit load_boston _skip_if_no_sklearn predict KFold GridSearchCV load_boston XGBRegressor _skip_if_no_sklearn fit assert_raises fit load_boston XGBRegressor _skip_if_no_sklearn predict KFold assert_raises load_digits len KFold _skip_if_no_sklearn XGBClassifier float sum predict fit data load_iris len target _skip_if_no_sklearn XGBClassifier train_test_split sum predict fit data load_iris len target _skip_if_no_sklearn XGBClassifier train_test_split sum predict fit data use to_graphviz plot_tree load_iris target _skip_if_no_sklearn XGBClassifier plot_importance fit load_digits StratifiedKFold _skip_if_no_sklearn cv DMatrix _skip_if_no_sklearn DMatrix train load_digits _skip_if_no_sklearn XGBClassifier _skip_if_no_sklearn XGBClassifier _skip_if_no_sklearn XGBClassifier _skip_if_no_sklearn XGBClassifier _skip_if_no_sklearn XGBClassifier clone seed fit choice _skip_if_no_sklearn XGBModel unique make_hastie_10_2 evals_result len seed fit choice _skip_if_no_sklearn XGBClassifier unique make_hastie_10_2 evals_result len _skip_if_no_sklearn load_digits KFold zip print flush str make_regression train DMatrix predict | Robust Decision Trees Against Adversarial Examples ============================================ We developed a novel algorithm to train robust decision tree based models (notably, Gradient Boosted Decision Tree). This repo contains our implementation under the [XGBoost](https://github.com/dmlc/xgboost.git) framework. We plan to merge robust training as a feature to XGBoost upstream in near future. Please refer to our paper for more details on the proposed algorithm: Hongge Chen, Huan Zhang, Duane Boning, and Cho-Jui Hsieh ["Robust Decision Trees Against Adversarial Examples"](https://arxiv.org/abs/1902.10660), ICML 2019 [[video of the talk]](https://slideslive.com/38916896/supervised-learning) [[slides]](https://icml.cc/media/Slides/icml/2019/seasideball(11-14-00)-11-14-00-4401-robust_decision.pdf) [[poster]](https://s3.amazonaws.com/postersession.ai/0d7f42aa-707e-44bd-960d-a6dd2b9dd8aa.pdf) We also provide our implementation of an attack proposed in [Kantchelian et al. ICML 2016](https://arxiv.org/abs/1509.07892) to test the robustness of a GBDT model. This method uses Mixed Integer Linear Programming (MILP) to find the **exact minimum** adversarial example. | 1,690 |
chenlabgccri/CancerTypePrediction | ['type prediction'] | ['Convolutional neural network models for cancer type prediction based on gene expression'] | Hyperparameter tuning/1d_CNN_33class_hyperparameters.py 5cv_33class/5cv_Vanilla_33class.py Hyperparameter tuning/vanilla_CNN_33class_hyperparameters.py 5cv_34class/5cv_1D_CNN_34class.py 5cv_34class/5cv_hybrid_34class.py 5cv_34class/5cv_Vanilla_34class.py 5cv_33class/5cv_1D_CNN_33class.py 5cv_33class/5cv_hybrid_33class.py make_model make_model compile Sequential add output_shape Dense MaxPooling2D summary Conv2D Activation Flatten len | # Predicting all 33-cancer types and their normal tissues with CNN  Folder ending with 33 class contains models which only work for classification of 33 cancer tumors. In order to see the impact of Normal tissues in classification, the codes that are in 34 class folder need to be run. Hyperparameter tuning folder is showing grid search result of some of the hyperparameters for 1D-CNN and Vanilla models. All codes are written in Keras with a simple structure which helps reader understand the modeling stage easier. ## Background Precise prediction of cancer types is vital for cancer diagnosis and therapy. Important cancer marker genes can be inferred through predictive model. Several studies have attempted to build machine learning models for this task however none has taken into consideration the tissue of origin effects that can potentially bias the identification of cancer markers. ## Results In this paper, we introduced several Convolutional Neural Network (CNN) models that take unstructured gene expression inputs to classify tumor and non-tumor samples into their designated cancer types or as normal. Based on different designs of gene embeddings and convolution schemes, we implemented three CNN models: 1D-CNN, 2D-Vanilla-CNN, and 2D-Hybrid-CNN. The models were trained and tested on combined 10,340 samples of 33 cancer types and 731 matched normal tissues of The Cancer Genome Atlas (TCGA). Our models achieved excellent prediction accuracies (93.9-95.0%) among 34 classes (33 cancers and normal). Furthermore, we interpreted the 1D-CNN model with a guided saliency technique and identified a total of 2,090 cancer markers (108 per class). The concordance of differential expression of these markers between the cancer type they represent and others is confirmed. In breast cancer, for instance, our model identified well-known markers, such as GATA3 and ESR1. Finally, we extended the 1D-CNN model for prediction of breast cancer subtypes and achieved an average accuracy of 88.42% among 5 subtypes. ## Conclusions Here we present novel CNN designs for accurate and simultaneous cancer/normal and cancer types prediction based on gene expression profiles, and unique model interpretation scheme to elucidate biologically relevance of cancer marker genes after eliminating the effects of tissue-of-origin. The proposed model had light hyperparameters to be trained and thus can be easily adapt to facilitate cancer diagnosis in the future. | 1,691 |
chenxi116/TF-phrasecut-public | ['semantic segmentation'] | ['Recurrent Multimodal Interaction for Referring Image Segmentation'] | util/eval_tools.py util/processing_tools.py util/io.py build_batches.py util/text_processing.py LSTM_model.py util/data_reader.py util/im_processing.py RMI_model.py main.py util/loss.py build_referit_batches build_coco_batches LSTM_model visualize_seg train test RMI_model run_prefetch DataReader compute_mask_IU compute_bbox_iou crop_masks_subtract_mean crop_bboxes_subtract_mean bboxes_from_masks resize_and_pad resize_and_crop load_proposal_mask save_json load_json save_str_list load_str_list load_referit_gt_mask l2_regularization_loss weighed_logistic_loss iou_loss smooth_l1_loss logistic_loss_cond dsc_loss generate_bilinear_filter compute_accuracy generate_spatial_batch spatial_feature_from_bbox sentence2vocab_indices preprocess_sentence load_vocab_dict_from_file resize_and_pad open list len img_as_ubyte append imread range load_vocab_dict_from_file astype tile preprocess_sentence keys enumerate load savez print float32 makedirs savez print astype float32 zfill REFER img_as_ubyte resize_and_pad tile preprocess_sentence frPyObjects imread load_vocab_dict_from_file makedirs restore RMI_model print astype LSTM_model float32 range Saver read_batch save run global_variables_initializer expand_dims DataReader compute_accuracy Session makedirs LSTM_model num_batch Saver read_batch resize_and_pad DataReader Session run str restore addPairwiseGaussian RMI_model squeeze len addPairwiseBilateral img_as_ubyte inference expand_dims range DenseCRF2D concatenate compute_mask_IU astype zeros resize_and_crop print reshape float32 visualize_seg global_variables_initializer setUnaryEnergy makedirs show imshow title astype load join str permutation arange close put dict minimum isinstance reshape maximum array logical_or sum logical_and int min floor resize zeros round int floor resize zeros round max isinstance reshape img_as_ubyte resize zeros array range zeros range nonzero copy img_as_ubyte bboxes_from_masks resize zeros range loadmat loadmat sigmoid_cross_entropy_with_logits multiply reduce_sum add reduce_mean sigmoid_cross_entropy_with_logits select reduce_sum shape reduce_mean zeros equal add_n multiply reduce_sum add sigmoid div reduce_mean scalar_mul sub multiply reduce_sum add sigmoid div reduce_mean sub to_float reduce_sum pow reduce_mean stop_gradient less abs zeros range concatenate logical_xor sum logical_not reshape array zeros isinstance strip split sentence2vocab_indices len | # Recurrent Multimodal Interaction for Referring Image Segmentation This repository contains code for [Recurrent Multimodal Interaction for Referring Image Segmentation](https://arxiv.org/abs/1703.07939), ICCV 2017. If you use the code, please cite ``` @inproceedings{liu2017recurrent, title={Recurrent Multimodal Interaction for Referring Image Segmentation}, author={Liu, Chenxi and Lin, Zhe and Shen, Xiaohui and Yang, Jimei and Lu, Xin and Yuille, Alan}, booktitle={{ICCV}}, year={2017} } | 1,692 |
chenxuluo/GST-video | ['action recognition'] | ['Grouped Spatial-Temporal Aggregation for Efficient Action Recognition'] | GST.py datasets_video.py dataset.py models.py opts.py transforms.py main.py VideoRecord VideoDataSet return_somethingv1 return_somethingv2 return_dataset resnet101 ResNet resnet50 Bottleneck validate AverageMeter check_rootfolders accuracy save_checkpoint adjust_learning_rate get_optim_policies main train TemporalModel Stack IdentityTransform GroupCenterCrop GroupFiveCrop GroupNormalize GroupOverSample ToTorchFormatTensor StackFiveCrops GroupScale GroupRandomSizedCrop GroupRandomHorizontalFlip GroupRandomCrop GroupMultiScaleCrop join list ResNet size load_url unsqueeze load_state_dict keys list ResNet size load_url unsqueeze load_state_dict keys checkpoint_dir validate SGD root_path VideoDataSet DataLoader save_checkpoint adjust_learning_rate input_std dataset cuda max get_augmentation open scale_size lr_steps GroupNormalize crop_size load_state_dict parse_args range format TemporalModel start_epoch input_mean resume lr get_optim_policies is_available num_segments load join return_dataset evaluate print check_rootfolders isfile train epochs len model zero_grad cuda clip_gradient update format size item clip_grad_norm flush enumerate time criterion backward print AverageMeter write accuracy parameters step len time format print AverageMeter write eval flush copyfile save param_groups weight_decay sum lr print mkdir list isinstance BatchNorm3d extend parameters modules append Linear | # Grouped Spatial-Temporal Aggretation for Efficient Action Recognition Pytorch implementation of paper Grouped Spatial-Temporal Aggretation for Efficient Action Recognition. [arxiv](https://arxiv.org/abs/1909.13130) #### Prerequisites * PyTorch 1.0 or higher * python 3.5 or higher ### Data preparation Please refer to [TRN-pytorch](https://github.com/metalbubble/TRN-pytorch) for data preparation on Something-Something. ### Training * For GST-Large: `python3 main.py --root_path /path/to/video/folder --dataset somethingv1 --checkpoint_dir /path/for/saving/checkpoints/ --type GST --arch resnet50 --num_segments 8 --beta 1` | 1,693 |
chetanchawla/Sort-Tracker | ['multiple object tracking'] | ['Simple Online and Realtime Tracking'] | sort2.py KalmanBoxTracker iou Sort convert_bbox_to_z associate_detections_to_trackers convert_x_to_bbox parse_args minimum maximum float sqrt linear_assignment iou concatenate reshape append zeros empty enumerate add_argument ArgumentParser | The SORT tracker had been optimized for the indian dataset and the code had been modified accordingly. The dataset is not yet public. From the original Authors- SORT ===== A simple online and realtime tracking algorithm for 2D multiple object tracking in video sequences. See an example [video here](https://motchallenge.net/movies/ETH-Linthescher-SORT.mp4). By Alex Bewley [DynamicDetection.com](http://www.dynamicdetection.com) ### Introduction SORT is a barebones implementation of a visual multiple object tracking framework based on rudimentary data association and state estimation techniques. It is designed for online tracking applications where only past and current frames are available and the method produces object identities on the fly. While this minimalistic tracker doesn't handle occlusion or re-entering objects its purpose is to serve as a baseline and testbed for the development of future trackers. | 1,694 |
chevalierNoir/A2W-Segmental | ['speech recognition', 'word embeddings'] | ['Whole-Word Segmental Speech Recognition with Acoustic Word Embeddings'] | src/options.py src/lev.py src/spec_augment.py src/segloss/jit_segloss.py src/train_seg.py src/delta_ark.py src/seg_model.py src/utils.py src/sampler.py src/eval_seg.py Speech ToTensor collate_fn main get_trans iterative_levenshtein compute_acc get_parser BucketBatchSampler SegModel get_grid_locations interpolate_bilinear create_dense_flows apply_interpolation sparse_image_warp phi interpolate_spline time_warp freq_mask flatten_grid_locations dense_image_warp solve_interpolation specaug time_mask get_flat_grid_locations cross_squared_distance_matrix main train evaluate get_word_map viterbi SegLossFunction SegLossModule append range new_zeros join viterbi eval info append range enumerate len wordlist copy_ DataLoader data_sample_rate ArgumentParser open seed eval_len basicConfig list get_trans parse_known_args safe_load set_defaults to max_ilen Speech lstm_sample_rate best_dev_path max_olen info zip get_word_map eval_ark manual_seed eval_scp load items eval_out print add_argument eval_text min extend append range len iterative_levenshtein enumerate add_argument ArgumentParser add sparse_image_warp unsqueeze randrange device mean range clone randrange mean range clone randrange interpolate_spline shape device create_dense_flows get_flat_grid_locations dense_image_warp meshgrid linspace meshgrid linspace solve_interpolation apply_interpolation view randn solve shape unsqueeze device float cat mul squeeze transpose matmul sum tensor max sqrt ones_like phi matmul unsqueeze float cross_squared_distance_matrix interpolate_bilinear arange reshape shape unsqueeze permute device meshgrid float dtype unbind arange reshape min gather shape long floor unsqueeze device append tensor max clip_grad_norm_ zero_grad save ckpt_path max open max_grad append master_params encoder sum state_dict size item info clip_grad_norm enumerate backward write parameters accum_batch_size step len viterbi tolist eval item append compute_acc range enumerate len SGD load_emb train_scp ReduceLROnPlateau save get_parser StepLR initialize Adam train_len device_count load_state_dict range state_dict epoch Namespace dev_scp load_awe dev_text join train_ark evaluate dev_len write output parameters pow train_text dev_ark isfile train step makedirs argmax view LongTensor size append type max range | # A2W Segmental Model (SLT'2021) This repo contains the code for A2W segmental model [Whole-Word Segmental Speech Recognition with Acoustic Word Embeddings](https://arxiv.org/pdf/2007.00183.pdf) ## Requirements * Kaldi * g++ 5.5.0 * CUDA 10.0 * Pytorch 1.4.0 * kaldi-io ## Usage: 1. Use Kaldi for data preparation: setting up data dir, extracting fbank feature, computing and applying CMVN. | 1,695 |
chirag126/VOG | ['out of distribution detection'] | ['Estimating Example Difficulty Using Variance of Gradients'] | imagenet/imagenet_input.py imagenet/train_visualize_grad.py toy_script.py imagenet/train_get_gradients.py Feedforward plot_decision_boundaries calculate_distance weights_init blob_label inputs_base random_sized_crop distorted_inputs inputs preprocess parse_input_line lighting resize_image main train get_lr plot_grid calculate_top_10_percentile_error data isinstance fill_ BatchNorm3d Conv3d xavier_uniform_ normal_ manual_seed calculate_gain Linear arange xlabel reshape grid ylabel mean shape scatter contourf figure meshgrid xticks numpy yticks copy decode_csv read_file cast int32 decode_jpeg resize_images greater where cast int32 random_uniform minimum random_crop resize_images float64 cast int32 random_uniform reshape array random_normal reduce_sum random_crop random_sized_crop random_saturation random_flip_left_right slice random_brightness shape cast int32 lighting resize_image random_contrast array constant partial map_and_batch print prefetch_to_device map make_one_shot_iterator apply get_next repeat set_shape append range TextLineDataset shuffle_and_repeat num_test_instance l2_weight gpu_fraction test_dataset num_classes batch_size print test_image_root display log_device_placement Graph momentum lr_step_epoch test_iter lr_decay output_file initial_lr checkpoint train format arange plot xlabel ylabel savefig figure append xticks range len format system | ## Estimating Example Difficulty using Variance of Gradients This repository contains source code necessary to reproduce some of the main results in [the paper](https://arxiv.org/abs/2008.11600): **If you use this software, please consider citing:** @inproceedings{agarwal2022estimating, title={Estimating example difficulty using variance of gradients}, author={Agarwal, Chirag and D'souza, Daniel and Hooker, Sara}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, pages={10368--10378}, year={2022} | 1,696 |
chirag2796/RNN-LSTM-for-Text-Generation | ['text generation'] | ['Context-aware Natural Language Generation with Recurrent Neural Networks'] | train.py model/utils.py model/model.py model/model_blueprint.py TextGenModel new_rnn init_rnn_model AttentionWeightedAverage textgenrnn_generate textgenrnn_texts_from_file_context synthesize_to_file synthesize process_sequence textgenrnn_texts_from_file textgenrnn_encode_sequence generate_after_epoch textgenrnn_encode_cat generate_sequences_from_texts textgenrnn_sample save_model_weights concatenate Model load_weights append Input range compile argmax exp astype log multinomial sum epsilon int list format remove join print textgenrnn_encode_sequence Model eval sub input textgenrnn_sample enumerate array zeros list float32 zip textgenrnn_generate vocab get META_TOKEN format indices_char model print shuffle append synthesize vocab list META_TOKEN process_sequence squeeze shuffle tokenizer textgenrnn_encode_cat append array range Tokenizer pad_sequences texts_to_sequences | chirag2796/RNN-LSTM-for-Text-Generation | 1,697 |
chisam0217/Graph-Universal-Attack | ['graph learning'] | ['Graph Universal Adversarial Attacks: A Few Bad Actors Ruin Graph Learning Models'] | deepwalk/graph.py GUA/eval_baseline.py GUA/generate_perturbation.py node2vec/utils.py pyGAT/evaluate_GAT.py node2vec/evaluate_n2v.py pyGAT/models.py GUA/__init__.py pyGAT/utils.py GUA/utils.py pyGAT/layers.py deepwalk/deepwalkmodel.py GUA/utils_polblogs.py node2vec/graph.py deepwalk/evaluate_deepwalk.py GUA/layers.py deepwalk/utils.py GUA/models.py Skipgram get_splits sparse2graph deepwalk format_csr count_words main Graph normalize largest_connected_components train_val_test_split_tabular sparse_mx_to_torch_sparse_tensor preprocess_graph sample_mask accuracy parse_index_file load_data load_polblogs_data main encode_onehot load_npz calculate_entropy test add_perturb evaluate_attack train args normalize_add_perturb proj_lp test add_perturb select_pert universal_attack calculate_grad convert_to_v train deepfool GraphConvolution GCN normalize largest_connected_components old_load_data train_val_test_split_tabular sparse_mx_to_torch_sparse_tensor preprocess_graph sample_mask accuracy parse_index_file load_data load_polblogs_data encode_onehot load_npz node2vec main Graph alias_draw alias_setup normalize largest_connected_components train_val_test_split_tabular sparse_mx_to_torch_sparse_tensor preprocess_graph sample_mask accuracy parse_index_file load_data load_polblogs_data main encode_onehot load_npz calculate_entropy add_perturb evaluate_attack compute_test train SpecialSpmmFunction SpGraphAttentionLayer GraphAttentionLayer SpecialSpmm SpGAT GAT normalize largest_connected_components old_load_data train_val_test_split_tabular sparse_mx_to_torch_sparse_tensor preprocess_graph sample_mask accuracy parse_index_file load_data load_polblogs_data encode_onehot load_npz update Counter time format num_walks Graph print model num_of_nodes walk_length build_deep_walks Word2Vec count_words Skipgram data defaultdict row tocoo col add zip list range row tocoo col zip append score where ArgumentParser dataset list csr_matrix len tolist LogisticRegression load_polblogs_data append parse_args sum range predict add_edge asarray neighbors copy matrix float emb join deepwalk print reshape add_argument load_data array remove_edge fit get list map set array append train_test_split arange bincount connected_components print format A1 tocsr eye power diags append int strip open zeros from_dict_of_lists tocoo tuple parse_index_file vstack max list tolist array_equal range format lil_matrix concatenate adjacency_matrix tolil sort min from_scipy_sparse_matrix zeros full len diags flatten dot sum array sum type_as double data Size astype float32 from_numpy shape int64 setdiag arange tocoo eliminate_zeros max seed todense tocsr largest_connected_components normalize load_npz astype preprocess_graph union1d A1 T train_val_test_split_tabular from_scipy_sparse_matrix array time model Variable backward nll_loss print zero_grad accuracy step model print nll_loss accuracy eval ones zeros multiply range sum format model print tolist astype float32 add_perturb from_numpy eye append normalize float argmax cuda range len sum range backward Variable model nll_loss append numpy cuda minimum norm min sign flatten abs clip zeros absolute ones multiply power multiply sum normalize_add_perturb flatten argmax abs clip cuda from_numpy range inf size astype eval int norm print float32 calculate_grad convert_to_v zeros numpy model proj_lp where dataset cuda from_numpy append normalize sum radius format astype shuffle eval mkdir float deepfool join time print float32 add_perturb eye numpy len todense FloatTensor normalize LongTensor toarray eye array genfromtxt list format todense LongTensor FloatTensor print csr_matrix reshape multiply sparse_mx_to_torch_sparse_tensor shape coo_matrix eye encode_onehot normalize array range FloatTensor LongTensor toarray time format number_of_nodes p Graph num_walks print build_node2vec_walks walk_length preprocess_transition_probs Word2Vec q node2vec pop len append zeros enumerate int rand floor len eval model print nll_loss accuracy eval | # Graph Universal Adversarial Attack (GUA) ## Usage * PyTorch 0.4 or 0.5 * Python 2.7 or 3.6 * networkx, scipy, sklearn, numpy, pickle ## Train the attack model **Example:** ```python generate_perturbation.py --dataset cora --radius 4 ``` *dataset: the network dataset you are going to attack* \ *radius: the radius of the l2 Norm Projection* The verision of jupyter notebook is also supported as: universal_attack.ipynb | 1,698 |
chiukin/SPANet | ['rain removal', 'single image deraining'] | ['Spatial Attentive Single-Image Deraining with a High Quality Real Rain Dataset'] | cal_ssim.py main.py SPANet.py dataset.py create_window gaussian _ssim SSIM ssim run_train_val ensure_dir Session run_test conv1x1 Bottleneck conv3x3 SPANet irnn_layer Attention SAM Tensor Variable contiguous unsqueeze pow conv2d create_window size type_as get_device cuda is_cuda makedirs inf_batch zero_grad DataParallel load_checkpoints Session multi_gpu log_name save_mask tensorboard save_checkpoints next get_dataloader eval info net train_data_path backward write train step val_log_name data inf_batch imwrite DataParallel load_checkpoints heatmap clip Session multi_gpu transpose append get_dataloader update test_data_path format compare_ssim astype start eval ensure_dir net enumerate print numpy compare_psnr | # Spatial Attentive Single-Image Deraining with a High Quality Real Rain Dataset (CVPR'19) [Tianyu Wang](https://stevewongv.github.io)\*, Xin Yang\*, Ke Xu, Shaozhe Chen, Qiang Zhang, [Rynson W.H. Lau](http://www.cs.cityu.edu.hk/~rynson/) † (\* Joint first author. † Rynson Lau is the corresponding author.) [\[Project Page\]](https://stevewongv.github.io/derain-project.html) [\[Arxiv\]](https://arxiv.org/abs/1904.01538) ## Abstract Removing rain streaks from a single image has been drawing considerable attention as rain streaks can severely degrade the image quality and affect the performance of existing outdoor vision tasks. While recent CNN-based derainers have reported promising performances, deraining remains an open problem for two reasons. First, existing synthesized rain datasets have only limited realism, in terms of modeling real rain characteristics such as rain shape, direction and intensity. Second, there are no public benchmarks for quantitative comparisons on real rain images, which makes the current evaluation less objective. The core challenge is that real world rain/clean image pairs cannot be captured at the same time. In this paper, we address the single image rain removal problem in two ways. First, we propose a semi-automatic method that incorporates temporal priors and human supervision to generate a high-quality clean image from each input sequence of real rain images. Using this method, we construct a large-scale dataset of ∼29.5K rain/rain-free image pairs that cover a wide range of natural rain scenes. Second, to better cover the stochastic distributions of real rain streaks, we propose a novel SPatial Attentive Network (SPANet) to remove rain streaks in a local-to-global manner. Extensive experiments demonstrate that our network performs favorably against the state-of-the-art deraining methods.  ## Dataset **Real Training Dataset (256x256):** Coming Soon! **Real Testing Dataset (512x512):** Coming Soon! | 1,699 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.