Exemplo n.º 1
0
def test_reduce_mean(x, axis, kd, dtype_str, tensor_fn, dev_str, call):
    # smoke test
    x = tensor_fn(x, dtype_str, dev_str)
    ret = ivy.reduce_mean(x, axis, kd)
    # type test
    assert ivy.is_array(ret)
    # cardinality test
    if axis is None:
        expected_shape = [1] * len(x.shape) if kd else []
    else:
        axis_ = [axis] if isinstance(axis, int) else axis
        axis_ = [item % len(x.shape) for item in axis_]
        expected_shape = list(x.shape)
        if kd:
            expected_shape = [
                1 if i % len(x.shape) in axis_ else item
                for i, item in enumerate(expected_shape)
            ]
        else:
            [expected_shape.pop(item) for item in axis_]
    expected_shape = [1] if expected_shape == [] else expected_shape
    assert ret.shape == tuple(expected_shape)
    # value test
    assert np.allclose(call(ivy.reduce_mean, x),
                       ivy.numpy.reduce_mean(ivy.to_numpy(x)))
    # compilation test
    helpers.assert_compilable(ivy.reduce_mean)
Exemplo n.º 2
0
def pixel_cost_volume(image1, image2, search_range, batch_shape=None):
    """
    Compute cost volume from image feature patch comparisons between first image
    :math:`\mathbf{X}_1\in\mathbb{R}^{h×w×d}` and second image :math:`\mathbf{X}_2\in\mathbb{R}^{h×w×d}`, as used in
    FlowNet paper.\n
    `[reference] <https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/Dosovitskiy_FlowNet_Learning_Optical_ICCV_2015_paper.pdf>`_

    :param image1: Image 1 *[batch_shape,h,w,D]*
    :type image1: array
    :param image2: Image 2 *[batch_shape,h,w,D]*
    :type image2: array
    :param search_range: Search range for patch comparisons.
    :type search_range: int
    :param batch_shape: Shape of batch. Inferred from inputs if None.
    :type batch_shape: sequence of ints, optional
    :return: Cost volume between the images *[batch_shape,h,w,(search_range*2+1)^2]*
    """

    if batch_shape is None:
        batch_shape = image1.shape[:-3]

    # shapes as list
    batch_shape = list(batch_shape)

    # shape info
    shape = image1.shape
    h = shape[-3]
    w = shape[-2]
    max_offset = search_range * 2 + 1

    # pad dims
    pad_dims = [[0, 0]] * len(batch_shape) + [[search_range, search_range]
                                              ] * 2 + [[0, 0]]

    # BS x (H+2*SR) x (W+2*SR) x D
    padded_lvl = _ivy.zero_pad(image2, pad_dims)

    # create list
    cost_vol = []

    # iterate through patches
    for y in range(0, max_offset):
        for x in range(0, max_offset):
            # BS x H x W x D
            tensor_slice = padded_lvl[..., y:y + h, x:x + w, :]

            # BS x H x W x 1
            cost = _ivy.reduce_mean(image1 * tensor_slice,
                                    axis=-1,
                                    keepdims=True)

            # append to list
            cost_vol.append(cost)

    # BS x H x W x (max_offset^2)
    return _ivy.concatenate(cost_vol, -1)
Exemplo n.º 3
0
 def _log_nested(self, nest, global_step, name_hierarchy, spec):
     if not ivy.exists(self._writer):
         raise Exception('torch must be installed in order to use the file writer for tensorboard logging.')
     if 'global_vector_norm' in spec:
         self._writer.add_scalar(name_hierarchy + '/global vector norm',
                                 ivy.to_scalar(ivy.to_native(nest.vector_norm(global_norm=True))), global_step)
     for k, v in nest.items():
         new_name_hierarchy = name_hierarchy + '/' + k
         if isinstance(v, dict):
             self._log_nested(v, global_step, new_name_hierarchy, spec)
         else:
             if 'mean' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/mean',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_mean(v))), global_step)
             if 'abs_mean' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/abs mean',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_mean(ivy.abs(v)))), global_step)
             if 'var' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/var',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_var(v))), global_step)
             if 'abs_var' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/abs var',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_var(ivy.abs(v)))), global_step)
             if 'min' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/min',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_min(v))), global_step)
             if 'abs_min' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/abs min',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_min(ivy.abs(v)))), global_step)
             if 'max' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/max',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_max(v))), global_step)
             if 'abs_max' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/abs max',
                                         ivy.to_scalar(ivy.to_native(ivy.reduce_max(ivy.abs(v)))), global_step)
             if 'vector_norm' in spec:
                 self._writer.add_scalar(new_name_hierarchy + '/vector norm',
                                         ivy.to_scalar(ivy.to_native(ivy.vector_norm(v))), global_step)
Exemplo n.º 4
0
def compute_cost_and_sdfs(learnable_anchor_vals, anchor_points,
                          start_anchor_val, end_anchor_val, query_points, sim):
    anchor_vals = ivy.concatenate(
        (ivy.expand_dims(start_anchor_val, 0), learnable_anchor_vals,
         ivy.expand_dims(end_anchor_val, 0)), 0)
    joint_angles = ivy_robot.sample_spline_path(anchor_points, anchor_vals,
                                                query_points)
    link_positions = ivy.transpose(
        sim.ivy_manipulator.sample_links(joint_angles), (1, 0, 2))
    length_cost = compute_length(link_positions)
    sdf_vals = sim.sdf(ivy.reshape(link_positions, (-1, 3)))
    coll_cost = -ivy.reduce_mean(sdf_vals)
    total_cost = length_cost + coll_cost * 10
    return total_cost[0], joint_angles, link_positions, ivy.reshape(
        sdf_vals, (-1, 100, 1))
Exemplo n.º 5
0
    def get_reward(self):
        """
        Get reward based on current state

        :return: Reward array
        """
        # Goal proximity.
        x = ivy.reduce_sum(ivy.cos(self.angles), -1)
        y = ivy.reduce_sum(ivy.sin(self.angles), -1)
        xy = ivy.concatenate([ivy.expand_dims(x, 0),
                              ivy.expand_dims(y, 0)],
                             axis=0)
        rew = ivy.reshape(
            ivy.exp(-1 * ivy.reduce_sum((xy - self.goal_xy)**2, -1)), (-1, ))
        return ivy.reduce_mean(rew, axis=0, keepdims=True)
Exemplo n.º 6
0
def compute_cost_and_sdfs(learnable_anchor_vals, anchor_points,
                          start_anchor_val, end_anchor_val, query_points, sim):
    anchor_vals = ivy.concatenate(
        (ivy.expand_dims(start_anchor_val, 0), learnable_anchor_vals,
         ivy.expand_dims(end_anchor_val, 0)), 0)
    poses = ivy_robot.sample_spline_path(anchor_points, anchor_vals,
                                         query_points)
    inv_ext_mat_query_vals = ivy_mech.rot_vec_pose_to_mat_pose(poses)
    body_positions = ivy.transpose(
        sim.ivy_drone.sample_body(inv_ext_mat_query_vals), (1, 0, 2))
    length_cost = compute_length(body_positions)
    sdf_vals = sim.sdf(ivy.reshape(body_positions, (-1, 3)))
    coll_cost = -ivy.reduce_mean(sdf_vals)
    total_cost = length_cost + coll_cost * 10
    return total_cost[0], poses, body_positions, ivy.reshape(
        sdf_vals, (-1, 100, 1))
Exemplo n.º 7
0
 def _compute_cost(self, network, batch, dev_str, v=None):
     network_output = network(batch.input, v=v)
     return ivy.reduce_mean((network_output - batch.target)**2)[0]
Exemplo n.º 8
0
def compute_length(query_vals):
    start_vals = query_vals[:, 0:-1]
    end_vals = query_vals[:, 1:]
    dists_sqrd = ivy.maximum((end_vals - start_vals)**2, 1e-12)
    distances = ivy.reduce_sum(dists_sqrd, -1)**0.5
    return ivy.reduce_mean(ivy.reduce_sum(distances, 1))
Exemplo n.º 9
0
 def loss_fn(v_):
     out = linear_layer(x, v=v_)
     return ivy.reduce_mean(out)[0]
Exemplo n.º 10
0
 def loss_fn(v_):
     out, (state_h, state_c) = lstm_layer(x, v=v_)
     return ivy.reduce_mean(out)[0]
Exemplo n.º 11
0
 def _loss_fn(self, model, rays_o, rays_d, target, v=None):
     rgb, depth = ivy_vision.render_implicit_features_and_depth(
         model, rays_o, rays_d, near=ivy.ones(self._img_dims, dev_str=self._dev_str) * 2,
         far=ivy.ones(self._img_dims, dev_str=self._dev_str) * 6, samples_per_ray=self._num_samples, v=v)
     return ivy.reduce_mean((rgb - target) ** 2)[0]
Exemplo n.º 12
0
 def loss_fn(v):
     pred = model(esm_obs, v=v)
     return ivy.reduce_mean((pred - target)**2)
Exemplo n.º 13
0
 def loss_fn(v_):
     out = module(x, v=v_)
     return ivy.reduce_mean(out)[0]