首页 > 解决方案 > 如何根据线性回归中的迭代次数绘制成本函数?

问题描述

def computecost(x,y,theta):
    m = x.shape[0]
    dot = np.dot(x,theta)-y
    temp = np.sum(np.power(dot,2))
    res = temp/(2*m)
    return res

j = computecost(population, profit, theta) 
#j returns a cost of 32 after running the cost function for the first time.

下面是我的梯度下降函数,它接受 x、y、theta、alpha(学习率)和迭代。它在 for 循环中调用成本函数并将参数附加到列表 cost_history 中,函数返回参数和 li。

def gdescent(x,y,parameter,alpha,itera):
    m = x.shape[0]
    cost_history=[]
    for i in range(itera):
        temp = np.dot(x,parameter)-y
        res = np.dot(x.T,temp)
        parameter = parameter - ((alpha/m)*(np.sum(res)))
        j = compute_cost(x,y,parameter)
        li.append(j)
    return parameter, li
        
iterations = 1500
alpha = 0.1
    
theta, cost_hist = gdescent(population,profit,theta,alpha,iterations)   
#this returns optimized values of [[5.21608809],[5.21608809]] for theta.

j = computecost(population,profit,theta)
#computcost returns a reduced cost function of 4.8.

这两个函数都正常工作,并且该行最适合数据,但我无法将成本函数(计算成本)的值附加到下降函数内的列表(li)中。每当我打印 cost_hist 时,我都会得到这个巨大的数组。

[4.865158889208666,
 4.865158889208666,
 4.865158889208666,
 4.865158889208666,
 4.865158889208666,
 ...]

标签: pythonmachine-learninglinear-regression

解决方案


推荐阅读