使用线性回归时,必须将L2正则化添加到成本函数中吗?

我没有添加l2或在计算成本时未考虑在内。错了吗

以下代码段应足够:

def gradient(self, X, Y, alpha, minibatch_size):

    predictions = None

    for batch in self.iterate_minibatches(X, Y, minibatch_size, shuffle=True):
        x, y = batch
        predictions = x.dot(self.theta)

        for it in range(self.theta.size):
            temp = x[:, it]
            temp.shape = (y.size, 1)

            errors_x1 = (predictions - y) * temp

            self.theta[it] = self.theta[it] - alpha * (1.0 / y.size) * errors_x1.sum() + self.lambda_l2 * self.theta[it] * self.theta[it].T

    print self.cost(X, Y, self.theta)


def cost(self, X, Y, theta, store=True):
    predictions = X.dot(theta)

    from sklearn.metrics import mean_squared_error
    cost = mean_squared_error(Y, predictions, sample_weight=None, multioutput='uniform_average')

    if store is True:
        self.cost_history.append(cost)

    return cost

最佳答案

不必在线性回归(LR)实现中添加L2(或L1)正则化。

但是,将L2正则项添加到我们的成本函数中比不使用正则项的LR具有优势。最重要的是,正则项可以帮助您减少模型的过拟合并提高模型的泛化性。具有L2正则化的LR通常称为“里奇回归”。

除了Ridge回归之外,具有L1正则化的LR被称为Lasso回归。如果使用套索回归构建回归模型,则您的模型将是稀疏模型。因此,套索也可以用于特征选择。

祝好运!

10-04 15:01