Robin Romero
Robin Romero

Reputation: 23

how to do a linear fit where my variable X is vector in 3d?

I need to do a linear fit as follows:

Y=a*X+b

I need to find the values ​​of a and b that fit the experimental data the first thing that occurred to me was to use the polyfit function, but the problem is that in my data, X is a vector with 3 entries,

this is my code:

p_0=np.array([10,10,10])
p_1=np.array([100,10,10])
p_2=np.array([10,100,10])
p_3=np.array([10,10,100])

# Experimental data:
x=np.array([p_0,p_1,p_2,p_3])
y=np.array([35,60,75,65])

a=np.polyfit(x, y,1)
print(a)

I was expecting a list of lists to print, with the matrix and matrix b ... but I got TypeError("expected 1D vector for x")

Is there any way to do this with numpy or some other library?

Upvotes: 2

Views: 300

Answers (2)

anon01
anon01

Reputation: 11161

sklearn can be used for this:

import numpy as np
from sklearn.linear_model import LinearRegression

model = LinearRegression()

p_0=np.array([10,10,10])
p_1=np.array([100,10,10])
p_2=np.array([10,100,10])
p_3=np.array([10,10,100])

# Experimental data:
x=np.array([p_0,p_1,p_2,p_3])
y=np.array([35,60,75,65])

model.fit(X=x, y=y)

print("coeff: ", *model.coef_)
print("intercept: ", model.intercept_)

output:

coeff:  0.27777777777777785 0.44444444444444464 0.33333333333333337
intercept:  24.444444444444436

A few other nice features of the sklearn package:

model.fit(x,y) # 1.0
model.rank_ # 3
model.predict([[1,2,3]]) # array([26.61111111])

Upvotes: 3

Mahdi
Mahdi

Reputation: 3238

One way to go about this is using numpy.linalg.lstsq:

# Experimental data:
x=np.array([p_0,p_1,p_2,p_3])
y=np.array([35,60,75,65])
A = np.column_stack([x, np.ones(len(x))])
coefs = np.linalg.lstsq(A, y)[0]
print (coefs)
# 0.27777778  0.44444444  0.33333333 24.44444444

Another option is to use LinearRegression from sklearn:

from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(x, y)
print (reg.coef_, reg.intercept_)
# array([0.27777778, 0.44444444, 0.33333333]), 24.444444444444443

Upvotes: 2

Related Questions