如何在 python 中添加 L1 归一化?

How to add L1 normalization in python?

我正在尝试从头开始编写逻辑回归代码。在我的这段代码中,我认为我的成本导数是我的正则化,但我的任务是添加 L1norm 正则化。如何在 python 中添加这个?这应该添加到我定义成本导数的地方吗?对正确方向的任何帮助表示赞赏。

def Sigmoid(z):
    return 1/(1 + np.exp(-z))

def Hypothesis(theta, X):   
    return Sigmoid(X @ theta)

def Cost_Function(X,Y,theta,m):
    hi = Hypothesis(theta, X)
    _y = Y.reshape(-1, 1)
    J = 1/float(m) * np.sum(-_y * np.log(hi) - (1-_y) * np.log(1-hi))
    return J

def Cost_Function_Derivative(X,Y,theta,m,alpha):
    hi = Hypothesis(theta,X)
    _y = Y.reshape(-1, 1)
    J = alpha/float(m) * X.T @ (hi - _y)
    return J

def Gradient_Descent(X,Y,theta,m,alpha):
    new_theta = theta - Cost_Function_Derivative(X,Y,theta,m,alpha)
    return new_theta

def Accuracy(theta):
    correct = 0
    length = len(X_test)
    prediction = (Hypothesis(theta, X_test) > 0.5) 
    _y = Y_test.reshape(-1, 1)
    correct = prediction == _y
    my_accuracy = (np.sum(correct) / length)*100
    print ('LR Accuracy: ', my_accuracy, "%")

def Logistic_Regression(X,Y,alpha,theta,num_iters):
    m = len(Y)
    for x in range(num_iters):
        new_theta = Gradient_Descent(X,Y,theta,m,alpha)
        theta = new_theta
        if x % 100 == 0:
            print #('theta: ', theta)    
            print #('cost: ', Cost_Function(X,Y,theta,m))
    Accuracy(theta)
ep = .012 
initial_theta = np.random.rand(X_train.shape[1],1) * 2 * ep - ep
alpha = 0.5
iterations = 10000
Logistic_Regression(X_train,Y_train,alpha,initial_theta,iterations)

正则化向成本函数添加一项,以便在最小化成本和最小化模型参数之间取得折衷,以减少过度拟合。您可以通过为正则化项添加标量 e 来控制您想要的折衷程度。

所以只需将theta的L1范数添加到原始成本函数中即可:

J = J + e * np.sum(abs(theta))

既然成本函数中加入了这一项,那么在计算成本函数的梯度时就应该考虑到。

这很简单,因为总和的导数是导数之和。所以现在只需要弄清楚术语 sum(abs(theta)) 的导数是什么。既然是线性项,那么导数就是常数。如果 theta >= 0,则 = 1,如果 theta < 0,则为 -1(请注意,0 处存在数学不确定性,但我们不关心它)。

所以在函数Cost_Function_Derivative中我们添加:

J = J + alpha * e * (theta >= 0).astype(float)