kinder chen
kinder chen

Reputation: 1461

how to use numpy polyfit to force scatter points linear fit pass through zero?

x=np.asarray([1,2,4,5,7,8,9])
y=np.asarray([2,1,3,6,4,7,9])

m,b=np.polyfit(x,y,1)

I have scatter points and try to do a linear fit (y = m*x + b, b = 0) by numpy polyfit. Is there a way to force interception b to be 0? Can I also have the variance?

I googled and someone said np.linalg.lstsq may work but I don't know how to manipulate it. And I prefer np.polyfit. Can it work?

Upvotes: 0

Views: 3076

Answers (2)

Daniel F
Daniel F

Reputation: 14399

No. np.polyfit doesn't have a method for removing lower order terms. Here's how you do it with np.linlg.lstsq:

m = np.linalg.lstsq(x.reshape(-1,1), y)[0][0]
m

0.87916666666666654

This is not the same as:

np.mean(y/x)

0.98520408163265305

Upvotes: 2

Colin Dickie
Colin Dickie

Reputation: 910

Linear Algebra maybe overkill here:

m = np.mean(y/x)

Will do the job fine for an unweighted correlation.

Upvotes: 0

Related Questions