【问题标题】:Quadratic hypothesis in linear regression always goes wrong线性回归中的二次假设总是出错
【发布时间】:2020-05-11 15:57:18
【问题描述】:

我是初学者,代码纯粹是实验性的,可能会给您带来不便,对此深表歉意(例如:我在 for 循环中使用了大量的连续循环)

假设形式为:- ax^2+bx+c,参数为a、b、c。

测试数据和输出

x=[10,20,30,40,50]
y=[-50,-90,-130,-170,-210]

假设函数

def h(m):
    return a*(x[m]**2)+b*x[m]+c

更改参数

for i in range(1,300000000):
    for j in range (0,4):
        c1=c1+(h(j)-y[j])
        b1=b1+(h(j)-y[j])*(x[j])
        a1=a1+(h(j)-y[j])*(x[j])**2

a=a-0.00000046*0.20*a1
b=b-0.00000046*0.20*b1
c=c-0.00000046*0.20*c1

成本函数

for k in range(0, 4):
    s = s + (h(k) - y[k])**2
cost=1/5*s

答案应该是 a=0、b=-4 和 c=-10 但我得到 a=0.02(每次循环后都会增加)、b=-5.4946 和 c=11 当成本约为 2 时(我没有'实际上并没有结束代码执行,很抱歉给您带来不便)

我哪里做错了?

【问题讨论】:

    标签: python machine-learning linear-regression


    【解决方案1】:

    您几乎做对了一切,只有两个问题。请参阅内联 cmets:

    # reliance on global/upper scope variables is a bad practice
    def h(a, b, c, value):
        return a*(value**2)+b*value+c
    
    # don't repeat yourself - define it in one place rather than 3
    lr = 0.00000046*0.20  # learning rate
    for i in range(1,300000000):
    
        # first issue: a1, b1 and c1 need to be reset
        a1 = b1 = c1 = 0
    
        # hardcoding magic constants (including data shape) is a bad practice
        for x_, y_ in range zip(x, y):
            diff = h(a, b, c, x_)-y_
            c1 += diff
            b1 += diff * x[j]
            a1 += diff * x[j]**2
    
        # second issue: this needs to be done every "batch"
        a -= lr * a1
        b -= lr * b1
        c -= lr * c1
    

    这在向量形式中会更有效,但我希望你明白

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2018-07-18
      • 2020-06-18
      • 2022-09-09
      • 1970-01-01
      • 2015-05-17
      • 2017-10-07
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多