2

使用线性回归时必须将 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
4

1 回答 1

1

无需将 L2(或 L1)正则化添加到您的线性回归 (LR) 实现中。

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

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

祝你好运!

于 2016-06-17T19:23:43.230 回答