How to force zero interception in linear regression?

前端 未结 2 819
心在旅途
心在旅途 2021-02-12 04:15

I\'m a bit of a newby so apologies if this question has already been answered, I\'ve had a look and couldn\'t find specifically what I was looking for.

I have some more

2条回答
  •  一生所求
    2021-02-12 04:49

    I am not adept at these modules, but I have some experience in statistics, so here is what I see. You need to change your fit function from

    fitfunc = lambda params, x: params[0] * x + params[1]  
    

    to:

    fitfunc = lambda params, x: params[0] * x 
    

    Also remove the line:

    init_b = min(y) 
    

    And change the next line to:

    init_p = numpy.array((init_a))
    

    This should get rid of the second parameter that is producing the y-intercept and pass the fitted line through the origin. There might be a couple more minor alterations you might have to do for this in the rest of your code.

    But yes, I'm not sure if this module will work if you just pluck the second parameter away like this. It depends on the internal workings of the module as to whether it can accept this modification. For example, I don't know where params, the list of parameters, is being initialized, so I don't know if doing just this will change its length.

    And as an aside, since you mentioned, this I actually think is a bit of an over-the-top way to optimize just a slope. You could read up linear regression a little and write small code to do it yourself after some back-of-the envelope calculus. It's pretty simple and straightforward, really. In fact, I just did some calculations, and I guess the optimized slope will just be /, i.e. the mean of x*y products divided by the mean of x^2's.

提交回复
热议问题