使用numpy-python计算投影和重构错误的函数

问题描述 投票:1回答:1

我想创建一个函数来计算和返回向量b上的向量x的投影以及重建错误。

我的代码如下:

def reconstruction_error(x, b):

    '''The function calculates the projection and reconstruction error
    from projecting a vector x onto a vector b'''


    b = np.matrix(b)

    x_projection_on_b = (b.T @ b/ float(([email protected]))) @ x

    reconstruction_error = (x - x_projection_on_b) @ (x - x_projection_on_b).T 

    return( x_projection_on_b, float(reconstruction_error))

但是重建错误不正确。例如。,

x = np.array([1,1,1])

b = np.array([5, 10, 10])

a, error = reconstruction_error(x, b)

a
matrix([[0.55555556, 1.11111111, 1.11111111]])

error
0.2222222222222222

您的建议将不胜感激

python numpy projection
1个回答
1
投票

不确定terminology,但如果“重建错误”是“拒绝矢量”(原始矢量减去它的投影)的长度,那么你将拥有:

import numpy as np
from numpy.linalg import norm

a = np.array([1,1,1])
b = np.array([5, 10, 10])    

def projection(x, on):
    return np.dot(x, on) / np.dot(on, on) * on

def rejection(x, on):
    return x - projection(x, on)

def reconstruction_error(x, on):
    return norm(rejection(x, on))

>>> reconstruction_error(a, b)
0.4714045207910317
© www.soinside.com 2019 - 2024. All rights reserved.