python - 如何根据线性回归中的迭代次数绘制成本函数?
问题描述
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,
...]
解决方案
推荐阅读
- postgresql - 有什么方法可以更好地使用 postgis 索引地理查询以提高查询性能
- ternary - 需要一些帮助来重构三元
- flutter - 标签未满时如何禁用滚动?
- javascript - 允许更多 WebGL 上下文
- swiftui - SwiftUI 禁用视图的自动旋转
- ios - 如何通过循环 swift 5 为滚动视图内的 imageView 设置 trailingAnchor.constraint
- ios - 适合用于后台获取?
- r - 如何在过滤功能中使用应用
- c++11 - travis 仅构建失败:使用已删除的函数 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&)
- javascript - 如何使用 javascript 专注于谷歌自定义搜索引擎字段?