python - 这段用于正则化线性回归的 Python 代码有什么问题?

标签 python algorithm numpy machine-learning linear-regression

我用 numpy 写代码(theta,X 是 numpy 数组):

def CostRegFunction(X, y, theta, lambda_):
    m = len(X)
    # add bias unit
    X = np.concatenate((np.ones((m,1)),X),1)

    H = np.dot(X,theta)

    J = (1 / (2 * m)) * (np.sum([(H[i] - y[i][0])**2 for i in range(len(H))])) + (lambda_ / (2 * m)) * np.sum(theta[1:]**2)

    grad_ = list()

    grad_.append((1 / m) * np.sum([(H[j] - y[j][0]) for j in range(len(H))]))
    for i in range(len(theta)-1):
        grad_.append((1 / m) * np.sum([(H[j] - y[j]) * X[j][i+1] for j in range(len(H))]) + (lambda_ / m) * theta[i+1])

    return J, grad_



def TrainLinearReg(X, y, theta, lambda_, alpha, iter):

    JHistory = list()
    for i in range(iter):
        J, grad = CostRegFunction(X, y, theta, Lambda_)
        JHistory.append(J)
        for j in range(len(theta)):
            theta[j] = theta[j] - alpha * grad[j]

    return theta, JHistory

Theta, JH = TrainLinearReg(X, y, th, Lambda_, 0.01, 50)

但是当我尝试学习 theta 时,这段代码让我的 theta 和 J 的值有了很大的增长。 例如第一次迭代 grad = [-15.12452, 598.435436] - 这是正确的。 J 是 303.3255 第二次迭代 - grad = [10.23566,-3646.2345] J = 7924 依此类推,J 增长得越来越快,但根据 LR 的想法,它必须更低。

但是如果我使用 Normal Linear Equation 给我一个很好的 Theta。

这段代码有什么问题?

最佳答案

numpy 版本

. 10月17日编辑

我使用 numpy 库重写了部分代码。

所有向量现在都是列 numpy 数组。

import numpy as np
from copy import deepcopy as dc
from matplotlib import pyplot as plt

_norm = np.linalg.norm    

def CostRegFunction(X, y, theta, lambda_):
    m = len(X)
    H = np.dot(X,theta)
    J = (1 / (2 * m)) * _norm(H-y)**2 + (lambda_ / (2 * m)) * _normal(theta[1:])**2
    grad_ = np.array(sum(H-y)/m,ndmin=2).T
    for i in range(theta.shape[0]-1):
        grad_=np.concatenate((grad_,np.array(sum((H-y)*np.array(X[:,1],ndmin=2).T)/m + (lambda_/m) * theta[i+1],ndmin=2).T),0)
    return J, grad_

def TrainLinearReg(X, y, theta, lambda_, alpha, iter):
    JHistory = list()
    # add bias unit -> it's better to do it here, before entering the loop
    X = np.concatenate((np.ones((X.shape[0],1)),X),1)
    for i in range(iter):
        J, grad = CostRegFunction(X, y, theta, lambda_)
        JHistory.append(J)
        theta = theta -  alpha*grad
    return theta, JHistory

然后我用白噪声生成了一组简单的 x-y 多项式数据,并使用 TrainLinearReg 函数拟合多项式方程。

x = np.concatenate((np.array(np.linspace(0,10,100) + np.random.normal(0,0.01,100),ndmin=2).T,\
np.array(np.linspace(0,10,100)**2 + np.random.normal(0,0.01,100),ndmin=2).T),1)
y = 2 + -3*np.array(x[:,0],ndmin=2).T + np.random.normal(0,3,[100,1]) - 2*np.array(x[:,1],ndmin=2).T
th = np.array([1,2,3],ndmin=2).T
alpha = 0.001
lambda_ = 0.1
Theta, JH = TrainLinearReg(x, y, dc(th), lambda_, alpha, 10000)

我得到的是以下内容。

plt.plot(x[:,0],y,'o',label='Original Data',alpha = 0.5)
x2 = np.linspace(0,10,10)
plt.plot(x2,Theta[0]+x2*Theta[1]+x2**2*Theta[2],'-',label='Fitted     Curve',lw=1.5,alpha=0.8,color='black')
plt.gca().set_xlabel('x')
plt.gca().set_ylabel('y')
plt.legend()

Output >> Theta = array([[ 1.29259285],
                         [-2.97763304],
                         [-1.98758321]])

enter image description here

希望对您有所帮助。

最好的问候, 加布里埃尔

关于python - 这段用于正则化线性回归的 Python 代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17696797/

相关文章:

python - 计算多列的百分比

python - exec() 方法中自定义命名空间的子类 python 字典

python - Python 线程中的死锁

c++ - 插入跳表

Java Concurrent - 没有 speedUp 获得 LU 算法 - 虚假共享?

Python 使用 curve_fit 拟合对数函数

python - 替换数组中的值

python - 如何按照我需要的方式 reshape 这个数组?

c++ - 骑士之旅回溯无限循环

numpy - 使用 cProfile 分析 numpy 没有给出有用的结果