2012-06-11 2 views
17

나는 많은 샘플을 가지고있다. y은 어느 정도까지 다항식으로 변하는 것으로 추정된다. 주어진 데이터 세트에 대한 예와도 2의 전 모델numpy의 다 변수 다항식 회귀

y = a^2 + 2ab - 3cb + c^2 +.5ac

이 최소 제곱을 사용하여 수행하고 NumPy와의 polyfit 루틴의 약간 확장 할 수 있습니다를 생성 할 수도 있습니다. 파이썬 생태계 어딘가에 표준 구현이 있습니까?

+2

이 문제를 해결하기 위해 코드를 게시했습니다. [https://github.com/mrocklin/multipolyfit](https://github.com/mrocklin/multipolyfit) – MRocklin

답변

2

polyfit은 작동하지만 더 나은 최소 사각형 최소화 기가 있습니다. 나는 그것은 그 polyfit 더 강력

http://www.astro.rug.nl/software/kapteyn-beta/kmpfittutorial.html

에서 사용할 수 kmpfit을 추천하고, 2 차를하는 기초를 제공해야하는 간단한 선형 피팅을 수행하는 방법을 보여줍니다 자신의 페이지에 대한 예제가있다 다항식 적합.

 

def model(p, v, x, w):  
    a,b,c,d,e,f,g,h,i,j,k = p  #coefficients to the polynomials  
    return a*v**2 + b*x**2 + c*w**2 + d*v*x + e*v*w + f*x*w + g*v + h*x + i*y + k 

def residuals(p, data):  # Function needed by fit routine 
    v, x, w, z = data   # The values for v, x, w and the measured hypersurface z 
    a,b,c,d,e,f,g,h,i,j,k = p #coefficients to the polynomials 
    return (z-model(p,v,x,w)) # Returns an array of residuals. 
           #This should (z-model(p,v,x,w))/err if 
           # there are error bars on the measured z values 


#initial guess at parameters. Avoid using 0.0 as initial guess 
par0 = [1.0, 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0] 

#create a fitting object. data should be in the form 
#that the functions above are looking for, i.e. a Nx4 
#list of lists/tuples like (v,x,w,z) 
fitobj = kmpfit.Fitter(residuals=residuals, data=data) 

# call the fitter 
fitobj.fit(params0=par0) 

이 일의 성공은 적합의 시작 값에 밀접하게 의존

, 그래서주의 깊게 가능하면 선택했다. 무료 매개 변수가 너무 많아서 솔루션을 얻는 것이 어려울 수 있습니다.

+1

polyfit을 사용하여 다 변수 회귀의 예를 게시 할 수 있습니까? ? 나는 이것이 지원된다고 확신하지 않는다. kmpfit에 대한 문서를 살펴본 후이 라이브러리에 대해서도 마찬가지 일 수 있습니다. – MRocklin

+0

무엇을 맞추려고합니까? y (x) = a * x ** 2 + b * x + c? 어쨌든, 당신은 확실히 mpfit/kmpfit로 다 변수 피팅을 할 수 있습니다. – reptilicus

+0

아니요, y (v, x, w) = a * v ** 2 + b * x ** 2 + c * w ** 2 + d * v * x + e * v * w + f * x * w + g * v + h * x + i * y + k – MRocklin

8

sklearn은이를 수행하는 간단한 방법을 제공합니다.

#X is the independent variable (bivariate in this case) 
X = array([[0.44, 0.68], [0.99, 0.23]]) 

#vector is the dependent data 
vector = [109.85, 155.72] 

#predict is an independent variable for which we'd like to predict the value 
predict= [0.49, 0.18] 

#generate a model of polynomial features 
poly = PolynomialFeatures(degree=2) 

#transform the x data for proper fitting (for single variable type it returns,[1,x,x**2]) 
X_ = poly.fit_transform(X) 

#transform the prediction to fit the model type 
predict_ = poly.fit_transform(predict) 

#here we can remove polynomial orders we don't want 
#for instance I'm removing the `x` component 
X_ = np.delete(X_,(1),axis=1) 
predict_ = np.delete(predict_,(1),axis=1) 

#generate the regression object 
clf = linear_model.LinearRegression() 
#preform the actual regression 
clf.fit(X_, vector) 

print("X_ = ",X_) 
print("predict_ = ",predict_) 
print("Prediction = ",clf.predict(predict_)) 

그리고 heres는 출력 :

here을 기록하는 예를 구축

>>> X_ = [[ 0.44 0.68 0.1936 0.2992 0.4624] 
>>> [ 0.99 0.23 0.9801 0.2277 0.0529]] 
>>> predict_ = [[ 0.49 0.18 0.2401 0.0882 0.0324]] 
>>> Prediction = [ 126.84247142] 
+0

'delete' 함수의 구현을 포함시킬 수 있습니까? 건배! –

+1

죄송합니다, numpy입니다, https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html –

+0

'PolynomialFeatures'는 명시 적으로 무엇을합니까? 코드를 볼 수 있습니까? –

0

sklearn는 파이프 라인 here를 사용하여 좋은 예제가 실려있다. - 단지 파이프 라인으로 전달 당신은 당신의 데이터를 직접 변환 할 필요가 없습니다

polynomial_features = PolynomialFeatures(degree=degrees[i], 
             include_bias=False) 
linear_regression = LinearRegression() 
pipeline = Pipeline([("polynomial_features", polynomial_features), 
        ("linear_regression", linear_regression)]) 
pipeline.fit(X[:, np.newaxis], y) 

: 여기에 자신의 예를의 핵심입니다.

+3

그 예는 다 변수 회귀를 사용하지 않습니다. –