【问题标题】:How do I get r_squared from loss minimization with constraints using numpy?如何使用 numpy 从具有约束的损失最小化中获得 r_squared?
【发布时间】:2018-02-01 05:51:39
【问题描述】:

使用带约束的损失最小化对 numpy 和 scipy 执行回归。这是一个例子:

y_values 是具有 numObservations 个值的向量

x_matrix_trans 是 x 矩阵

我们想用一个约束来求解 y = Xc,这样一些系数乘以一些输入权重必须总和为 0。

    def constraint1(x):
        res = 0
        for i in range (0, NUM_WEIGHTS):
            res = res + x[CONST_VAL + i] * weights[CONST_VAL + i]
        return res

    def loss(x):
        return np.sum(np.square((np.dot(x, x_matrix_trans) - y_values)))

    cons = ({'type': 'eq',
             'fun' : constraint1})

    x0 = np.zeros(x_matrix_trans.shape[0])        
    res = minimize(loss, x0, method='SLSQP',constraints=cons, options={'disp': True, 'maxiter' : 1000, 'ftol' : 1e-07}) 
    print(res.x)

我的回归在 res.x 中产生了正确的值,但我还需要计算 r_squared 和调整后的 r_squared。我试图计算 r_squared 但结果不正确。

这是我尝试计算 r_squared 的方法:

    ymeas = y_values
    yfit = np.dot(res.x, x_matrix_trans)
    ss_res = np.sum((ymeas - yfit) ** 2)
    ss_tot = np.var(ymeas) * len(ymeas)
    rsq = 1 - ss_res / ss_tot

这是我尝试计算调整后的 r_squared 的方法:

    adjRsq = 0.0
    if ((num_coefficients - num_observations - 1) != 0):
        adjRsq = rsq - (1-rsq)*(num_coefficients - 1)/( num_observations -num_coefficients - 1)

谢谢。

【问题讨论】:

  • 也许你可以说你的结果在什么意义上是不正确的。

标签: python numpy scipy statistics regression


【解决方案1】:

事实证明我的回答一直都是正确的。除了根据维基百科调整的 r_square 应该是

adjRsq = rsq - (1-rsq)*(num_coeff)/(num_observations-num_coeff-1)

而不是

adjRsq = rsq - (1-rsq)*(num_coeff - 1)/(num_observations-num_coeff-1)

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2011-04-27
    • 2013-09-17
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多