code stringlengths 17 6.64M |
|---|
def motp_custom(df: DataFrame, num_detections: float) -> float:
"\n Multiple object tracker precision.\n Based on py-motmetric's motp function.\n Additionally we check whether there are any detections.\n :param df: Motmetrics dataframe that is required, but not used here.\n :param num_detections: T... |
def faf(df: DataFrame, num_false_positives: float, num_frames: float) -> float:
'\n The average number of false alarms per frame.\n :param df: Motmetrics dataframe that is required, but not used here.\n :param num_false_positives: The number of false positives.\n :param num_frames: The number of frame... |
def num_fragmentations_custom(df: DataFrame, obj_frequencies: DataFrame) -> float:
"\n Total number of switches from tracked to not tracked.\n Based on py-motmetric's num_fragmentations function.\n :param df: Motmetrics dataframe that is required, but not used here.\n :param obj_frequencies: Stores th... |
class MOTAccumulatorCustom(motmetrics.mot.MOTAccumulator):
def __init__(self):
super().__init__()
@staticmethod
def new_event_dataframe_with_data(indices, events):
"\n Create a new DataFrame filled with data.\n This version overwrites the original in MOTAccumulator achieves... |
def summary_plot(cfg: TrackingConfig, md_list: TrackingMetricDataList, ncols: int=2, savepath: str=None) -> None:
'\n Creates a summary plot with which includes all traditional metrics for each class.\n :param cfg: A TrackingConfig object.\n :param md_list: TrackingMetricDataList instance.\n :param nc... |
def recall_metric_curve(cfg: TrackingConfig, md_list: TrackingMetricDataList, metric_name: str, savepath: str=None, ax: Axis=None) -> None:
'\n Plot the recall versus metric curve for the given metric.\n :param cfg: A TrackingConfig object.\n :param md_list: TrackingMetricDataList instance.\n :param m... |
class TrackingRenderer():
'\n Class that renders the tracking results in BEV and saves them to a folder.\n '
def __init__(self, save_path):
'\n :param save_path: Output path to save the renderings.\n '
self.save_path = save_path
self.id2color = {}
def render(... |
class TestAlgo(unittest.TestCase):
@staticmethod
def single_scene() -> Tuple[(str, Dict[(str, Dict[(int, List[TrackingBox])])])]:
class_name = 'car'
box = TrackingBox(translation=(0, 0, 0), tracking_id='ta', tracking_name=class_name, tracking_score=0.5)
timestamp_boxes_gt = {0: [copy.... |
class TestMain(unittest.TestCase):
res_mockup = 'nusc_eval.json'
res_eval_folder = 'tmp'
def tearDown(self):
if os.path.exists(self.res_mockup):
os.remove(self.res_mockup)
if os.path.exists(self.res_eval_folder):
shutil.rmtree(self.res_eval_folder)
@staticmeth... |
def category_to_tracking_name(category_name: str) -> Optional[str]:
'\n Default label mapping from nuScenes to nuScenes tracking classes.\n :param category_name: Generic nuScenes class.\n :return: nuScenes tracking class.\n '
tracking_mapping = {'vehicle.bicycle': 'bicycle', 'vehicle.bus.bendy': '... |
def metric_name_to_print_format(metric_name) -> str:
'\n Get the standard print format (numerical precision) for each metric.\n :param metric_name: The lowercase metric name.\n :return: The print format.\n '
if (metric_name in ['amota', 'amotp', 'motar', 'recall', 'mota', 'motp']):
print_f... |
def print_final_metrics(metrics: TrackingMetrics) -> None:
'\n Print metrics to stdout.\n :param metrics: The output of evaluate().\n '
print('\n### Final results ###')
metric_names = metrics.label_metrics.keys()
print('\nPer-class results:')
print('\t\t', end='')
print('\t'.join([m.u... |
def print_threshold_metrics(metrics: Dict[(str, Dict[(str, float)])]) -> None:
'\n Print only a subset of the metrics for the current class and threshold.\n :param metrics: A dictionary representation of the metrics.\n '
assert (len(metrics['mota_custom'].keys()) == 1)
threshold_str = list(metric... |
def create_motmetrics() -> MetricsHost:
'\n Creates a MetricsHost and populates it with default and custom metrics.\n It does not populate the global metrics which are more time consuming.\n :return The initialized MetricsHost object with default MOT metrics.\n '
mh = MetricsHost()
warnings.fi... |
def truncate_class_name(class_name: str) -> str:
'\n Truncate a given class name according to a pre-defined map.\n :param class_name: The long form (i.e. original form) of the class name.\n :return: The truncated form of the class name.\n '
string_mapper = {'noise': 'noise', 'human.pedestrian.adul... |
def render_histogram(nusc: NuScenes, sort_by: str='count_desc', verbose: bool=True, font_size: int=20, save_as_img_name: str=None) -> None:
'\n Render two histograms for the given nuScenes split. The top histogram depicts the number of scan-wise instances\n for each class, while the bottom histogram depicts... |
def get_lidarseg_num_points_per_class(nusc: NuScenes, sort_by: str='count_desc') -> Dict[(str, int)]:
'\n Get the number of points belonging to each class for the given nuScenes split.\n :param nusc: A NuScenes object.\n :param sort_by: How to sort the classes:\n - count_desc: Sort the classes by ... |
def get_panoptic_num_instances_per_class(nusc: NuScenes, sort_by: str='count_desc') -> Dict[(str, int)]:
'\n Get the number of scan-wise instances belonging to each class for the given nuScenes split.\n :param nusc: A NuScenes object.\n :param sort_by: How to sort the classes:\n - count_desc: Sort... |
class BitMap():
def __init__(self, dataroot: str, map_name: str, layer_name: str):
"\n This class is used to render bitmap map layers. Currently these are:\n - semantic_prior: The semantic prior (driveable surface and sidewalks) mask from nuScenes 1.0.\n - basemap: The HD lidar basem... |
class TestAllMaps(unittest.TestCase):
version = 'v1.0-mini'
render = False
def setUp(self):
' Initialize the map for each location. '
self.nusc_maps = dict()
for map_name in locations:
nusc_map = NuScenesMap(map_name=map_name, dataroot=os.environ['NUSCENES'])
... |
class TestUtils(unittest.TestCase):
def setUp(self) -> None:
self.straight_path = {'start_pose': [421.2419602954602, 1087.9127960414617, 2.739593514975998], 'end_pose': [391.7142849867393, 1100.464077182952, 2.7365754617298705], 'shape': 'LSR', 'radius': 999.999, 'segment_length': [0.23651121617864976, 2... |
def get_egoposes_on_drivable_ratio(nusc: NuScenes, nusc_map: NuScenesMap, scene_token: str) -> float:
'\n Get the ratio of ego poses on the drivable area.\n :param nusc: A NuScenes instance.\n :param nusc_map: The NuScenesMap instance of a particular map location.\n :param scene_token: The token of th... |
def get_disconnected_subtrees(connectivity: Dict[(str, dict)]) -> Set[str]:
'\n Compute lanes or lane_connectors that are part of disconnected subtrees.\n :param connectivity: The connectivity of the current NuScenesMap.\n :return: The lane_tokens for lanes that are part of a disconnected subtree.\n '... |
def drop_disconnected_lanes(nusc_map: NuScenesMap) -> NuScenesMap:
'\n Remove any disconnected lanes.\n Note: This function is currently not used and we do not recommend using it. Some lanes that we do not drive on are\n disconnected from the other lanes. Removing them would create a single connected gra... |
def get_disconnected_lanes(nusc_map: NuScenesMap) -> List[str]:
'\n Get a list of all disconnected lanes and lane_connectors.\n :param nusc_map: The NuScenesMap instance of a particular map location.\n :return: A list of lane or lane_connector tokens.\n '
disconnected = set()
for (lane_token, ... |
def pixels_to_box_corners(row_pixel: int, column_pixel: int, length_in_pixels: float, width_in_pixels: float, yaw_in_radians: float) -> np.ndarray:
'\n Computes four corners of 2d bounding box for agent.\n The coordinates of the box are in pixels.\n :param row_pixel: Row pixel of the agent.\n :param c... |
def get_track_box(annotation: Dict[(str, Any)], center_coordinates: Tuple[(float, float)], center_pixels: Tuple[(float, float)], resolution: float=0.1) -> np.ndarray:
'\n Get four corners of bounding box for agent in pixels.\n :param annotation: The annotation record of the agent.\n :param center_coordin... |
def reverse_history(history: History) -> History:
'\n Reverse history so that most distant observations are first.\n We do this because we want to draw more recent bounding boxes on top of older ones.\n :param history: result of get_past_for_sample PredictHelper method.\n :return: History with the val... |
def add_present_time_to_history(current_time: List[Dict[(str, Any)]], history: History) -> History:
'\n Adds the sample annotation records from the current time to the\n history object.\n :param current_time: List of sample annotation records from the\n current time. Result of get_annotations_for_... |
def fade_color(color: Tuple[(int, int, int)], step: int, total_number_of_steps: int) -> Tuple[(int, int, int)]:
'\n Fades a color so that past observations are darker in the image.\n :param color: Tuple of ints describing an RGB color.\n :param step: The current time step.\n :param total_number_of_ste... |
def default_colors(category_name: str) -> Tuple[(int, int, int)]:
'\n Maps a category name to an rgb color (without fading).\n :param category_name: Name of object category for the annotation.\n :return: Tuple representing rgb color.\n '
if ('vehicle' in category_name):
return (255, 255, 0... |
def draw_agent_boxes(center_agent_annotation: Dict[(str, Any)], center_agent_pixels: Tuple[(float, float)], agent_history: History, base_image: np.ndarray, get_color: Callable[([str], Tuple[(int, int, int)])], resolution: float=0.1) -> None:
'\n Draws past sequence of agent boxes on the image.\n :param cent... |
class AgentBoxesWithFadedHistory(AgentRepresentation):
'\n Represents the past sequence of agent states as a three-channel\n image with faded 2d boxes.\n '
def __init__(self, helper: PredictHelper, seconds_of_history: float=2, frequency_in_hz: float=2, resolution: float=0.1, meters_ahead: float=40, ... |
def add_foreground_to_image(base_image: np.ndarray, foreground_image: np.ndarray) -> np.ndarray:
'\n Overlays a foreground image on top of a base image without mixing colors. Type uint8.\n :param base_image: Image that will be the background. Type uint8.\n :param foreground_image: Image that will be the ... |
class Rasterizer(Combinator):
'\n Combines images into a three channel image.\n '
def combine(self, data: List[np.ndarray]) -> np.ndarray:
"\n Combine three channel images into a single image.\n :param data: List of images to combine.\n :return: Numpy array representing ima... |
class StaticLayerRepresentation(abc.ABC):
' Represents static map information as a numpy array. '
@abc.abstractmethod
def make_representation(self, instance_token: str, sample_token: str) -> np.ndarray:
raise NotImplementedError()
|
class AgentRepresentation(abc.ABC):
' Represents information of agents in scene as numpy array. '
@abc.abstractmethod
def make_representation(self, instance_token: str, sample_token: str) -> np.ndarray:
raise NotImplementedError()
|
class Combinator(abc.ABC):
' Combines the StaticLayer and Agent representations into a single one. '
@abc.abstractmethod
def combine(self, data: List[np.ndarray]) -> np.ndarray:
raise NotImplementedError()
|
class InputRepresentation():
'\n Specifies how to represent the input for a prediction model.\n Need to provide a StaticLayerRepresentation - how the map is represented,\n an AgentRepresentation - how agents in the scene are represented,\n and a Combinator, how the StaticLayerRepresentation and AgentR... |
class TestRasterizer(unittest.TestCase):
def test(self):
layer_1 = np.zeros((100, 100, 3))
box_1 = cv2.boxPoints(((50, 50), (20, 20), 0))
layer_1 = cv2.fillPoly(layer_1, pts=[np.int0(box_1)], color=(255, 255, 255))
layer_2 = np.zeros((100, 100, 3))
box_2 = cv2.boxPoints(((... |
class Test_convert_to_pixel_coords(unittest.TestCase):
def test_above_and_to_the_right(self):
location = (55, 60)
center_of_image_in_global = (50, 50)
center_of_image_in_pixels = (400, 250)
pixels = utils.convert_to_pixel_coords(location, center_of_image_in_global, center_of_image... |
class Test_get_crops(unittest.TestCase):
def test(self):
(row_crop, col_crop) = utils.get_crops(40, 10, 25, 25, 0.1, 800)
self.assertEqual(row_crop, slice(0, 500))
self.assertEqual(col_crop, slice(150, 650))
|
def convert_to_pixel_coords(location: Tuple[(float, float)], center_of_image_in_global: Tuple[(float, float)], center_of_image_in_pixels: Tuple[(float, float)], resolution: float=0.1) -> Tuple[(int, int)]:
'\n Convert from global coordinates to pixel coordinates.\n :param location: Location in global coordi... |
def get_crops(meters_ahead: float, meters_behind: float, meters_left: float, meters_right: float, resolution: float, image_side_length_pixels: int) -> Tuple[(slice, slice)]:
'\n Crop the excess pixels and centers the agent at the (meters_ahead, meters_left)\n coordinate in the image.\n :param meters_ahea... |
def get_rotation_matrix(image_shape: Tuple[(int, int, int)], yaw_in_radians: float) -> np.ndarray:
'\n Gets a rotation matrix to rotate a three channel image so that\n yaw_in_radians points along the positive y-axis.\n :param image_shape: (Length, width, n_channels).\n :param yaw_in_radians: Angle to ... |
def trim_network_at_index(network: nn.Module, index: int=(- 1)) -> nn.Module:
'\n Returns a new network with all layers up to index from the back.\n :param network: Module to trim.\n :param index: Where to trim the network. Counted from the last layer.\n '
assert (index < 0), f'Param index must be... |
def calculate_backbone_feature_dim(backbone, input_shape: Tuple[(int, int, int)]) -> int:
' Helper to calculate the shape of the fully-connected regression layer. '
tensor = torch.ones(1, *input_shape)
output_feat = backbone.forward(tensor)
return output_feat.shape[(- 1)]
|
class ResNetBackbone(nn.Module):
'\n Outputs tensor after last convolution before the fully connected layer.\n\n Allowed versions: resnet18, resnet34, resnet50, resnet101, resnet152.\n '
def __init__(self, version: str):
'\n Inits ResNetBackbone\n :param version: resnet version... |
class MobileNetBackbone(nn.Module):
'\n Outputs tensor after last convolution before the fully connected layer.\n\n Allowed versions: mobilenet_v2.\n '
def __init__(self, version: str):
'\n Inits MobileNetBackbone.\n :param version: mobilenet version to use.\n '
... |
class CoverNet(nn.Module):
' Implementation of CoverNet https://arxiv.org/pdf/1911.10298.pdf '
def __init__(self, backbone: nn.Module, num_modes: int, n_hidden_layers: List[int]=None, input_shape: Tuple[(int, int, int)]=(3, 500, 500)):
'\n Inits Covernet.\n :param backbone: Backbone mod... |
def mean_pointwise_l2_distance(lattice: torch.Tensor, ground_truth: torch.Tensor) -> torch.Tensor:
'\n Computes the index of the closest trajectory in the lattice as measured by l1 distance.\n :param lattice: Lattice of pre-generated trajectories. Shape [num_modes, n_timesteps, state_dim]\n :param ground... |
class ConstantLatticeLoss():
'\n Computes the loss for a constant lattice CoverNet model.\n '
def __init__(self, lattice: Union[(np.ndarray, torch.Tensor)], similarity_function: Callable[([torch.Tensor, torch.Tensor], int)]=mean_pointwise_l2_distance):
'\n Inits the loss.\n :param... |
def _kinematics_from_tokens(helper: PredictHelper, instance: str, sample: str) -> KinematicsData:
'\n Returns the 2D position, velocity and acceleration vectors from the given track records,\n along with the speed, yaw rate, (scalar) acceleration (magnitude), and heading.\n :param helper: Instance of Pre... |
def _constant_velocity_heading_from_kinematics(kinematics_data: KinematicsData, sec_from_now: float, sampled_at: int) -> np.ndarray:
'\n Computes a constant velocity baseline for given kinematics data, time window\n and frequency.\n :param kinematics_data: KinematicsData for agent.\n :param sec_from_n... |
def _constant_acceleration_and_heading(kinematics_data: KinematicsData, sec_from_now: float, sampled_at: int) -> np.ndarray:
'\n Computes a baseline prediction for the given time window and frequency, under\n the assumption that the acceleration and heading are constant.\n :param kinematics_data: Kinemat... |
def _constant_speed_and_yaw_rate(kinematics_data: KinematicsData, sec_from_now: float, sampled_at: int) -> np.ndarray:
'\n Computes a baseline prediction for the given time window and frequency, under\n the assumption that the (scalar) speed and yaw rate are constant.\n :param kinematics_data: Kinematics... |
def _constant_magnitude_accel_and_yaw_rate(kinematics_data: KinematicsData, sec_from_now: float, sampled_at: int) -> np.ndarray:
'\n Computes a baseline prediction for the given time window and frequency, under\n the assumption that the rates of change of speed and yaw are constant.\n :param kinematics_d... |
class Baseline(abc.ABC):
def __init__(self, sec_from_now: float, helper: PredictHelper):
'\n Inits Baseline.\n :param sec_from_now: How many seconds into the future to make the prediction.\n :param helper: Instance of PredictHelper.\n '
assert ((sec_from_now % 0.5) == ... |
class ConstantVelocityHeading(Baseline):
' Makes predictions according to constant velocity and heading model. '
def __call__(self, token: str) -> Prediction:
'\n Makes prediction.\n :param token: string of format {instance_token}_{sample_token}.\n '
(instance, sample) = ... |
class PhysicsOracle(Baseline):
' Makes several physics-based predictions and picks the one closest to the ground truth. '
def __call__(self, token) -> Prediction:
'\n Makes prediction.\n :param token: string of format {instance_token}_{sample_token}.\n '
(instance, sample... |
class TestBackBones(unittest.TestCase):
def count_layers(self, model):
if isinstance(model[4][0], BasicBlock):
n_convs = 2
elif isinstance(model[4][0], Bottleneck):
n_convs = 3
else:
raise ValueError('Backbone layer block not supported!')
return... |
class TestPhysicsBaselines(unittest.TestCase):
def test_Baselines_raise_error_when_sec_from_now_bad(self):
with self.assertRaises(AssertionError):
ConstantVelocityHeading(2.23, None)
with self.assertRaises(AssertionError):
PhysicsOracle(2.25, None)
PhysicsOracle(5.... |
def export_ego_poses(nusc: NuScenes, out_dir: str):
' Script to render where ego vehicle drives on the maps '
locations = np.unique([log['location'] for log in nusc.log])
if (not os.path.isdir(out_dir)):
os.makedirs(out_dir)
for location in locations:
print('Rendering map {}...'.format... |
def get_poses(nusc: NuScenes, scene_token: str) -> List[dict]:
'\n Return all ego poses for the current scene.\n :param nusc: The NuScenes instance to load the ego poses from.\n :param scene_token: The token of the scene.\n :return: A list of the ego pose dicts.\n '
pose_list = []
scene_rec... |
def get_coordinate(ref_lat: float, ref_lon: float, bearing: float, dist: float) -> Tuple[(float, float)]:
'\n Using a reference coordinate, extract the coordinates of another point in space given its distance and bearing\n to the reference coordinate. For reference, please see: https://www.movable-type.co.u... |
def derive_latlon(location: str, poses: List[Dict[(str, float)]]) -> List[Dict[(str, float)]]:
"\n For each pose value, extract its respective lat/lon coordinate and timestamp.\n \n This makes the following two assumptions in order to work:\n 1. The reference coordinate for each map is in the sout... |
def export_kml(coordinates_per_location: Dict[(str, Dict[(str, List[Dict[(str, float)]])])], output_path: str) -> None:
'\n Export the coordinates of a scene to .kml file.\n :param coordinates_per_location: A dict of lat/lon coordinate dicts for each scene.\n :param output_path: Path of the kml file to w... |
def main(dataroot: str, version: str, output_prefix: str, output_format: str='kml') -> None:
'\n Extract the latlon coordinates for each available pose and write the results to a file.\n The file is organized by location and scene_name.\n :param dataroot: Path of the nuScenes dataset.\n :param version... |
def export_videos(nusc: NuScenes, out_dir: str):
' Export videos of the images displayed in the images. '
scene_tokens = [s['token'] for s in nusc.scene]
if (not os.path.isdir(out_dir)):
os.makedirs(out_dir)
for scene_token in scene_tokens:
scene = nusc.get('scene', scene_token)
... |
def verify_setup(nusc: NuScenes):
'\n Script to verify that the nuScenes installation is complete.\n '
print('Checking that sample_data files are complete...')
for sd in tqdm(nusc.sample_data):
file_path = os.path.join(nusc.dataroot, sd['filename'])
assert os.path.exists(file_path), ... |
class TestNuScenesLidarseg(unittest.TestCase):
def setUp(self):
assert ('NUSCENES' in os.environ), 'Set NUSCENES env. variable to enable tests.'
self.nusc = NuScenes(version='v1.0-mini', dataroot=os.environ['NUSCENES'], verbose=False)
def test_num_classes(self) -> None:
'\n Ch... |
class TestNuScenes(unittest.TestCase):
def test_load(self):
'\n Loads up NuScenes.\n This is intended to simply run the NuScenes class to check for import errors, typos, etc.\n '
assert ('NUSCENES' in os.environ), 'Set NUSCENES env. variable to enable tests.'
nusc = N... |
def get_colormap() -> Dict[(str, Tuple[(int, int, int)])]:
'\n Get the defined colormap.\n :return: A mapping from the class names to the respective RGB values.\n '
classname_to_color = {'noise': (0, 0, 0), 'animal': (70, 130, 180), 'human.pedestrian.adult': (0, 0, 230), 'human.pedestrian.child': (13... |
def load_bin_file(bin_path: str, type: str='lidarseg') -> np.ndarray:
"\n Loads a .bin file containing the lidarseg or lidar panoptic labels.\n :param bin_path: Path to the .bin file.\n :param type: semantic type, 'lidarseg': stored in 8-bit format, 'panoptic': store in 32-bit format.\n :return: An ar... |
def panoptic_to_lidarseg(panoptic_labels: np.ndarray) -> np.ndarray:
'\n Convert panoptic label array to lidarseg label array\n :param panoptic_labels: <np.array, HxW, np.uint16>, encoded in (instance_id + 1000 * category_idx), note instance_id\n for stuff points is 0.\n :return: lidarseg semantic lab... |
def create_splits_logs(split: str, nusc: 'NuScenes') -> List[str]:
'\n Returns the logs in each dataset split of nuScenes.\n Note: Previously this script included the teaser dataset splits. Since new scenes from those logs were added and\n others removed in the full dataset, that code is incompatib... |
def create_splits_scenes(verbose: bool=False) -> Dict[(str, List[str])]:
'\n Similar to create_splits_logs, but returns a mapping from split to scene names, rather than log names.\n The splits are as follows:\n - train/val/test: The standard splits of the nuScenes dataset (700/150/150 scenes).\n - min... |
class TestDataClasses(unittest.TestCase):
def test_load_pointclouds(self):
'\n Loads up lidar and radar pointclouds.\n '
assert ('NUSCENES' in os.environ), 'Set NUSCENES env. variable to enable tests.'
dataroot = os.environ['NUSCENES']
nusc = NuScenes(version='v1.0-m... |
class TestGeometryUtils(unittest.TestCase):
def test_quaternion_yaw(self):
'Test valid and invalid inputs for quaternion_yaw().'
for yaw_in in np.linspace((- 10), 10, 100):
q = Quaternion(axis=(0, 0, 1), angle=yaw_in)
yaw_true = (yaw_in % (2 * np.pi))
if (yaw_t... |
class TestLoad(unittest.TestCase):
fixture = 'testmap.png'
foreground = 255
native_res = 0.1
small_number = 1e-05
half_gt = ((native_res / 2) + small_number)
half_lt = ((native_res / 2) - small_number)
def setUp(self):
mask = np.zeros((50, 40))
mask[(30, 20)] = self.foregr... |
def knn_gather_wrapper(som_node, som_node_knn_I):
'\n\n :param som_node: Bx3xN\n :param som_node_knn_I: BxNxK\n :param som_node_neighbors: Bx3xNxK\n :return:\n '
B = som_node.size()[0]
C = som_node.size()[1]
N = som_node.size()[2]
K = som_node_knn_I.size()[2]
assert (C == 3)
... |
def knn_gather_by_indexing(som_node, som_node_knn_I):
'\n\n :param som_node: BxCxN\n :param som_node_knn_I: BxNxK\n :param som_node_neighbors: BxCxNxK\n :return:\n '
B = som_node.size()[0]
C = som_node.size()[1]
N = som_node.size()[2]
K = som_node_knn_I.size()[2]
som_node_knn_I ... |
class Options():
def __init__(self):
self.is_debug = False
self.is_fine_resolution = True
self.is_remove_ground = False
self.accumulation_frame_num = 3
self.accumulation_frame_skip = 6
self.delta_ij_max = 40
self.translation_max = 10.0
self.crop_ori... |
class Shapes(object):
def __init__(self, dataset_zip=None):
loc = 'data/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz'
if (dataset_zip is None):
self.dataset_zip = np.load(loc, encoding='latin1')
else:
self.dataset_zip = dataset_zip
self.imgs = torch.from_... |
class Dataset(object):
def __init__(self, loc):
self.dataset = torch.load(loc).float().div(255).view((- 1), 1, 64, 64)
def __len__(self):
return self.dataset.size(0)
@property
def ndim(self):
return self.dataset.size(1)
def __getitem__(self, index):
return self.... |
class Faces(Dataset):
LOC = 'data/basel_face_renders.pth'
def __init__(self):
return super(Faces, self).__init__(self.LOC)
|
class Normal(nn.Module):
'Samples from a Normal distribution using the reparameterization trick.\n '
def __init__(self, mu=0, sigma=1):
super(Normal, self).__init__()
self.normalization = Variable(torch.Tensor([np.log((2 * np.pi))]))
self.mu = Variable(torch.Tensor([mu]))
s... |
class Laplace(nn.Module):
'Samples from a Laplace distribution using the reparameterization trick.\n '
def __init__(self, mu=0, scale=1):
super(Laplace, self).__init__()
self.normalization = Variable(torch.Tensor([(- math.log(2))]))
self.mu = Variable(torch.Tensor([mu]))
se... |
class Bernoulli(nn.Module):
'Samples from a Bernoulli distribution where the probability is given\n by the sigmoid of the given parameter.\n '
def __init__(self, p=0.5, stgradient=False):
super(Bernoulli, self).__init__()
p = torch.Tensor([p])
self.p = Variable(torch.log(((p / (... |
class FactorialNormalizingFlow(nn.Module):
def __init__(self, dim, nsteps):
super(FactorialNormalizingFlow, self).__init__()
self.dim = dim
self.nsteps = nsteps
self.x_dist = Normal()
self.scale = nn.Parameter(torch.Tensor(self.nsteps, self.dim))
self.weight = nn.P... |
class STHeaviside(Function):
@staticmethod
def forward(ctx, x):
y = torch.zeros(x.size()).type_as(x)
y[(x >= 0)] = 1
return y
@staticmethod
def backward(ctx, grad_output):
return grad_output
|
def save_checkpoint(state, save, epoch):
if (not os.path.exists(save)):
os.makedirs(save)
filename = os.path.join(save, ('checkpt-%04d.pth' % epoch))
torch.save(state, filename)
|
class AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
class RunningAverageMeter(object):
'Computes and stores the average and current value'
def __init__(self, momentum=0.97):
self.momentum = momentum
self.reset()
def reset(self):
self.val = None
self.avg = 0
def update(self, val):
if (self.val is None):
... |
def isnan(tensor):
return (tensor != tensor)
|
def logsumexp(value, dim=None, keepdim=False):
'Numerically stable implementation of the operation\n\n value.exp().sum(dim, keepdim).log()\n '
if (dim is not None):
(m, _) = torch.max(value, dim=dim, keepdim=True)
value0 = (value - m)
if (keepdim is False):
m = m.sque... |
def load_model_and_dataset(checkpt_filename):
print('Loading model and dataset.')
checkpt = torch.load(checkpt_filename, map_location=(lambda storage, loc: storage))
args = checkpt['args']
state_dict = checkpt['state_dict']
if (not hasattr(args, 'conv')):
args.conv = False
if ((not has... |
def get_dataset(name):
mod = __import__('lisrd.datasets.{}'.format(name), fromlist=[''])
return getattr(mod, _module_to_class(name))
|
def _module_to_class(name):
return ''.join((n.capitalize() for n in name.split('_')))
|
class BaseDataset(metaclass=ABCMeta):
' Base dataset class.\n\n Arguments:\n config: A dictionary containing the configuration parameters.\n device: The device to train/test on.\n '
required_baseconfig = ['batch_size', 'test_batch_size', 'sizes']
def __init__(self, config, device):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.