同时更新 theta0 和 theta1 以计算 python 中的梯度下降

Ser*_*ity 4 python numpy machine-learning linear-regression gradient-descent

我正在学习 Coursera 的机器学习课程。有一个主题叫梯度下降来优化成本函数。它表示同时更新 theta0 和 theta1,从而最小化成本函数并达到全局最小值。

梯度下降的公式为

在此输入图像描述

我如何使用 python 以编程方式执行此操作?我正在使用 numpy 数组和 pandas 从头开始​​逐步理解其逻辑。

现在我只计算了成本函数

# step 1 - collect our data
data = pd.read_csv("datasets.txt", header=None)

def compute_cost_function(x, y, theta):
    '''
        Taking in a numpy array x, y, theta and generate the cost function
    '''
    m = len(y)
    # formula for prediction = theta0 + theta1.x
    predictions = x.dot(theta)
    # formula for square error = ((theta1.x + theta0) - y)**2
    square_error = (predictions - y)**2
    # sum of square error function
    return 1/(2*m) * np.sum(square_error)

# converts into numpy represetation of the pandas dataframe. The axes labels will be excluded
numpy_data = data.values
m = data[0].size
x = np.append(np.ones((m, 1)), numpy_data[:, 0].reshape(m, 1), axis=1)
y = numpy_data[:, 1].reshape(m, 1)
theta = np.zeros((2, 1))

compute_cost_function(x, y, theta)

def gradient_descent(x, y, theta, alpha):
    '''
        simultaneously update theta0 and theta1 where 
        theta0 = theta0 - apha * 1/m * (sum of square error)
    '''
    pass
Run Code Online (Sandbox Code Playgroud)

我知道我必须compute_cost_function从梯度下降中调用它,但无法应用该公式。

ray*_*ica 5

这意味着您使用参数的先前值并计算右侧所需的值。完成后,更新参数。为了最清楚地做到这一点,请在函数内创建一个临时数组,将结果存储在右侧,并在完成时返回计算结果。

def gradient_descent(x, y, theta, alpha):
    ''' simultaneously update theta0 and theta1 where
        theta0 = theta0 - apha * 1/m * (sum of square error) ''' 
    theta_return = np.zeros((2, 1))
    theta_return[0] = theta[0] - (alpha / m) * ((x.dot(theta) - y).sum())
    theta_return[1] = theta[1] - (alpha / m) * (((x.dot(theta) - y)*x[:, 1][:, None]).sum())

    return theta_return
Run Code Online (Sandbox Code Playgroud)

我们首先声明临时数组,然后分别计算参数的每个部分,即截距和斜率,然后返回我们需要的值。上面代码的好处是我们将其矢量化。对于截距项,x.dot(theta)在拥有数据矩阵x和参数向量 的情况下执行矩阵向量乘法theta。通过用输出值减去这个结果y,我们计算预测值和真实值之间所有误差的总和,然后乘以学习率,然后除以样本数。我们对斜率项做了类似的事情,只是我们另外乘以每个输入值而不使用偏差项。我们还需要确保输入值位于沿x1D NumPy 数组而不是具有单列的 2D 结果的第二列切片时的列中。这使得元素乘法可以很好地结合在一起。

还要注意的一件事是,更新参数时根本不需要计算成本。请注意,在优化循环中,最好在更新参数时调用它,这样您就可以看到参数从数据中学习的效果如何。


为了使其真正矢量化,从而利用同步更新,您可以将其表示为仅训练示例的矩阵向量乘法:

def gradient_descent(x, y, theta, alpha):
    ''' simultaneously update theta0 and theta1 where
        theta0 = theta0 - apha * 1/m * (sum of square error) ''' 
    return theta - (alpha / m) * x.T.dot(x.dot(theta) - y)
Run Code Online (Sandbox Code Playgroud)

它的作用是,当我们计算 时x.dot(theta),它会计算出预测值,然后我们通过减去预期值来将其结合起来。这会产生误差向量。当我们预乘 的转置时x,最终发生的是我们获取误差向量并执行向量化求和,使得转置矩阵的第一行x对应于 1 的值,这意味着我们只是将所有误差项为我们提供了偏差或截距项的更新。类似地,转置矩阵的第二行x还通过相应的样本值对每个误差项进行加权x(没有偏差项 1),并以这种方式计算总和。结果是一个 2 x 1 向量,当我们减去之前的参数值并根据学习率和样本数进行加权时,它为我们提供了最终更新。


我没有意识到您将代码放入迭代框架中。在这种情况下,您需要在每次迭代时更新参数。

def gradient_descent(x, y, theta, alpha, iterations):

    ''' simultaneously update theta0 and theta1 where
    theta0 = theta0 - apha * 1/m * (sum of square error) ''' 

    theta_return = np.zeros((2, 1))
    for i in range(iterations):
        theta_return[0] = theta[0] - (alpha / m) * ((x.dot(theta) - y).sum())
        theta_return[1] = theta[1] - (alpha / m) * (((x.dot(theta) - y)*x[:, 1][:, None]).sum())
        theta = theta_return

    return theta

theta = gradient_descent(x, y, theta, 0.01, 1000)
Run Code Online (Sandbox Code Playgroud)

在每次迭代中,您更新参数,然后正确设置它,以便下一次,当前更新成为以前的更新。