Python tensorflow.matrix_inverse() Examples

The following are 30 code examples of tensorflow.matrix_inverse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow , or try the search function .
Example #1
Source File: linear_regression.py    From multilabel-image-classification-tensorflow with MIT License 6 votes vote down vote up
def solve_ridge(x, y, ridge_factor):
  with tf.name_scope("solve_ridge"):
    # Added a column of ones to the end of the feature matrix for bias
    A = tf.concat([x, tf.ones((x.shape.as_list()[0], 1))], axis=1)

    # Analytic solution for the ridge regression loss
    inv_target = tf.matmul(A, A, transpose_a=True)
    np_diag_penalty = ridge_factor * np.ones(
        A.shape.as_list()[1], dtype="float32")
    # Remove penalty on bias component of weights
    np_diag_penalty[-1] = 0.
    diag_penalty = tf.constant(np_diag_penalty)
    inv_target += tf.diag(diag_penalty)

    inv = tf.matrix_inverse(inv_target)
    w = tf.matmul(inv, tf.matmul(A, y, transpose_a=True))
    return w 
Example #2
Source File: components.py    From strsum with Apache License 2.0 6 votes vote down vote up
def get_matrix_tree(r, A):
    L = tf.reduce_sum(A, 1)
    L = tf.matrix_diag(L)
    L = L - A

    r_diag = tf.matrix_diag(r)
    LL = L + r_diag

    LL_inv = tf.matrix_inverse(LL)  #batch_l, doc_l, doc_l
    LL_inv_diag_ = tf.matrix_diag_part(LL_inv)

    d0 = tf.multiply(r, LL_inv_diag_)

    LL_inv_diag = tf.expand_dims(LL_inv_diag_, 2)

    tmp1 = tf.multiply(A, tf.matrix_transpose(LL_inv_diag))
    tmp2 = tf.multiply(A, tf.matrix_transpose(LL_inv))

    d = tmp1 - tmp2
    d = tf.concat([tf.expand_dims(d0,[1]), d], 1)
    return d 
Example #3
Source File: problem_generator.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #4
Source File: layers.py    From face_landmark_dnn with MIT License 6 votes vote down vote up
def LandmarkTransformLayer(Landmark, Param, Inverse=False):
    '''
    Landmark: [N, N_LANDMARK x 2]
    Param: [N, 6]
    return: [N, N_LANDMARK x 2]
    '''

    A = tf.reshape(Param[:, 0:4], [-1, 2, 2])
    T = tf.reshape(Param[:, 4:6], [-1, 1, 2])

    Landmark = tf.reshape(Landmark, [-1, N_LANDMARK, 2])
    if Inverse:
        A = tf.matrix_inverse(A)
        T = tf.matmul(-T, A)

    return tf.reshape(tf.matmul(Landmark, A) + T, [-1, N_LANDMARK * 2]) 
Example #5
Source File: problem_generator.py    From yolo_v2 with Apache License 2.0 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #6
Source File: geo_utils.py    From DeepMatchVO with MIT License 6 votes vote down vote up
def pixel2cam(depth, pixel_coords, intrinsics, is_homogeneous=True):
    """Transforms coordinates in the pixel frame to the camera frame.

    Args:
      depth: [batch, height, width]
      pixel_coords: homogeneous pixel coordinates [batch, 3, height, width]
      intrinsics: camera intrinsics [batch, 3, 3]
      is_homogeneous: return in homogeneous coordinates
    Returns:
      Coords in the camera frame [batch, 3 (4 if homogeneous), height, width]
    """
    batch, height, width = depth.get_shape().as_list()
    depth = tf.reshape(depth, [batch, 1, -1])
    pixel_coords = tf.reshape(pixel_coords, [batch, 3, -1])
    cam_coords = tf.matmul(tf.matrix_inverse(intrinsics), pixel_coords) * depth
    if is_homogeneous:
        ones = tf.ones([batch, 1, height*width])
        cam_coords = tf.concat([cam_coords, ones], axis=1)
    cam_coords = tf.reshape(cam_coords, [batch, -1, height, width])
    return cam_coords 
Example #7
Source File: gaussian_sampler_example.py    From hamiltonian-monte-carlo with Apache License 2.0 6 votes vote down vote up
def gaussian_log_posterior(x, covariance):
    """Evaluate the unormalized log posterior from a zero-mean
    Gaussian distribution, with the specifed covariance matrix
    
    Parameters
    ----------
    x : tf.Variable
        Sample ~ target distribution
    covariance : tf.Variable N x N 
        Covariance matrix for N-dim Gaussian

        For diagonal - [[sigma_1^2, 0], [0, sigma_2^2]]

    Returns
    -------
    logp : float
        Unormalized log p(x)
    """
    covariance_inverse = tf.matrix_inverse(covariance)

    xA = tf.matmul(x, covariance_inverse)
    xAx = tf.matmul(xA, tf.transpose(x))
    return xAx / 2.0 
Example #8
Source File: transform.py    From 3D-point-cloud-generation with MIT License 6 votes vote down vote up
def fuse3D(opt,XYZ,maskLogit,fuseTrans): # [B,H,W,3V],[B,H,W,V]
	with tf.name_scope("transform_fuse3D"):
		XYZ = tf.transpose(XYZ,perm=[0,3,1,2]) # [B,3V,H,W]
		maskLogit = tf.transpose(maskLogit,perm=[0,3,1,2]) # [B,V,H,W]
		# 2D to 3D coordinate transformation
		invKhom = np.linalg.inv(opt.Khom2Dto3D)
		invKhomTile = np.tile(invKhom,[opt.batchSize,opt.outViewN,1,1])
		# viewpoint rigid transformation
		q_view = fuseTrans
		t_view = np.tile([0,0,-opt.renderDepth],[opt.outViewN,1]).astype(np.float32)
		RtHom_view = transParamsToHomMatrix(q_view,t_view)
		RtHomTile_view = tf.tile(tf.expand_dims(RtHom_view,0),[opt.batchSize,1,1,1])
		invRtHomTile_view = tf.matrix_inverse(RtHomTile_view)
		# effective transformation
		RtHomTile = tf.matmul(invRtHomTile_view,invKhomTile) # [B,V,4,4]
		RtTile = RtHomTile[:,:,:3,:] # [B,V,3,4]
		# transform depth stack
		ML = tf.reshape(maskLogit,[opt.batchSize,1,-1]) # [B,1,VHW]
		XYZhom = get3DhomCoord(XYZ,opt) # [B,V,4,HW]
		XYZid = tf.matmul(RtTile,XYZhom) # [B,V,3,HW]
		# fuse point clouds
		XYZid = tf.reshape(tf.transpose(XYZid,perm=[0,2,1,3]),[opt.batchSize,3,-1]) # [B,3,VHW]
	return XYZid,ML # [B,1,VHW]

# build transformer (render 2D depth) 
Example #9
Source File: linear_regression.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def solve_ridge(x, y, ridge_factor):
  with tf.name_scope("solve_ridge"):
    # Added a column of ones to the end of the feature matrix for bias
    A = tf.concat([x, tf.ones((x.shape.as_list()[0], 1))], axis=1)

    # Analytic solution for the ridge regression loss
    inv_target = tf.matmul(A, A, transpose_a=True)
    np_diag_penalty = ridge_factor * np.ones(
        A.shape.as_list()[1], dtype="float32")
    # Remove penalty on bias component of weights
    np_diag_penalty[-1] = 0.
    diag_penalty = tf.constant(np_diag_penalty)
    inv_target += tf.diag(diag_penalty)

    inv = tf.matrix_inverse(inv_target)
    w = tf.matmul(inv, tf.matmul(A, y, transpose_a=True))
    return w 
Example #10
Source File: matrix_inverse_op_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _verifyInverse(self, x):
    for np_type in [np.float32, np.float64]:
      for adjoint in False, True:
        y = x.astype(np_type)
        with self.test_session():
          # Verify that x^{-1} * x == Identity matrix.
          inv = tf.matrix_inverse(y, adjoint=adjoint)
          tf_ans = tf.batch_matmul(inv, y, adj_y=adjoint)
          np_ans = np.identity(y.shape[-1])
          if x.ndim > 2:
            tiling = list(y.shape)
            tiling[-2:] = [1, 1]
            np_ans = np.tile(np_ans, tiling)
          out = tf_ans.eval()
          self.assertAllClose(np_ans, out)
          self.assertShapeEqual(y, tf_ans) 
Example #11
Source File: homography.py    From stereo-magnification with Apache License 2.0 6 votes vote down vote up
def inv_homography(k_s, k_t, rot, t, n_hat, a):
  """Computes inverse homography matrix between two cameras via a plane.

  Args:
      k_s: intrinsics for source cameras, [..., 3, 3] matrices
      k_t: intrinsics for target cameras, [..., 3, 3] matrices
      rot: relative rotations between source and target, [..., 3, 3] matrices
      t: [..., 3, 1], translations from source to target camera. Mapping a 3D
        point p from source to target is accomplished via rot * p + t.
      n_hat: [..., 1, 3], plane normal w.r.t source camera frame
      a: [..., 1, 1], plane equation displacement
  Returns:
      homography: [..., 3, 3] inverse homography matrices (homographies mapping
        pixel coordinates from target to source).
  """
  with tf.name_scope('inv_homography'):
    rot_t = tf.matrix_transpose(rot)
    k_t_inv = tf.matrix_inverse(k_t, name='k_t_inv')

    denom = a - tf.matmul(tf.matmul(n_hat, rot_t), t)
    numerator = tf.matmul(tf.matmul(tf.matmul(rot_t, t), n_hat), rot_t)
    inv_hom = tf.matmul(
        tf.matmul(k_s, rot_t + divide_safe(numerator, denom)),
        k_t_inv, name='inv_hom')
    return inv_hom 
Example #12
Source File: glow.py    From WaveGlow with MIT License 6 votes vote down vote up
def invertible1x1Conv(z, n_channels, forward=True, name='inv1x1conv'):
    with tf.variable_scope(name):
        shape = tf.shape(z)
        batch_size, length, channels = shape[0], shape[1], shape[2]

        # sample a random orthogonal matrix to initialize weight
        W_init = np.linalg.qr(np.random.randn(n_channels, n_channels))[0].astype('float32')
        W = create_variable_init('W', initializer=W_init)

        # compute log determinant
        det = tf.log(tf.abs(tf.cast(tf.matrix_determinant(tf.cast(W, tf.float64)), tf.float32)))
        logdet = det * tf.cast(batch_size * length, 'float32')
        if forward:
            _W = tf.reshape(W, [1, n_channels, n_channels])
            z = tf.nn.conv1d(z, _W, stride=1, padding='SAME')
            return z, logdet
        else:
            _W = tf.matrix_inverse(W)
            _W = tf.reshape(_W, [1, n_channels, n_channels])
            z = tf.nn.conv1d(z, _W, stride=1, padding='SAME')
            return z 
Example #13
Source File: problem_generator.py    From object_detection_kitti with Apache License 2.0 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #14
Source File: stneuronet.py    From STNeuroNet with Apache License 2.0 6 votes vote down vote up
def layer_op(self, input_tensor):
        sz = input_tensor.get_shape().as_list()
        grid_warper = AffineGridWarperLayer(sz[1:-1],
                                            sz[1:-1])

        resampler = ResamplerLayer(interpolation=self.interpolation,
                                   boundary=self.boundary)
        relative_transform = self.transform_func(sz[0])
        to_relative=tf.tile([[[2./(sz[1]-1), 0., 0., -1.],
                              [0., 2. / (sz[2] - 1), 0., -1.],
                              [0., 0., 2. / (sz[3] - 1), -1.],
                              [0., 0., 0., 1.]]],[sz[0],1,1])
        from_relative=tf.matrix_inverse(to_relative)
        voxel_transform = tf.matmul(from_relative,
                                    tf.matmul(relative_transform,to_relative))
        warp_parameters = tf.reshape(voxel_transform[:, 0:3, 0:4],
                                     [sz[0], 12])
        grid = grid_warper(warp_parameters)
        return resampler(input_tensor,grid) 
Example #15
Source File: problem_generator.py    From object_detection_with_tensorflow with MIT License 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #16
Source File: utils.py    From GeoNet with MIT License 6 votes vote down vote up
def pixel2cam(depth, pixel_coords, intrinsics, is_homogeneous=True):
  """Transforms coordinates in the pixel frame to the camera frame.

  Args:
    depth: [batch, height, width]
    pixel_coords: homogeneous pixel coordinates [batch, 3, height, width]
    intrinsics: camera intrinsics [batch, 3, 3]
    is_homogeneous: return in homogeneous coordinates
  Returns:
    Coords in the camera frame [batch, 3 (4 if homogeneous), height, width]
  """
  batch, height, width = depth.get_shape().as_list()
  depth = tf.reshape(depth, [batch, 1, -1])
  pixel_coords = tf.reshape(pixel_coords, [batch, 3, -1])
  cam_coords = tf.matmul(tf.matrix_inverse(intrinsics), pixel_coords) * depth
  if is_homogeneous:
    ones = tf.ones([batch, 1, height*width])
    cam_coords = tf.concat([cam_coords, ones], axis=1)
  cam_coords = tf.reshape(cam_coords, [batch, -1, height, width])
  return cam_coords 
Example #17
Source File: LEGOLearner.py    From LEGO with MIT License 6 votes vote down vote up
def get_multi_scale_intrinsics(self, raw_cam_mat, num_scales):
        proj_cam2pix = []
        # Scale the intrinsics accordingly for each scale
        for s in range(num_scales):
            fx = raw_cam_mat[0,0]/(2 ** s)
            fy = raw_cam_mat[1,1]/(2 ** s)
            cx = raw_cam_mat[0,2]/(2 ** s)
            cy = raw_cam_mat[1,2]/(2 ** s)
            r1 = tf.stack([fx, 0, cx])
            r2 = tf.stack([0, fy, cy])
            r3 = tf.constant([0.,0.,1.])
            proj_cam2pix.append(tf.stack([r1, r2, r3]))
        proj_cam2pix = tf.stack(proj_cam2pix)
        proj_pix2cam = tf.matrix_inverse(proj_cam2pix)
        proj_cam2pix.set_shape([num_scales,3,3])
        proj_pix2cam.set_shape([num_scales,3,3])
        return proj_cam2pix, proj_pix2cam 
Example #18
Source File: projection.py    From layered-scene-inference with Apache License 2.0 6 votes vote down vote up
def forward_projection_matrix(k_s, k_t, rot, t):
  """Projection matrix for transforming a src pixel coordinates to target frame.

  Args:
      k_s: intrinsics for source cameras, are [...] X 3 X 3 matrices
      k_t: intrinsics for target cameras, are [...] X 3 X 3 matrices
      rot: relative rotation from source to target, are [...] X 3 X 3 matrices
      t: [...] X 3 X 1 translations from source to target camera
  Returns:
      transform: [...] X 4 X 4 projection matrix
  """
  with tf.name_scope('forward_projection_matrix'):
    k_s_inv = tf.matrix_inverse(k_s, name='k_s_inv')
    return tf.matmul(
        pad_intrinsic(k_t),
        tf.matmul(pad_extrinsic(rot, t), pad_intrinsic(k_s_inv))) 
Example #19
Source File: projection.py    From layered-scene-inference with Apache License 2.0 6 votes vote down vote up
def inverse_projection_matrix(k_s, k_t, rot, t):
  """Projection matrix for transforming a trg pixel coordinates to src frame.

  Args:
      k_s: intrinsics for source cameras, are [...] X 3 X 3 matrices
      k_t: intrinsics for target cameras, are [...] X 3 X 3 matrices
      rot: relative rotation from source to target, are [...] X 3 X 3 matrices
      t: [...] X 3 X 1 translations from source to target camera
  Returns:
      transform: [...] X 4 X 4 projection matrix
  """
  with tf.name_scope('inverse_projection_matrix'):
    k_t_inv = tf.matrix_inverse(k_t, name='k_t_inv')
    rot_inv = nn_helpers.transpose(rot)
    t_inv = -1 * tf.matmul(rot_inv, t)
    return tf.matmul(
        pad_intrinsic(k_s),
        tf.matmul(pad_extrinsic(rot_inv, t_inv), pad_intrinsic(k_t_inv))) 
Example #20
Source File: homography.py    From layered-scene-inference with Apache License 2.0 6 votes vote down vote up
def inv_homography(k_s, k_t, rot, t, n_hat, a):
  """Computes inverse homography matrix.

  Args:
      k_s: intrinsics for source cameras, are [...] X 3 X 3 matrices
      k_t: intrinsics for target cameras, are [...] X 3 X 3 matrices
      rot: relative rotation, are [...] X 3 X 3 matrices
      t: [...] X 3 X 1, translations from source to target camera
      n_hat: [...] X 1 X 3, plane normal w.r.t source camera frame
      a: [...] X 1 X 1, plane equation displacement
  Returns:
      homography: [...] X 3 X 3 inverse homography matrices
  """
  with tf.name_scope('inv_homography'):
    rot_t = nn_helpers.transpose(rot)
    k_t_inv = tf.matrix_inverse(k_t, name='k_t_inv')

    denom = a - tf.matmul(tf.matmul(n_hat, rot_t), t)
    numerator = tf.matmul(tf.matmul(tf.matmul(rot_t, t), n_hat), rot_t)
    inv_hom = tf.matmul(
        tf.matmul(k_s, rot_t + nn_helpers.divide_safe(numerator, denom)),
        k_t_inv,
        name='inv_hom')
    return inv_hom 
Example #21
Source File: homography.py    From layered-scene-inference with Apache License 2.0 6 votes vote down vote up
def inv_homography_dmat(k_t, rot, t, n_hat, a):
  """Computes M where M*(u,v,1) = d_t.

  Args:
      k_t: intrinsics for target cameras, are [...] X 3 X 3 matrices
      rot: relative rotation, are [...] X 3 X 3 matrices
      t: [...] X 3 X 1, translations from source to target camera
      n_hat: [...] X 1 X 3, plane normal w.r.t source camera frame
      a: [...] X 1 X 1, plane equation displacement
  Returns:
      d_mat: [...] X 1 X 3 matrices
  """
  with tf.name_scope('inv_homography'):
    rot_t = nn_helpers.transpose(rot)
    k_t_inv = tf.matrix_inverse(k_t, name='k_t_inv')

    denom = a - tf.matmul(tf.matmul(n_hat, rot_t), t)
    d_mat = nn_helpers.divide_safe(
        -1 * tf.matmul(tf.matmul(n_hat, rot_t), k_t_inv), denom, name='dmat')
    return d_mat 
Example #22
Source File: problem_generator.py    From g-tensorflow-models with Apache License 2.0 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #23
Source File: linear_regression.py    From g-tensorflow-models with Apache License 2.0 6 votes vote down vote up
def solve_ridge(x, y, ridge_factor):
  with tf.name_scope("solve_ridge"):
    # Added a column of ones to the end of the feature matrix for bias
    A = tf.concat([x, tf.ones((x.shape.as_list()[0], 1))], axis=1)

    # Analytic solution for the ridge regression loss
    inv_target = tf.matmul(A, A, transpose_a=True)
    np_diag_penalty = ridge_factor * np.ones(
        A.shape.as_list()[1], dtype="float32")
    # Remove penalty on bias component of weights
    np_diag_penalty[-1] = 0.
    diag_penalty = tf.constant(np_diag_penalty)
    inv_target += tf.diag(diag_penalty)

    inv = tf.matrix_inverse(inv_target)
    w = tf.matmul(inv, tf.matmul(A, y, transpose_a=True))
    return w 
Example #24
Source File: problem_generator.py    From models with Apache License 2.0 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #25
Source File: linear_regression.py    From models with Apache License 2.0 6 votes vote down vote up
def solve_ridge(x, y, ridge_factor):
  with tf.name_scope("solve_ridge"):
    # Added a column of ones to the end of the feature matrix for bias
    A = tf.concat([x, tf.ones((x.shape.as_list()[0], 1))], axis=1)

    # Analytic solution for the ridge regression loss
    inv_target = tf.matmul(A, A, transpose_a=True)
    np_diag_penalty = ridge_factor * np.ones(
        A.shape.as_list()[1], dtype="float32")
    # Remove penalty on bias component of weights
    np_diag_penalty[-1] = 0.
    diag_penalty = tf.constant(np_diag_penalty)
    inv_target += tf.diag(diag_penalty)

    inv = tf.matrix_inverse(inv_target)
    w = tf.matmul(inv, tf.matmul(A, y, transpose_a=True))
    return w 
Example #26
Source File: problem_generator.py    From multilabel-image-classification-tensorflow with MIT License 6 votes vote down vote up
def objective(self, parameters, data=None, labels=None):
    theta_a = parameters[0]
    theta_b = parameters[1]

    # Compute theta_c from theta_a and theta_b.
    p = tf.matmul(self.a, theta_a) * tf.matmul(self.b, theta_b)
    p_trans = tf.transpose(p, name="p_trans")
    p_inv = tf.matmul(
        tf.matrix_inverse(tf.matmul(p_trans, p)), p_trans, name="p_inv")
    theta_c = tf.matmul(p_inv, self.c, name="theta_c")

    # Compute the "predicted" value of c.
    c_hat = tf.matmul(p, theta_c, name="c_hat")

    # Compute the loss (sum of squared errors).
    loss = tf.reduce_sum((c_hat - self.c)**2, name="loss")

    return loss 
Example #27
Source File: filter.py    From kvae with MIT License 6 votes vote down vote up
def backward_step_fn(self, params, inputs):
        """
        Backwards step over a batch, to be used in tf.scan
        :param params:
        :param inputs: (batch_size, variable dimensions)
        :return:
        """
        mu_back, Sigma_back = params
        mu_pred_tp1, Sigma_pred_tp1, mu_filt_t, Sigma_filt_t, A = inputs

        # J_t = tf.matmul(tf.reshape(tf.transpose(tf.matrix_inverse(Sigma_pred_tp1), [0, 2, 1]), [-1, self.dim_z]),
        #                 self.A)
        # J_t = tf.transpose(tf.reshape(J_t, [-1, self.dim_z, self.dim_z]), [0, 2, 1])
        J_t = tf.matmul(tf.transpose(A, [0, 2, 1]), tf.matrix_inverse(Sigma_pred_tp1))
        J_t = tf.matmul(Sigma_filt_t, J_t)

        mu_back = mu_filt_t + tf.matmul(J_t, mu_back - mu_pred_tp1)
        Sigma_back = Sigma_filt_t + tf.matmul(J_t, tf.matmul(Sigma_back - Sigma_pred_tp1, J_t, adjoint_b=True))

        return mu_back, Sigma_back 
Example #28
Source File: homography_warping.py    From MVSNet with MIT License 5 votes vote down vote up
def get_homographies(left_cam, right_cam, depth_num, depth_start, depth_interval):
    with tf.name_scope('get_homographies'):
        # cameras (K, R, t)
        R_left = tf.slice(left_cam, [0, 0, 0, 0], [-1, 1, 3, 3])
        R_right = tf.slice(right_cam, [0, 0, 0, 0], [-1, 1, 3, 3])
        t_left = tf.slice(left_cam, [0, 0, 0, 3], [-1, 1, 3, 1])
        t_right = tf.slice(right_cam, [0, 0, 0, 3], [-1, 1, 3, 1])
        K_left = tf.slice(left_cam, [0, 1, 0, 0], [-1, 1, 3, 3])
        K_right = tf.slice(right_cam, [0, 1, 0, 0], [-1, 1, 3, 3])

        # depth 
        depth_num = tf.reshape(tf.cast(depth_num, 'int32'), [])
        depth = depth_start + tf.cast(tf.range(depth_num), tf.float32) * depth_interval
        # preparation
        num_depth = tf.shape(depth)[0]
        K_left_inv = tf.matrix_inverse(tf.squeeze(K_left, axis=1))
        R_left_trans = tf.transpose(tf.squeeze(R_left, axis=1), perm=[0, 2, 1])
        R_right_trans = tf.transpose(tf.squeeze(R_right, axis=1), perm=[0, 2, 1])

        fronto_direction = tf.slice(tf.squeeze(R_left, axis=1), [0, 2, 0], [-1, 1, 3])          # (B, D, 1, 3)

        c_left = -tf.matmul(R_left_trans, tf.squeeze(t_left, axis=1))
        c_right = -tf.matmul(R_right_trans, tf.squeeze(t_right, axis=1))                        # (B, D, 3, 1)
        c_relative = tf.subtract(c_right, c_left)        

        # compute
        batch_size = tf.shape(R_left)[0]
        temp_vec = tf.matmul(c_relative, fronto_direction)
        depth_mat = tf.tile(tf.reshape(depth, [batch_size, num_depth, 1, 1]), [1, 1, 3, 3])

        temp_vec = tf.tile(tf.expand_dims(temp_vec, axis=1), [1, num_depth, 1, 1])

        middle_mat0 = tf.eye(3, batch_shape=[batch_size, num_depth]) - temp_vec / depth_mat
        middle_mat1 = tf.tile(tf.expand_dims(tf.matmul(R_left_trans, K_left_inv), axis=1), [1, num_depth, 1, 1])
        middle_mat2 = tf.matmul(middle_mat0, middle_mat1)

        homographies = tf.matmul(tf.tile(K_right, [1, num_depth, 1, 1])
                     , tf.matmul(tf.tile(R_right, [1, num_depth, 1, 1])
                     , middle_mat2))

    return homographies 
Example #29
Source File: dagmm.py    From AnomalyDetectionTransformations with MIT License 5 votes vote down vote up
def _calc_component_density(z, phi, mu, sigma):
        sig_inv = tf.matrix_inverse(sigma)
        sig_sqrt_det = K.sqrt(tf.matrix_determinant(2 * np.pi * sigma) + K.epsilon())
        density = phi * (K.exp(-0.5 * K.sum(K.dot(z - mu, sig_inv) * (z - mu),
                                            axis=-1,
                                            keepdims=True)) / sig_sqrt_det) + K.epsilon()

        return density 
Example #30
Source File: utils.py    From kfac with Apache License 2.0 5 votes vote down vote up
def posdef_inv_matrix_inverse(tensor, identity, damping):
  """Computes inverse(tensor + damping * identity) directly."""
  return tf.matrix_inverse(tensor + damping * identity)